repo_id
stringclasses
1 value
file_path
stringlengths
117
174
content
stringlengths
8
42.4k
__index_level_0__
int64
0
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/util/SQLiteDatabaseHelper.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.util; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteStatement; import com.adobe.marketing.mobile.internal.CoreConstants; import com.adobe.marketing.mobile.services.Log; import java.io.File; /** Helper class for performing atomic operation on SQLite Database. */ public class SQLiteDatabaseHelper { private static final String LOG_PREFIX = "SQLiteDatabaseHelper"; private SQLiteDatabaseHelper() {} /** * Creates the Table if not already exists in database. * * @param dbPath the path to Database. * @param query the query for creating table. * @return true if successfully created table else false. */ public static boolean createTableIfNotExist(final String dbPath, final String query) { SQLiteDatabase database = null; try { database = openDatabase(dbPath, DatabaseOpenMode.READ_WRITE); database.execSQL(query); return true; } catch (final SQLiteException e) { Log.warning( CoreConstants.LOG_TAG, LOG_PREFIX, String.format( "createTableIfNotExists - Error in creating/accessing database (%s)." + "Error: (%s)", dbPath, e.getMessage())); return false; } finally { closeDatabase(database); } } /** * Returns the count of rows in table @tableName * * @param dbPath path to database * @param tableName name of table to calculate size of. * @return number of rows in Table @tableName. */ public static int getTableSize(final String dbPath, final String tableName) { SQLiteDatabase database = null; try { database = openDatabase(dbPath, DatabaseOpenMode.READ_ONLY); SQLiteStatement selectStatement = database.compileStatement("Select Count (*) from " + tableName); return (int) selectStatement.simpleQueryForLong(); } catch (final SQLiteException e) { Log.warning( CoreConstants.LOG_TAG, LOG_PREFIX, String.format( "getTableSize - Error in querying table(%s) size from database(%s)." + "Returning 0. Error: (%s)", tableName, dbPath, e.getMessage())); return 0; } finally { closeDatabase(database); } } /** * Deletes all the rows in table. * * @param dbPath path to database. * @param tableName name of table to empty. * @return true if successfully clears the table else returns false. */ public static boolean clearTable(final String dbPath, final String tableName) { SQLiteDatabase database = null; try { database = openDatabase(dbPath, DatabaseOpenMode.READ_WRITE); database.delete(tableName, "1", null); return true; } catch (final SQLiteException e) { Log.warning( CoreConstants.LOG_TAG, LOG_PREFIX, String.format( "clearTable - Error in clearing table(%s) from database(%s)." + "Returning false. Error: (%s)", tableName, dbPath, e.getMessage())); return false; } finally { closeDatabase(database); } } /** * Opens the database exists at path @filePath. If database doesn't exist than creates the new * one. * * @param filePath the absolute path to database. * @param dbOpenMode an instance of {@link DatabaseOpenMode} * @return an instance of {@link SQLiteDatabase} to interact with database. * @throws SQLiteException if there is an error in opening database. */ public static SQLiteDatabase openDatabase( final String filePath, final DatabaseOpenMode dbOpenMode) throws SQLiteException { if (filePath == null || filePath.isEmpty()) { Log.debug( CoreConstants.LOG_TAG, LOG_PREFIX, "openDatabase - Failed to open database - filepath is null or empty"); throw new SQLiteException("Invalid database path. Database path is null or empty."); } // Create parent directory if it don't exist. try { File databasePath = new File(filePath); File parentDir = databasePath.getParentFile(); if (parentDir != null && !parentDir.exists()) { Log.debug( CoreConstants.LOG_TAG, LOG_PREFIX, "openDatabase - Creating parent directory (%s)", parentDir.getPath()); parentDir.mkdirs(); } } catch (Exception ex) { Log.debug( CoreConstants.LOG_TAG, LOG_PREFIX, "openDatabase - Failed to create parent directory for path (%s)", filePath); throw new SQLiteException( "Invalid database path. Unable to create parent directory for database."); } SQLiteDatabase database = SQLiteDatabase.openDatabase( filePath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.CREATE_IF_NECESSARY | dbOpenMode.mode); Log.trace( CoreConstants.LOG_TAG, LOG_PREFIX, String.format( "openDatabase - Successfully opened the database at path (%s)", filePath)); return database; } /** * Closes the database. * * @param database, an instance of {@link SQLiteDatabase}, pointing to database to close. */ public static void closeDatabase(final SQLiteDatabase database) { if (database == null) { Log.debug( CoreConstants.LOG_TAG, LOG_PREFIX, "closeDatabase - Unable to close database, database passed is null."); return; } database.close(); Log.trace( CoreConstants.LOG_TAG, LOG_PREFIX, "closeDatabase - Successfully closed the database."); } /** * Open the database and begin processing database operations in {@link * DatabaseProcessing#execute(SQLiteDatabase)}, then disconnecting the database. * * @param filePath path to database * @param dbOpenMode an instance of {@link DatabaseOpenMode} * @param databaseProcessing the function interface to include database operations * @return the result of the {@link DatabaseProcessing#execute(SQLiteDatabase)} */ public static boolean process( final String filePath, final DatabaseOpenMode dbOpenMode, final DatabaseProcessing databaseProcessing) { SQLiteDatabase database = null; try { database = openDatabase(filePath, dbOpenMode); return databaseProcessing.execute(database); } catch (Exception e) { Log.warning( CoreConstants.LOG_TAG, LOG_PREFIX, "Failed to open database (%s). Error: %s", filePath, e.getLocalizedMessage()); return false; } finally { if (database != null) { closeDatabase(database); } } } /** * Enum type to pass to function open database. It determined whether to open Database * connection in READ only mode or READ WRITE mode. */ public enum DatabaseOpenMode { READ_ONLY(SQLiteDatabase.OPEN_READONLY), READ_WRITE(SQLiteDatabase.OPEN_READWRITE); final int mode; DatabaseOpenMode(final int mode) { this.mode = mode; } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/util/VisitorIDSerializer.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.util; import androidx.annotation.NonNull; import com.adobe.marketing.mobile.VisitorID; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** Utility class for serializing/deserializing {@link VisitorID} objects. */ public class VisitorIDSerializer { private static final String ID = "ID"; private static final String ID_ORIGIN = "ID_ORIGIN"; private static final String ID_TYPE = "ID_TYPE"; private static final String STATE = "STATE"; /** * Serializes the given {@link VisitorID} to a {@link Map}. * * @param visitorID {@link VisitorID} instance to serialize * @return a {@link Map} representing {@link VisitorID} properties */ public static Map<String, Object> convertVisitorId(@NonNull final VisitorID visitorID) { Map<String, Object> data = new HashMap<>(); data.put(ID, visitorID.getId()); data.put(ID_ORIGIN, visitorID.getIdOrigin()); data.put(ID_TYPE, visitorID.getIdType()); data.put(STATE, visitorID.getAuthenticationState().getValue()); return data; } /** * Serializes the given {@link VisitorID} list to a {@link Map} list. * * @param visitorIDList a list of {@link VisitorID} instances to serialize * @return a list of {@link Map} representing the given {@link VisitorID} properties */ public static List<Map<String, Object>> convertVisitorIds( @NonNull final List<VisitorID> visitorIDList) { List<Map<String, Object>> data = new ArrayList<>(); for (VisitorID vId : visitorIDList) { if (vId != null) { data.add(VisitorIDSerializer.convertVisitorId(vId)); } } return data; } /** * Deserializes the given map {@link List} to a list of {@link VisitorID}. * * @param data a list of {@link Map} to deserialize * @return a list of {@link VisitorID} that was deserialized from the property {@link Map} */ public static List<VisitorID> convertToVisitorIds(@NonNull final List<Map> data) { List<VisitorID> visitorIDList = new ArrayList<>(); for (Map item : data) { if (item != null) { String id = String.valueOf(item.get(ID)); String origin = String.valueOf(item.get(ID_ORIGIN)); String type = String.valueOf(item.get(ID_TYPE)); int state = Integer.parseInt(String.valueOf(item.get(STATE))); visitorIDList.add( new VisitorID( origin, type, id, VisitorID.AuthenticationState.fromInteger(state))); } } return visitorIDList; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/util/UrlEncoder.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.util import com.adobe.marketing.mobile.internal.CoreConstants import com.adobe.marketing.mobile.services.Log import java.io.UnsupportedEncodingException import java.nio.charset.StandardCharsets internal object UrlEncoder { private const val LOG_TAG = "UrlUtilities" // lookup tables used by urlEncode private val encodedChars = arrayOf( "%00", "%01", "%02", "%03", "%04", "%05", "%06", "%07", "%08", "%09", "%0A", "%0B", "%0C", "%0D", "%0E", "%0F", "%10", "%11", "%12", "%13", "%14", "%15", "%16", "%17", "%18", "%19", "%1A", "%1B", "%1C", "%1D", "%1E", "%1F", "%20", "%21", "%22", "%23", "%24", "%25", "%26", "%27", "%28", "%29", "%2A", "%2B", "%2C", "-", ".", "%2F", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "%3A", "%3B", "%3C", "%3D", "%3E", "%3F", "%40", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "%5B", "%5C", "%5D", "%5E", "_", "%60", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "%7B", "%7C", "%7D", "~", "%7F", "%80", "%81", "%82", "%83", "%84", "%85", "%86", "%87", "%88", "%89", "%8A", "%8B", "%8C", "%8D", "%8E", "%8F", "%90", "%91", "%92", "%93", "%94", "%95", "%96", "%97", "%98", "%99", "%9A", "%9B", "%9C", "%9D", "%9E", "%9F", "%A0", "%A1", "%A2", "%A3", "%A4", "%A5", "%A6", "%A7", "%A8", "%A9", "%AA", "%AB", "%AC", "%AD", "%AE", "%AF", "%B0", "%B1", "%B2", "%B3", "%B4", "%B5", "%B6", "%B7", "%B8", "%B9", "%BA", "%BB", "%BC", "%BD", "%BE", "%BF", "%C0", "%C1", "%C2", "%C3", "%C4", "%C5", "%C6", "%C7", "%C8", "%C9", "%CA", "%CB", "%CC", "%CD", "%CE", "%CF", "%D0", "%D1", "%D2", "%D3", "%D4", "%D5", "%D6", "%D7", "%D8", "%D9", "%DA", "%DB", "%DC", "%DD", "%DE", "%DF", "%E0", "%E1", "%E2", "%E3", "%E4", "%E5", "%E6", "%E7", "%E8", "%E9", "%EA", "%EB", "%EC", "%ED", "%EE", "%EF", "%F0", "%F1", "%F2", "%F3", "%F4", "%F5", "%F6", "%F7", "%F8", "%F9", "%FA", "%FB", "%FC", "%FD", "%FE", "%FF" ) private const val ALL_BITS_ENABLED = 0xFF private val utf8Mask = booleanArrayOf( false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, false, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false ) /** * Encodes an URL given as [String] * * @param [unencodedString] nullable [String] value to be encoded * @return [String] which is URL encoded or null if encoding failed */ @JvmStatic fun urlEncode(unencodedString: String?): String? { // bail fast return if (unencodedString == null) { null } else { try { val stringBytes = unencodedString.toByteArray(charset("UTF-8")) val len = stringBytes.size var curIndex = 0 // iterate looking for any characters that don't match our "safe" mask while (curIndex < len && utf8Mask[stringBytes[curIndex].toInt() and ALL_BITS_ENABLED]) { curIndex++ } // if our iterator got all the way to the end of the string, no unsafe characters existed // and it's safe to return the original value that was passed in if (curIndex == len) { return unencodedString } // if we get here we know there's at least one character we need to encode val encodedString = StringBuilder(stringBytes.size shl 1) // if i > than 1 then we have some characters we can just "paste" in if (curIndex > 0) { encodedString.append(String(stringBytes, 0, curIndex, StandardCharsets.UTF_8)) } // rip through the rest of the string character by character while (curIndex < len) { encodedString.append(encodedChars[stringBytes[curIndex].toInt() and ALL_BITS_ENABLED]) curIndex++ } // return the completed string encodedString.toString() } catch (e: UnsupportedEncodingException) { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Failed to url encode string $unencodedString $e" ) null } } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/util/NetworkUtils.kt
/* Copyright 2024 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ @file:JvmName("NetworkUtils") package com.adobe.marketing.mobile.internal.util import android.net.ConnectivityManager import android.net.NetworkCapabilities import android.os.Build /** * Checks if the network is configured to reach the general Internet. * * @param connectivityManager the [ConnectivityManager] to use to check the network status * @return `true` if the network is configured to reach the general Internet, `false` otherwise */ @JvmName("isInternetAvailable") internal fun isInternetAvailable(connectivityManager: ConnectivityManager): Boolean { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // The getActiveNetwork() API was introduced in API version 23. val network = connectivityManager.activeNetwork ?: return false val activeCapabilities = connectivityManager.getNetworkCapabilities(network) ?: return false return activeCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) } else { val networkInfo = connectivityManager.activeNetworkInfo ?: return false return networkInfo.isConnected } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/util/StringEncoder.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.util; import com.adobe.marketing.mobile.internal.CoreConstants; import com.adobe.marketing.mobile.services.Log; import com.adobe.marketing.mobile.util.StringUtils; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** Utility class for {@code String} related encoding methods */ public final class StringEncoder { private static final String LOG_TAG = "StringEncoder"; private static final char[] hexArray = "0123456789abcdef".toCharArray(); private static final int ALL_BITS_ENABLED = 0xFF; private static final int SHIFT_BY = 4; private static final int HEX_CHAR_MULTIPLIER = 0x0F; private static final int HEX_RADIX = 16; private static final int PRIME = 0x1000193; // 16777619 as hex private static final int OFFSET = 0x811c9dc5; // 2166136261 as hex private static final int LSB_8_MASK = 0xFF; private static final char[] BYTE_TO_HEX = ("000102030405060708090A0B0C0D0E0F" + "101112131415161718191A1B1C1D1E1F" + "202122232425262728292A2B2C2D2E2F" + "303132333435363738393A3B3C3D3E3F" + "404142434445464748494A4B4C4D4E4F" + "505152535455565758595A5B5C5D5E5F" + "606162636465666768696A6B6C6D6E6F" + "707172737475767778797A7B7C7D7E7F" + "808182838485868788898A8B8C8D8E8F" + "909192939495969798999A9B9C9D9E9F" + "A0A1A2A3A4A5A6A7A8A9AAABACADAEAF" + "B0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF" + "C0C1C2C3C4C5C6C7C8C9CACBCCCDCECF" + "D0D1D2D3D4D5D6D7D8D9DADBDCDDDEDF" + "E0E1E2E3E4E5E6E7E8E9EAEBECEDEEEF" + "F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF") .toCharArray(); private static final int OXFF = 0xFF; private StringEncoder() {} public static String getSha1HashedString(final String inputString) { if (inputString == null || inputString.isEmpty()) { return null; } String hash = null; try { final MessageDigest digest = MessageDigest.getInstance("SHA-1"); byte[] bytes = inputString.getBytes(StandardCharsets.UTF_8); digest.update(bytes, 0, bytes.length); bytes = digest.digest(); char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & ALL_BITS_ENABLED; hexChars[j * 2] = hexArray[v >>> SHIFT_BY]; hexChars[j * 2 + 1] = hexArray[v & HEX_CHAR_MULTIPLIER]; } hash = new String(hexChars); } catch (final NoSuchAlgorithmException ex) { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Error while attempting to encode a string (%s)" + ex); } return hash; } /** * Converts the given {@code String} into a decimal representation of the signed 2's complement * FNV1a 32-bit hash. * * @param inputString {@code String} containing to be hashed * @return a {@link long} containing the decimal FNV1a 32-bit hash */ public static long convertStringToDecimalHash(final String inputString) { final int hash = getFnv1aHash(inputString); // convert signed 2's complement hash to hex string final String hexHash = Integer.toHexString(hash); return Long.parseLong(hexHash, HEX_RADIX); } /** * Converts the given {@code String} to a signed 2's complement FNV1a 32-bit hash. * * <p>https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function Online * validator - https://md5calc.com/hash/fnv1a32?str= * * @param input {@code String} to be hashed * @return a {@code int} containing the signed 2's complement FNV1a 32-bit hash */ private static int getFnv1aHash(final String input) { if (input == null) { return 0; } int hash = input.trim().isEmpty() ? 0 : OFFSET; final byte[] bytes = input.getBytes(); for (byte aByte : bytes) { hash ^= (aByte & ALL_BITS_ENABLED); hash *= PRIME; } return hash; } /** * Converts a string to hexadecimal notation * * @param originalString the string for which hexadecimal value is to be computed * @return hexadecimal representation of the string if valid, null otherwise */ public static String getHexString(final String originalString) { if (StringUtils.isNullOrEmpty(originalString)) { return null; } byte[] bytes = originalString.getBytes(StandardCharsets.UTF_8); final int bytesLength = bytes.length; final char[] chars = new char[bytesLength << 1]; int hexIndex; int index = 0; int offset = 0; while (offset < bytesLength) { hexIndex = (bytes[offset++] & OXFF) << 1; chars[index++] = BYTE_TO_HEX[hexIndex++]; chars[index++] = BYTE_TO_HEX[hexIndex]; } return new String(chars); } /** * Decodes a hexadecimal string * * @param hexString the hexadecimal string to be decoded * @return decoded hexadecimal string if valid, null otherwise */ public static String hexToString(final String hexString) { if (hexString == null || hexString.length() <= 0 || hexString.length() % 2 != 0) { return null; } final int length = hexString.length(); byte[] data = new byte[length / 2]; for (int i = 0; i < length; i += 2) { final int radix = 16; final int fourDigit = 4; data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), radix) << fourDigit) + Character.digit(hexString.charAt(i + 1), radix)); } String decodedString = new String(data, StandardCharsets.UTF_8); return decodedString; } /** * Computes the sha2 hash for the string * * @param input the string for which sha2 hash is to be computed * @return sha2 hash result if the string is valid, null otherwise */ public static String sha2hash(final String input) { if (input == null || input.isEmpty()) { return null; } try { final MessageDigest messagedigest = MessageDigest.getInstance("SHA-256"); messagedigest.update(input.getBytes(StandardCharsets.UTF_8)); final byte[] messageDigest = messagedigest.digest(); final StringBuilder sha2HexBuilder = new StringBuilder(); for (byte aMessageDigest : messageDigest) { StringBuilder hexString = new StringBuilder(Integer.toHexString(LSB_8_MASK & aMessageDigest)); while (hexString.length() < 2) { hexString.insert(0, "0"); } sha2HexBuilder.append(hexString); } return sha2HexBuilder.toString(); } catch (NoSuchAlgorithmException e) { Log.debug(CoreConstants.LOG_TAG, LOG_TAG, "Failed to create sha2 hash " + e); } return null; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/util/FileUtils.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.util import com.adobe.marketing.mobile.internal.CoreConstants import com.adobe.marketing.mobile.services.Log import java.io.BufferedReader import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.io.InputStream import java.io.InputStreamReader import java.util.zip.ZipInputStream internal object FileUtils { const val TAG = "FileUtils" private const val MAX_BUFFER_SIZE = 4096 /** * Verifies if the directory is writable * * @param directory the directory to check for * @return true if [directory] represents a directory and the directory is writable. * false otherwise */ @JvmStatic fun isWritableDirectory(directory: File?): Boolean { return directory != null && directory.isDirectory && directory.canWrite() } /** * Reads the content of [file] as a [String]. * * @param file the file whose contents need to be read * @return contents of the file as a string or, * null if the file cannot be read */ @JvmStatic fun readAsString(file: File?): String? { if (!isReadable(file)) { Log.debug( CoreConstants.LOG_TAG, TAG, "Failed to read file: ($file)" ) return null } val content = StringBuilder() try { BufferedReader(InputStreamReader(FileInputStream(file), Charsets.UTF_8)).use { br -> var line: String? while (br.readLine().also { line = it } != null) { content.append(line) } } } catch (e: Exception) { Log.debug( CoreConstants.LOG_TAG, TAG, "Failed to read $file contents. $e" ) return null } return content.toString() } /** * Checks if the [file] content can be read. * * @param file the source file whose readability is to be validated * @return true if [file] exists, is not null, is a file and has read permissions; * false otherwise */ @JvmStatic fun isReadable(file: File?): Boolean { try { if (file == null || !file.exists() || !file.canRead() || !file.isFile) { Log.debug( CoreConstants.LOG_TAG, TAG, "File does not exist or doesn't have read permission $file" ) return false } return true } catch (e: SecurityException) { Log.debug( CoreConstants.LOG_TAG, TAG, "Failed to read file ($e)" ) return false } } /** * Reads the content of [inputStream] into [file]. * * @param file the file whose contents need to be created/updated read from the [inputStream] * @param inputStream the [InputStream] from which the contents should be read * @param append if the contents of [inputStream] should be appended to the contents of [file] * @return true if the contents of the input stream were added to the file, * false otherwise */ @JvmStatic fun readInputStreamIntoFile(file: File?, inputStream: InputStream, append: Boolean): Boolean { return try { FileOutputStream(file, append).use { outputStream -> inputStream.copyTo(outputStream, MAX_BUFFER_SIZE) } true } catch (e: Exception) { Log.debug( CoreConstants.LOG_TAG, TAG, "Unexpected exception while attempting to write to file: ${file?.path} ($e)" ) false } } /** * Extracts the zip file to an output directory. * * @param zipFile the zip file that needs to be extracted * @param outputDirectoryPath the destination for the extracted [zipFile] contents * @return true if the zip file has been successfully extracted * false otherwise */ @JvmStatic fun extractFromZip(zipFile: File?, outputDirectoryPath: String): Boolean { if (zipFile == null) return false val folder = File(outputDirectoryPath) if (!folder.exists() && !folder.mkdir()) { Log.debug( CoreConstants.LOG_TAG, TAG, "Could not create the output directory $outputDirectoryPath" ) return false } var extractedSuccessfully = true try { ZipInputStream(FileInputStream(zipFile)).use { zipInputStream -> // get the zipped file list entry var ze = zipInputStream.nextEntry val outputFolderCanonicalPath = folder.canonicalPath if (ze == null) { // Invalid zip file! Log.debug( CoreConstants.LOG_TAG, TAG, "Zip file was invalid" ) return false } var entryProcessedSuccessfully = true while (ze != null && entryProcessedSuccessfully) { val fileName = ze.name val newZipEntryFile = File(outputDirectoryPath + File.separator + fileName) if (!newZipEntryFile.canonicalPath.startsWith(outputFolderCanonicalPath)) { Log.debug( CoreConstants.LOG_TAG, TAG, "The zip file contained an invalid path. Verify that your zip file is formatted correctly and has not been tampered with." ) return false } entryProcessedSuccessfully = if (ze.isDirectory) { // handle directory (newZipEntryFile.exists() || newZipEntryFile.mkdirs()) } else { // handle file val parentFolder = newZipEntryFile.parentFile if (parentFolder != null && (parentFolder.exists() || parentFolder.mkdirs())) { readInputStreamIntoFile(newZipEntryFile, zipInputStream, false) } else { Log.debug( CoreConstants.LOG_TAG, TAG, "Could not extract the file ${newZipEntryFile.absolutePath}" ) return false } } extractedSuccessfully = extractedSuccessfully && entryProcessedSuccessfully zipInputStream.closeEntry() ze = zipInputStream.nextEntry } zipInputStream.closeEntry() } } catch (ex: Exception) { Log.debug( CoreConstants.LOG_TAG, TAG, "Extraction failed - $ex" ) extractedSuccessfully = false } return extractedSuccessfully } /** * Removes the relative part of the file name(if exists). * * for ex: File name `/mydatabase/../../database1` will be converted to `mydatabase_database1` * * @param filePath the file name * @return file name without relative path */ @JvmStatic fun removeRelativePath(filePath: String): String { return if (filePath.isBlank()) { filePath } else { var result = filePath.replace("\\.[/\\\\]".toRegex(), "\\.") result = result.replace("[/\\\\](\\.{2,})".toRegex(), "_") result = result.replace("/".toRegex(), "") result } } /** * Copies the contents from `src` to `dest`. * * @param src [File] from which the contents are read * @param dest [File] to which contents are written to * @throws Exception if `src` or `dest` is not present or it does not have read permissions */ @JvmStatic @Throws(Exception::class) fun copyFile(src: File, dest: File) { src.copyTo(dest, true) } /** * Move file from `src` to `dest`. * * @param src [File] source file * @param dest [File] destination to move the file * @throws Exception if `src` is not present or it does not have read permissions */ @JvmStatic @Throws(Exception::class) fun moveFile(src: File, dest: File) { if (dest.parentFile != null && !dest.parentFile.exists()) { dest.parentFile.mkdirs() } if (!dest.exists()) { dest.createNewFile() } copyFile(src, dest) deleteFile(src, false) } /** * Deletes the file * * @param fileToDelete [File] which needs to be deleted * @param recursive [Boolean] if true, delete this file with all its children. * @throws SecurityException if it does not have permission to delete file */ @JvmStatic @Throws(SecurityException::class) fun deleteFile(fileToDelete: File?, recursive: Boolean): Boolean { if (fileToDelete == null) { return false } return if (recursive) fileToDelete.deleteRecursively() else fileToDelete.delete() } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/eventhub/EventPreprocessor.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.eventhub import com.adobe.marketing.mobile.Event fun interface EventPreprocessor { fun process(event: Event): Event }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/eventhub/SharedStateManager.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.eventhub import com.adobe.marketing.mobile.SharedStateResult import com.adobe.marketing.mobile.SharedStateStatus import com.adobe.marketing.mobile.internal.CoreConstants import com.adobe.marketing.mobile.services.Log import java.util.TreeMap /** * Internal representation of a shared event state. * Allows associating version and pending behavior with the state data in a queryable way. */ private data class SharedState constructor(val version: Int, val status: SharedStateStatus, val data: Map<String, Any?>?) { fun getResult(): SharedStateResult = SharedStateResult(status, data) } /** * Represents the types of shared state that are supported. */ internal enum class SharedStateType { STANDARD, XDM } /** * Responsible for managing the shared state operations for an extension. * Employs a red-black tree to store the state data and their versions * The knowledge of whether or not a state is pending is deferred to the caller to ensure this class * is decoupled from the rules for a pending state. * * Note that the methods in this class fall on the public ExtensionApi path and, changes to method * behaviors may impact the shared state API behavior. */ internal class SharedStateManager(private val name: String) { private val LOG_TAG = "SharedStateManager($name)" /** * A mapping between the version of the state to the state. */ private val states: TreeMap<Int, SharedState> = TreeMap<Int, SharedState>() companion object { const val VERSION_LATEST: Int = Int.MAX_VALUE } /** * Sets the shared state for the extension at [version] as [data] if it does not already exist. * * @param version the version of the shared state to be created * @param data the content that the shared state needs to be populated with * @return true - if a new shared state has been created at [version] */ @Synchronized fun setState(version: Int, data: Map<String, Any?>?): Boolean { return set(version, SharedState(version, SharedStateStatus.SET, data)) } /** * Sets the pending shared state for the extension at [version] if it does not already exist. * * @param version the version of the shared state to be created * @return true - if a new pending shared state has been created at [version] */ @Synchronized fun setPendingState(version: Int): Boolean { return set(version, SharedState(version, SharedStateStatus.PENDING, resolve(VERSION_LATEST).value)) } /** * Updates the pending shared state for the extension at [version] to contain [data] * * @param version the version of the shared state to be created * @param data the content that the shared state needs to be populated with * @return true - if the pending shared state is updated at [version] to contain [data] */ @Synchronized fun updatePendingState(version: Int, data: Map<String, Any?>?): Boolean { val stateAtVersion = states[version] ?: return false if (stateAtVersion.status != SharedStateStatus.PENDING) { return false } // At this point, there exists a previously recorded state at the version provided. // Overwrite its value with a confirmed state. states[version] = SharedState(version, SharedStateStatus.SET, data) return true } /** * Retrieves data for shared state at [version]. If such a version does not exist, * retrieves the most recent version of the shared state available. * * @param version the version of the shared state to be retrieved * @return shared state at [version] if it exists, or the most recent shared state before [version] if * shared state at [version] does not exist, * null - If no state at or before [version] is found */ @Synchronized fun resolve(version: Int): SharedStateResult { // Return first state equal to or less than version val resolvedState = states.floorEntry(version)?.value if (resolvedState != null) { return resolvedState.getResult() } // If not return the lowest shared state or null if empty return states.firstEntry()?.value?.getResult() ?: SharedStateResult(SharedStateStatus.NONE, null) } /** * Retrieves data for shared state at [version]. If such a version does not exist, * retrieves the most recent version of the shared state available. * * @param version the version of the shared state to be retrieved * @return shared state at [version] if it exists, or the most recent shared state before [version] if * shared state at [version] does not exist, * null - If no state at or before [version] is found */ @Synchronized fun resolveLastSet(version: Int): SharedStateResult { // Return the first non pending state equal to or less than version states.descendingMap().tailMap(version).forEach { val state = it.value if (state.status != SharedStateStatus.PENDING) { return state.getResult() } } // If not return the lowest shared state if it is non pending or null otherwise val lowestState = states.firstEntry()?.value return if (lowestState?.status == SharedStateStatus.SET) { lowestState.getResult() } else { SharedStateResult(SharedStateStatus.NONE, null) } } /** * Removes all the states being tracked from [states] */ @Synchronized fun clear() { states.clear() } /** * Checks if the [SharedStateManager] is empty. */ @Synchronized fun isEmpty(): Boolean { return states.size == 0 } /** * Sets the shared state at [version] as [state] if it does not already exist. * * @param version the version of the shared state to be created * @param state the [SharedState] object * @return true - if a new shared state has been created at [version] */ private fun set(version: Int, state: SharedState): Boolean { // Check if there exists a state at a version equal to, or higher than the one provided. if (states.ceilingEntry(version) != null) { Log.trace( CoreConstants.LOG_TAG, LOG_TAG, "Cannot create $name shared state at version $version. " + "More recent state exists." ) return false } // At this point, there does not exist a state at the provided version. states[version] = state return true } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/eventhub/EventHubPlaceholderExtension.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.eventhub import com.adobe.marketing.mobile.Extension import com.adobe.marketing.mobile.ExtensionApi /** * An `Extension` for `EventHub`. This serves no purpose other than to allow `EventHub` to store share state and manage event listeners. */ internal class EventHubPlaceholderExtension(val extensionApi: ExtensionApi) : Extension(extensionApi) { override fun getName() = EventHubConstants.NAME override fun getFriendlyName() = EventHubConstants.FRIENDLY_NAME override fun getVersion() = EventHubConstants.VERSION_NUMBER }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/eventhub/ExtensionContainer.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.eventhub import com.adobe.marketing.mobile.Event import com.adobe.marketing.mobile.EventHistoryRequest import com.adobe.marketing.mobile.EventHistoryResultHandler import com.adobe.marketing.mobile.Extension import com.adobe.marketing.mobile.ExtensionApi import com.adobe.marketing.mobile.ExtensionEventListener import com.adobe.marketing.mobile.SharedStateResolution import com.adobe.marketing.mobile.SharedStateResolver import com.adobe.marketing.mobile.SharedStateResult import com.adobe.marketing.mobile.internal.CoreConstants import com.adobe.marketing.mobile.services.Log import com.adobe.marketing.mobile.util.SerialWorkDispatcher import java.util.concurrent.ConcurrentLinkedQueue internal class ExtensionContainer constructor( private val extensionClass: Class<out Extension>, callback: (EventHubError) -> Unit ) : ExtensionApi() { companion object { const val LOG_TAG = "ExtensionContainer" } var sharedStateName: String? = null private set var friendlyName: String? = null private set var version: String? = null private set var metadata: Map<String, String>? = null private set var lastProcessedEvent: Event? = null private set var extension: Extension? = null private set private var sharedStateManagers: Map<SharedStateType, SharedStateManager>? = null private val eventListeners: ConcurrentLinkedQueue<ExtensionListenerContainer> = ConcurrentLinkedQueue() /** * Implementation of [SerialWorkDispatcher.WorkHandler] that is responsible for dispatching * an [Event] "e". Dispatch is regarded complete when [SerialWorkDispatcher.WorkHandler.doWork] finishes for "e". */ private val dispatchJob: SerialWorkDispatcher.WorkHandler<Event> = SerialWorkDispatcher.WorkHandler { event -> if (extension?.readyForEvent(event) != true) { return@WorkHandler false } eventListeners.forEach { if (it.shouldNotify(event)) { it.notify(event) } } lastProcessedEvent = event return@WorkHandler true } private val initJob = Runnable { val extension = extensionClass.initWith(this) if (extension == null) { callback(EventHubError.ExtensionInitializationFailure) return@Runnable } val extensionName = extension.extensionName if (extensionName.isNullOrBlank()) { callback(EventHubError.InvalidExtensionName) return@Runnable } this.extension = extension sharedStateName = extensionName friendlyName = extension.extensionFriendlyName version = extension.extensionVersion metadata = extension.extensionMetadata sharedStateManagers = mapOf( SharedStateType.XDM to SharedStateManager(extensionName), SharedStateType.STANDARD to SharedStateManager(extensionName) ) Log.debug( CoreConstants.LOG_TAG, getTag(), "Extension registered" ) callback(EventHubError.None) // Notify that the extension is registered extension.onExtensionRegistered() } private val teardownJob = Runnable { extension?.onExtensionUnregistered() Log.debug( CoreConstants.LOG_TAG, getTag(), "Extension unregistered" ) } val eventProcessor: SerialWorkDispatcher<Event> = SerialWorkDispatcher(extensionClass.extensionTypeName, dispatchJob) init { eventProcessor.setInitialJob(initJob) eventProcessor.setFinalJob(teardownJob) eventProcessor.start() } fun shutdown() { eventProcessor.shutdown() } /** * Returns instance of [SharedStateManager] for [SharedStateType] */ fun getSharedStateManager(type: SharedStateType): SharedStateManager? { return sharedStateManagers?.get(type) } private fun getTag(): String { if (extension == null) { return LOG_TAG } return "ExtensionContainer[$sharedStateName($version)]" } // Override ExtensionApi Methods override fun registerEventListener( eventType: String, eventSource: String, eventListener: ExtensionEventListener ) { eventListeners.add(ExtensionListenerContainer(eventType, eventSource, eventListener)) } override fun dispatch( event: Event ) { EventHub.shared.dispatch(event) } override fun startEvents() { eventProcessor.resume() } override fun stopEvents() { eventProcessor.pause() } override fun createSharedState( state: MutableMap<String, Any?>, event: Event? ) { val sharedStateName = this.sharedStateName ?: run { Log.warning( CoreConstants.LOG_TAG, getTag(), "ExtensionContainer is not fully initialized. createSharedState should not be called from Extension constructor" ) return } EventHub.shared.createSharedState( SharedStateType.STANDARD, sharedStateName, state, event ) } override fun createPendingSharedState( event: Event? ): SharedStateResolver? { val sharedStateName = this.sharedStateName ?: run { Log.warning( CoreConstants.LOG_TAG, getTag(), "ExtensionContainer is not fully initialized. createPendingSharedState should not be called from 'Extension' constructor" ) return null } return EventHub.shared.createPendingSharedState( SharedStateType.STANDARD, sharedStateName, event ) } override fun getSharedState( extensionName: String, event: Event?, barrier: Boolean, resolution: SharedStateResolution ): SharedStateResult? { return EventHub.shared.getSharedState( SharedStateType.STANDARD, extensionName, event, barrier, resolution ) } override fun createXDMSharedState( state: MutableMap<String, Any?>, event: Event? ) { val sharedStateName = this.sharedStateName ?: run { Log.warning( CoreConstants.LOG_TAG, getTag(), "ExtensionContainer is not fully initialized. createXDMSharedState should not be called from Extension constructor" ) return } EventHub.shared.createSharedState(SharedStateType.XDM, sharedStateName, state, event) } override fun createPendingXDMSharedState( event: Event? ): SharedStateResolver? { val sharedStateName = this.sharedStateName ?: run { Log.warning( CoreConstants.LOG_TAG, getTag(), "ExtensionContainer is not fully initialized. createPendingXDMSharedState should not be called from 'Extension' constructor" ) return null } return EventHub.shared.createPendingSharedState(SharedStateType.XDM, sharedStateName, event) } override fun getXDMSharedState( extensionName: String, event: Event?, barrier: Boolean, resolution: SharedStateResolution ): SharedStateResult? { return EventHub.shared.getSharedState( SharedStateType.XDM, extensionName, event, barrier, resolution ) } override fun unregisterExtension() { EventHub.shared.unregisterExtension(extensionClass) {} } override fun getHistoricalEvents( eventHistoryRequests: Array<out EventHistoryRequest>, enforceOrder: Boolean, handler: EventHistoryResultHandler<Int> ) { EventHub.shared.eventHistory?.getEvents(eventHistoryRequests, enforceOrder, handler) } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/eventhub/EventHub.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.eventhub import androidx.annotation.VisibleForTesting import com.adobe.marketing.mobile.AdobeCallback import com.adobe.marketing.mobile.AdobeCallbackWithError import com.adobe.marketing.mobile.AdobeError import com.adobe.marketing.mobile.Event import com.adobe.marketing.mobile.EventSource import com.adobe.marketing.mobile.EventType import com.adobe.marketing.mobile.Extension import com.adobe.marketing.mobile.LoggingMode import com.adobe.marketing.mobile.SharedStateResolution import com.adobe.marketing.mobile.SharedStateResolver import com.adobe.marketing.mobile.SharedStateResult import com.adobe.marketing.mobile.SharedStateStatus import com.adobe.marketing.mobile.WrapperType import com.adobe.marketing.mobile.internal.CoreConstants import com.adobe.marketing.mobile.internal.eventhub.history.AndroidEventHistory import com.adobe.marketing.mobile.internal.eventhub.history.EventHistory import com.adobe.marketing.mobile.internal.util.prettify import com.adobe.marketing.mobile.services.Log import com.adobe.marketing.mobile.util.EventDataUtils import com.adobe.marketing.mobile.util.SerialWorkDispatcher import java.util.concurrent.Callable import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger /** * EventHub class is responsible for delivering events to listeners and maintaining registered extension's lifecycle. */ internal class EventHub { companion object { const val LOG_TAG = "EventHub" var shared = EventHub() } /** * Executor for eventhub callbacks and response listeners */ private val scheduledExecutor: ScheduledExecutorService by lazy { Executors.newSingleThreadScheduledExecutor() } /** * Executor to serialize EventHub operations */ private val eventHubExecutor: ExecutorService by lazy { Executors.newSingleThreadExecutor() } /** * Concurrent map which stores the backing extension container for each Extension and can be referenced by extension type name */ private val registeredExtensions: ConcurrentHashMap<String, ExtensionContainer> = ConcurrentHashMap() /** * Concurrent list which stores the event listeners for response events. */ private val responseEventListeners: ConcurrentLinkedQueue<ResponseListenerContainer> = ConcurrentLinkedQueue() /** * Concurrent list which stores the registered event preprocessors. * Preprocessors will be executed on each event before distributing it to extension queue. */ private val eventPreprocessors: ConcurrentLinkedQueue<EventPreprocessor> = ConcurrentLinkedQueue() /** * Atomic counter which is incremented when processing event and shared state. */ private val lastEventNumber: AtomicInteger = AtomicInteger(0) /** * A cache that maps UUID of an Event to an internal sequence of its dispatch. */ private val eventNumberMap: ConcurrentHashMap<String, Int> = ConcurrentHashMap<String, Int>() /** * Boolean to denote if event hub has started processing events */ private var hubStarted = false /** * Implementation of [SerialWorkDispatcher.WorkHandler] that is responsible for dispatching * an [Event] "e". Dispatch is regarded complete when [SerialWorkDispatcher.WorkHandler.doWork] finishes for "e". */ private val dispatchJob: SerialWorkDispatcher.WorkHandler<Event> = SerialWorkDispatcher.WorkHandler { event -> var processedEvent: Event = event for (eventPreprocessor in eventPreprocessors) { processedEvent = eventPreprocessor.process(processedEvent) } // Handle response event listeners if (processedEvent.responseID != null) { val matchingResponseListeners = responseEventListeners.filterRemove { listener -> if (listener.shouldNotify(processedEvent)) { listener.timeoutTask?.cancel(false) true } else { false } } // Call the response event listeners from different thread to avoid block event processing queue executeCompletionHandler { matchingResponseListeners.forEach { listener -> listener.notify(processedEvent) } } } // Notify to extensions for processing registeredExtensions.values.forEach { it.eventProcessor.offer(processedEvent) } if (Log.getLogLevel() >= LoggingMode.DEBUG) { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Dispatched Event #${getEventNumber(event)} to extensions after processing rules - ($processedEvent)" ) } // Record event history processedEvent.mask?.let { eventHistory?.recordEvent(processedEvent) { result -> if (!result) { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Failed to insert Event(${processedEvent.uniqueIdentifier}) into EventHistory database" ) } } } true } /** * Responsible for processing and dispatching each event. */ private val eventDispatcher: SerialWorkDispatcher<Event> = SerialWorkDispatcher("EventHub", dispatchJob) /** * Responsible for managing event history. */ var eventHistory: EventHistory? = null init { registerExtension(EventHubPlaceholderExtension::class.java) } private var _wrapperType = WrapperType.NONE var wrapperType: WrapperType get() { return eventHubExecutor.submit( Callable { return@Callable _wrapperType } ).get() } set(value) { eventHubExecutor.submit( Callable { if (hubStarted) { Log.warning( CoreConstants.LOG_TAG, LOG_TAG, "Wrapper type can not be set after EventHub starts processing events" ) return@Callable } _wrapperType = value Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Wrapper type set to $value" ) } ).get() } /** * Submits a task to be executed in the event hub executor. */ fun executeInEventHubExecutor(task: () -> Unit) { eventHubExecutor.submit(task) } /** * Initializes event history. This must be called after the SDK has application context. */ fun initializeEventHistory() { if (eventHistory != null) { Log.warning( CoreConstants.LOG_TAG, LOG_TAG, "Event history is already initialized" ) return } eventHistory = try { AndroidEventHistory() } catch (ex: Exception) { Log.warning( CoreConstants.LOG_TAG, LOG_TAG, "Event history initialization failed with exception ${ex.message}" ) null } } /** * `EventHub` will begin processing `Event`s when this API is invoked. */ fun start() { eventHubExecutor.submit { this.hubStarted = true this.eventDispatcher.start() this.shareEventHubSharedState() Log.trace(CoreConstants.LOG_TAG, LOG_TAG, "EventHub started. Will begin processing events") } } /** * Dispatches a new [Event] to all listeners who have registered for the event type and source. * If the `event` has a `mask`, this method will attempt to record the `event` in `eventHistory`. * See [eventDispatcher] for more details. * * @param event the [Event] to be dispatched to listeners */ fun dispatch(event: Event) { eventHubExecutor.submit { dispatchInternal(event) } } /** * Internal method to dispatch an event */ private fun dispatchInternal(event: Event) { val eventNumber = lastEventNumber.incrementAndGet() eventNumberMap[event.uniqueIdentifier] = eventNumber // Offer event to the serial dispatcher to perform operations on the event. if (!eventDispatcher.offer(event)) { Log.warning( CoreConstants.LOG_TAG, LOG_TAG, "Failed to dispatch event #$eventNumber - ($event)" ) } if (Log.getLogLevel() >= LoggingMode.DEBUG) { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Dispatching Event #$eventNumber - ($event)" ) } } /** * Registers a new [Extension] to the `EventHub`. This extension must extend [Extension] class * * @param extensionClass The class of extension to register * @param completion Invoked when the extension has been registered or failed to register */ @JvmOverloads fun registerExtension( extensionClass: Class<out Extension>, completion: ((error: EventHubError) -> Unit)? = null ) { eventHubExecutor.submit { val extensionTypeName = extensionClass.extensionTypeName if (registeredExtensions.containsKey(extensionTypeName)) { completion?.let { executeCompletionHandler { it(EventHubError.DuplicateExtensionName) } } return@submit } val container = ExtensionContainer(extensionClass) { error -> eventHubExecutor.submit { completion?.let { executeCompletionHandler { it(error) } } extensionPostRegistration(extensionClass, error) } } registeredExtensions[extensionTypeName] = container } } /** * Called after creating extension container to hold the extension * * @param extensionClass The class of extension to register * @param error Error denoting the status of registration */ private fun extensionPostRegistration(extensionClass: Class<out Extension>, error: EventHubError) { if (error != EventHubError.None) { Log.warning(CoreConstants.LOG_TAG, LOG_TAG, "Extension $extensionClass registration failed with error $error") unregisterExtensionInternal(extensionClass) } else { Log.trace(CoreConstants.LOG_TAG, LOG_TAG, "Extension $extensionClass registered successfully") shareEventHubSharedState() } } /** * Unregisters the extension from the `EventHub` if registered * @param extensionClass The class of extension to unregister * @param completion Invoked when the extension has been unregistered or failed to unregister */ fun unregisterExtension( extensionClass: Class<out Extension>, completion: ((error: EventHubError) -> Unit) ) { eventHubExecutor.submit { unregisterExtensionInternal(extensionClass, completion) } } private fun unregisterExtensionInternal( extensionClass: Class<out Extension>, completion: ((error: EventHubError) -> Unit)? = null ) { val extensionName = extensionClass.extensionTypeName val container = registeredExtensions.remove(extensionName) val error: EventHubError = if (container != null) { container.shutdown() shareEventHubSharedState() Log.trace(CoreConstants.LOG_TAG, LOG_TAG, "Extension $extensionClass unregistered successfully") EventHubError.None } else { Log.warning(CoreConstants.LOG_TAG, LOG_TAG, "Extension $extensionClass unregistration failed as extension was not registered") EventHubError.ExtensionNotRegistered } completion.let { executeCompletionHandler { it?.invoke(error) } } } /** * Registers an event listener which will be invoked when the response event to trigger event is dispatched * @param triggerEvent An [Event] which will trigger a response event * @param timeoutMS A timeout in milliseconds, if the response listener is not invoked within the timeout, then the `EventHub` invokes the fail method. * @param listener An [AdobeCallbackWithError] which will be invoked whenever the `EventHub` receives the response event for trigger event */ fun registerResponseListener( triggerEvent: Event, timeoutMS: Long, listener: AdobeCallbackWithError<Event> ) { eventHubExecutor.submit { val triggerEventId = triggerEvent.uniqueIdentifier val timeoutCallable: Callable<Unit> = Callable { responseEventListeners.filterRemove { it.triggerEventId == triggerEventId } try { listener.fail(AdobeError.CALLBACK_TIMEOUT) } catch (ex: Exception) { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Exception thrown from ResponseListener - $ex" ) } } val timeoutTask = scheduledExecutor.schedule(timeoutCallable, timeoutMS, TimeUnit.MILLISECONDS) responseEventListeners.add( ResponseListenerContainer( triggerEventId, timeoutTask, listener ) ) } } /** * Registers an event listener which will be invoked whenever an [Event] with matched type and source is dispatched * @param eventType A String indicating the event type the current listener is listening for * @param eventSource A `String` indicating the event source the current listener is listening for * @param listener An [AdobeCallback] which will be invoked whenever the `EventHub` receives a event with matched type and source */ fun registerListener(eventType: String, eventSource: String, listener: AdobeCallback<Event>) { eventHubExecutor.submit { val eventHubContainer = getExtensionContainer(EventHubPlaceholderExtension::class.java) eventHubContainer?.registerEventListener(eventType, eventSource) { listener.call(it) } } } /** * Registers an [EventPreprocessor] with the eventhub * Note that this is an internal only method for use by ConfigurationExtension, * until preprocessors are supported via a public api. * * @param eventPreprocessor the [EventPreprocessor] that should be registered */ internal fun registerEventPreprocessor(eventPreprocessor: EventPreprocessor) { if (eventPreprocessors.contains(eventPreprocessor)) { return } eventPreprocessors.add(eventPreprocessor) } /** * Creates a new shared state for the extension with provided data, versioned at [Event] * If `event` is nil, one of two behaviors will be observed: * 1. If this extension has not previously published a shared state, shared state will be versioned at 0 * 2. If this extension has previously published a shared state, shared state will be versioned at the latest * @param sharedStateType The type of shared state to be set * @param extensionName Extension whose shared state is to be updated * @param state Map which contains data for the shared state * @param event [Event] for which the `SharedState` should be versioned * @return true - if shared state is created successfully */ fun createSharedState( sharedStateType: SharedStateType, extensionName: String, state: MutableMap<String, Any?>?, event: Event? ): Boolean { val immutableState = try { EventDataUtils.immutableClone(state) } catch (ex: Exception) { Log.warning( CoreConstants.LOG_TAG, LOG_TAG, "Creating $sharedStateType shared state for extension $extensionName at event ${event?.uniqueIdentifier} with null - Cloning state failed with exception $ex" ) null } val callable = Callable { return@Callable createSharedStateInternal( sharedStateType, extensionName, immutableState, event ) } return eventHubExecutor.submit(callable).get() } /** * Internal method to creates a new shared state for the extension with provided data, versioned at [Event] */ private fun createSharedStateInternal( sharedStateType: SharedStateType, extensionName: String, state: MutableMap<String, Any?>?, event: Event? ): Boolean { val sharedStateManager = getSharedStateManager(sharedStateType, extensionName) sharedStateManager ?: run { Log.warning( CoreConstants.LOG_TAG, LOG_TAG, "Create $sharedStateType shared state for extension \"$extensionName\" for event ${event?.uniqueIdentifier} failed - SharedStateManager is null" ) return false } val version = resolveSharedStateVersion(sharedStateManager, event) val didSet = sharedStateManager.setState(version, state) if (!didSet) { Log.warning( CoreConstants.LOG_TAG, LOG_TAG, "Create $sharedStateType shared state for extension \"$extensionName\" for event ${event?.uniqueIdentifier} failed - SharedStateManager failed" ) } else { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Created $sharedStateType shared state for extension \"$extensionName\" with version $version and data ${state?.prettify()}" ) dispatchSharedStateEvent(sharedStateType, extensionName) } return didSet } /** * Sets the shared state for the extension to pending at event's version and returns a [SharedStateResolver] which is to be invoked with data for the shared state once available. * If event is nil, one of two behaviors will be observed: * 1. If this extension has not previously published a shared state, shared state will be versioned at 0 * 2. If this extension has previously published a shared state, shared state will be versioned at the latest * @param sharedStateType The type of shared state to be set * @param extensionName Extension whose shared state is to be updated * @param event [Event] for which the `SharedState` should be versioned * @return A [SharedStateResolver] which is invoked to set pending the shared state versioned at [Event] */ fun createPendingSharedState( sharedStateType: SharedStateType, extensionName: String, event: Event? ): SharedStateResolver? { val callable = Callable<SharedStateResolver?> { val sharedStateManager = getSharedStateManager(sharedStateType, extensionName) sharedStateManager ?: run { Log.warning( CoreConstants.LOG_TAG, LOG_TAG, "Create pending $sharedStateType shared state for extension \"$extensionName\" for event ${event?.uniqueIdentifier} failed - SharedStateManager is null" ) return@Callable null } val pendingVersion = resolveSharedStateVersion(sharedStateManager, event) val didSetPending = sharedStateManager.setPendingState(pendingVersion) if (!didSetPending) { Log.warning( CoreConstants.LOG_TAG, LOG_TAG, "Create pending $sharedStateType shared state for extension \"$extensionName\" for event ${event?.uniqueIdentifier} failed - SharedStateManager failed" ) return@Callable null } Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Created pending $sharedStateType shared state for extension \"$extensionName\" with version $pendingVersion" ) return@Callable SharedStateResolver { resolvePendingSharedState(sharedStateType, extensionName, it, pendingVersion) } } return eventHubExecutor.submit(callable).get() } /** * Updates a pending shared state and dispatches it to the `EventHub` * Providing a version for which there is no pending state will result in a no-op. * @param sharedStateType The type of shared state to be set * @param extensionName Extension whose shared state is to be updated * @param state Map which contains data for the shared state * @param version An `Int` containing the version of the state being updated */ private fun resolvePendingSharedState( sharedStateType: SharedStateType, extensionName: String, state: MutableMap<String, Any?>?, version: Int ) { val immutableState = try { EventDataUtils.immutableClone(state) } catch (ex: Exception) { Log.warning( CoreConstants.LOG_TAG, LOG_TAG, "Resolving pending $sharedStateType shared state for extension \"$extensionName\" and version $version with null - Clone failed with exception $ex" ) null } val callable = Callable { val sharedStateManager = getSharedStateManager(sharedStateType, extensionName) ?: run { Log.warning( CoreConstants.LOG_TAG, LOG_TAG, "Resolve pending $sharedStateType shared state for extension \"$extensionName\" and version $version failed - SharedStateManager is null" ) return@Callable } val didUpdate = sharedStateManager.updatePendingState(version, immutableState) if (!didUpdate) { Log.warning( CoreConstants.LOG_TAG, LOG_TAG, "Resolve pending $sharedStateType shared state for extension \"$extensionName\" and version $version failed - SharedStateManager failed" ) return@Callable } Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Resolved pending $sharedStateType shared state for \"$extensionName\" and version $version with data ${immutableState?.prettify()}" ) dispatchSharedStateEvent(sharedStateType, extensionName) } eventHubExecutor.submit(callable).get() } /** * Retrieves the shared state for a specific extension * @param sharedStateType The type of shared state to be set * @param extensionName Extension whose shared state will be returned * @param event If not nil, will retrieve the shared state that corresponds with this event's version or latest if not yet versioned. If event is nil will return the latest shared state * @param barrier If true, the `EventHub` will only return [SharedStateStatus.SET] if [extensionName] has moved past [Event] * @param resolution The [SharedStateResolution] to determine how to resolve the shared state * @return The shared state data and status for the extension with [extensionName] */ fun getSharedState( sharedStateType: SharedStateType, extensionName: String, event: Event?, barrier: Boolean, resolution: SharedStateResolution ): SharedStateResult? { val callable = Callable<SharedStateResult?> { val container = getExtensionContainer(extensionName) ?: run { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Unable to retrieve $sharedStateType shared state for \"$extensionName\". No such extension is registered." ) return@Callable null } val sharedStateManager = getSharedStateManager(sharedStateType, extensionName) ?: run { Log.warning( CoreConstants.LOG_TAG, LOG_TAG, "Unable to retrieve $sharedStateType shared state for \"$extensionName\". SharedStateManager is null" ) return@Callable null } val version = getEventNumber(event) ?: SharedStateManager.VERSION_LATEST val result: SharedStateResult = when (resolution) { SharedStateResolution.ANY -> sharedStateManager.resolve(version) SharedStateResolution.LAST_SET -> sharedStateManager.resolveLastSet(version) } val stateProviderLastVersion = getEventNumber(container.lastProcessedEvent) ?: 0 // shared state is still considered pending if barrier is used and the state provider has not processed past the previous event val hasProcessedEvent = if (event == null) true else stateProviderLastVersion > version - 1 return@Callable if (barrier && !hasProcessedEvent && result.status == SharedStateStatus.SET) { SharedStateResult(SharedStateStatus.PENDING, result.value) } else { result } } return eventHubExecutor.submit(callable).get() } /** * Clears all shared state previously set by [extensionName]. * * @param sharedStateType the type of shared state that needs to be cleared. * @param extensionName the name of the extension for which the state is being cleared * @return true - if the shared state has been cleared, false otherwise */ fun clearSharedState( sharedStateType: SharedStateType, extensionName: String ): Boolean { val callable = Callable { val sharedStateManager = getSharedStateManager(sharedStateType, extensionName) ?: run { Log.warning( CoreConstants.LOG_TAG, LOG_TAG, "Clear $sharedStateType shared state for extension \"$extensionName\" failed - SharedStateManager is null" ) return@Callable false } sharedStateManager.clear() Log.warning( CoreConstants.LOG_TAG, LOG_TAG, "Cleared $sharedStateType shared state for extension \"$extensionName\"" ) return@Callable true } return eventHubExecutor.submit(callable).get() } /** * Stops processing events and shuts down all registered extensions. */ fun shutdown() { // Shutdown and clear all the extensions. eventHubExecutor.submit { eventDispatcher.shutdown() // Unregister all extensions registeredExtensions.forEach { (_, extensionContainer) -> extensionContainer.shutdown() } registeredExtensions.clear() } eventHubExecutor.shutdown() scheduledExecutor.shutdown() } /** * Retrieve the event number for the Event from the [eventNumberMap] * * @param event the [Event] for which the event number should be resolved * @return the event number for the event if it exists (if it has been recorded/dispatched), * null otherwise */ private fun getEventNumber(event: Event?): Int? { if (event == null) { return null } val eventUUID = event.uniqueIdentifier return eventNumberMap[eventUUID] } /** * Retrieves a registered [ExtensionContainer] with [extensionClass] provided. * * @param extensionClass the extension class for which an [ExtensionContainer] should be fetched. * @return [ExtensionContainer] with [extensionName] provided if one was registered, * null if no extension is registered with the [extensionName] */ @VisibleForTesting internal fun getExtensionContainer(extensionClass: Class<out Extension>): ExtensionContainer? { return registeredExtensions[extensionClass.extensionTypeName] } /** * Retrieves a registered [ExtensionContainer] with [extensionTypeName] provided. * * @param extensionName the name of the extension for which an [ExtensionContainer] should be fetched. * This should match [Extension.name] of an extension registered with the event hub. * @return [ExtensionContainer] with [extensionName] provided if one was registered, * null if no extension is registered with the [extensionName] */ private fun getExtensionContainer(extensionName: String): ExtensionContainer? { val extensionContainer = registeredExtensions.entries.firstOrNull { return@firstOrNull ( it.value.sharedStateName?.equals( extensionName, true ) ?: false ) } return extensionContainer?.value } /** * Retrieves the [SharedStateManager] of type [sharedStateType] with [extensionName] provided. * * @param sharedStateType the [SharedStateType] for which an [SharedStateManager] should be fetched. * @param extensionName the name of the extension for which an [SharedStateManager] should be fetched. * This should match [Extension.name] of an extension registered with the event hub. * @return [SharedStateManager] with [extensionName] provided if one was registered and initialized * null otherwise */ private fun getSharedStateManager( sharedStateType: SharedStateType, extensionName: String ): SharedStateManager? { val extensionContainer = getExtensionContainer(extensionName) ?: run { return null } val sharedStateManager = extensionContainer.getSharedStateManager(sharedStateType) ?: run { return null } return sharedStateManager } /** * Retrieves the appropriate shared state version for the event. * * @param sharedStateManager A [SharedStateManager] to version the event. * @param event An [Event] which may contain a specific event from which the correct shared state can be retrieved * @return Int denoting the version number */ private fun resolveSharedStateVersion( sharedStateManager: SharedStateManager, event: Event? ): Int { // 1) If event is not null, pull the version number from internal map // 2) If event is null, start with version 0 if shared state is empty. // We start with '0' because extensions can call createSharedState() to export initial state // before handling any event and other extensions should be able to read this state. var version = 0 if (event != null) { version = getEventNumber(event) ?: 0 } else if (!sharedStateManager.isEmpty()) { version = lastEventNumber.incrementAndGet() } return version } /** * Dispatch shared state update event for the [sharedStateType] and [extensionName] * @param sharedStateType The type of shared state set * @param extensionName Extension whose shared state was updated */ private fun dispatchSharedStateEvent(sharedStateType: SharedStateType, extensionName: String) { val eventName = if (sharedStateType == SharedStateType.STANDARD) EventHubConstants.STATE_CHANGE else EventHubConstants.XDM_STATE_CHANGE val data = mapOf(EventHubConstants.EventDataKeys.Configuration.EVENT_STATE_OWNER to extensionName) val event = Event.Builder(eventName, EventType.HUB, EventSource.SHARED_STATE) .setEventData(data).build() dispatchInternal(event) } private fun shareEventHubSharedState() { if (!hubStarted) return val extensionsInfo = mutableMapOf<String, Any?>() registeredExtensions.values.forEach { val extensionName = it.sharedStateName if (extensionName != null && extensionName != EventHubConstants.NAME) { val extensionInfo = mutableMapOf<String, Any?>( EventHubConstants.EventDataKeys.FRIENDLY_NAME to it.friendlyName, EventHubConstants.EventDataKeys.VERSION to it.version ) it.metadata?.let { metadata -> extensionInfo[EventHubConstants.EventDataKeys.METADATA] = metadata } extensionsInfo[extensionName] = extensionInfo } } val wrapperInfo = mapOf( EventHubConstants.EventDataKeys.TYPE to _wrapperType.wrapperTag, EventHubConstants.EventDataKeys.FRIENDLY_NAME to _wrapperType.friendlyName ) val data = mapOf( EventHubConstants.EventDataKeys.VERSION to EventHubConstants.VERSION_NUMBER, EventHubConstants.EventDataKeys.WRAPPER to wrapperInfo, EventHubConstants.EventDataKeys.EXTENSIONS to extensionsInfo ) createSharedStateInternal( SharedStateType.STANDARD, EventHubConstants.NAME, EventDataUtils.immutableClone(data), null ) } private fun executeCompletionHandler(runnable: Runnable) { scheduledExecutor.submit { try { runnable.run() } catch (ex: Exception) { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Exception thrown from callback - $ex" ) } } } } private fun <T> MutableCollection<T>.filterRemove(predicate: (T) -> Boolean): MutableCollection<T> { val ret = mutableListOf<T>() this.removeAll { if (predicate(it)) { ret.add(it) true } else { false } } return ret }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/eventhub/EventListenerContainer.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.eventhub import com.adobe.marketing.mobile.AdobeCallbackWithError import com.adobe.marketing.mobile.Event import com.adobe.marketing.mobile.EventSource import com.adobe.marketing.mobile.EventType import com.adobe.marketing.mobile.ExtensionEventListener import com.adobe.marketing.mobile.internal.CoreConstants import com.adobe.marketing.mobile.services.Log import java.lang.Exception import java.util.concurrent.ScheduledFuture internal sealed class EventListenerContainer { abstract fun shouldNotify(event: Event): Boolean abstract fun notify(event: Event) } internal class ResponseListenerContainer( val triggerEventId: String, val timeoutTask: ScheduledFuture<Unit>?, val listener: AdobeCallbackWithError<Event> ) : EventListenerContainer() { override fun shouldNotify(event: Event): Boolean { return event.responseID == triggerEventId } override fun notify(event: Event) { try { listener.call(event) } catch (ex: Exception) { Log.debug( CoreConstants.LOG_TAG, "ResponseListenerContainer", "Exception thrown for EventId ${event.uniqueIdentifier}. $ex" ) } } } internal class ExtensionListenerContainer(val eventType: String, val eventSource: String, val listener: ExtensionEventListener) : EventListenerContainer() { override fun shouldNotify(event: Event): Boolean { // Wildcard listeners should only be notified of paired response events. return if (event.responseID != null) { (eventType == EventType.WILDCARD && eventSource == EventSource.WILDCARD) } else { eventType.equals(event.type, ignoreCase = true) && eventSource.equals(event.source, ignoreCase = true) || eventType == EventType.WILDCARD && eventSource == EventSource.WILDCARD } } override fun notify(event: Event) { try { listener.hear(event) } catch (ex: Exception) { Log.debug( CoreConstants.LOG_TAG, "ExtensionListenerContainer", "Exception thrown for EventId ${event.uniqueIdentifier}. $ex" ) } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/eventhub/EventHubConstants.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.eventhub import com.adobe.marketing.mobile.internal.CoreConstants internal object EventHubConstants { const val NAME = "com.adobe.module.eventhub" const val FRIENDLY_NAME = "EventHub" const val VERSION_NUMBER = CoreConstants.VERSION const val STATE_CHANGE = "Shared state change" const val XDM_STATE_CHANGE = "Shared state change (XDM)" object EventDataKeys { const val VERSION = "version" const val EXTENSIONS = "extensions" const val WRAPPER = "wrapper" const val TYPE = "type" const val METADATA = "metadata" const val FRIENDLY_NAME = "friendlyName" object Configuration { const val EVENT_STATE_OWNER = "stateowner" } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/eventhub/ExtensionExt.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.eventhub import com.adobe.marketing.mobile.Extension import com.adobe.marketing.mobile.ExtensionApi import com.adobe.marketing.mobile.ExtensionHelper import com.adobe.marketing.mobile.internal.CoreConstants import com.adobe.marketing.mobile.services.Log import java.lang.Exception // Type extensions for [Extension] to allow for easier usage /** * Function to initialize Extension with [ExtensionApi] */ internal fun Class<out Extension>.initWith(extensionApi: ExtensionApi): Extension? { try { val extensionConstructor = this.getDeclaredConstructor(ExtensionApi::class.java) extensionConstructor.isAccessible = true return extensionConstructor.newInstance(extensionApi) } catch (ex: Exception) { Log.debug(CoreConstants.LOG_TAG, "ExtensionExt", "Initializing Extension $this failed with $ex") } return null } /** * Property to get Extension name */ internal val Extension.extensionName: String? get() = ExtensionHelper.getName(this) /** * Property to get Extension version */ internal val Extension.extensionVersion: String? get() = ExtensionHelper.getVersion(this) /** * Property to get Extension friendly name */ internal val Extension.extensionFriendlyName: String? get() = ExtensionHelper.getFriendlyName(this) /** * Property to get Extension metadata */ internal val Extension.extensionMetadata: Map<String, String>? get() = ExtensionHelper.getMetadata(this) /** * Function to notify that the Extension has been unregistered */ internal fun Extension.onExtensionUnregistered() { ExtensionHelper.notifyUnregistered(this) } /** * Function to notify that the Extension has been registered */ internal fun Extension.onExtensionRegistered() { ExtensionHelper.notifyRegistered(this) } /** * Helper to get extension type name */ internal val Class<out Extension>.extensionTypeName get() = this.name
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/eventhub/EventHubError.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.eventhub internal enum class EventHubError { InvalidExtensionName, DuplicateExtensionName, ExtensionInitializationFailure, ExtensionNotRegistered, Unknown, None }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/eventhub/history/AndroidEventHistory.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.eventhub.history import com.adobe.marketing.mobile.Event import com.adobe.marketing.mobile.EventHistoryRequest import com.adobe.marketing.mobile.EventHistoryResultHandler import com.adobe.marketing.mobile.internal.CoreConstants import com.adobe.marketing.mobile.internal.util.convertMapToFnv1aHash import com.adobe.marketing.mobile.services.Log import java.util.concurrent.Executors import kotlin.math.max /** * The Android implementation of [EventHistory] which provides functionality for performing * database operations on an [AndroidEventHistoryDatabase]. */ internal class AndroidEventHistory : EventHistory { private val androidEventHistoryDatabase = AndroidEventHistoryDatabase() companion object { private const val LOG_TAG = "AndroidEventHistory" } /** * Responsible for holding a single thread executor for lazy initialization only if * AndroidEventHistory operations are used. */ private val executor by lazy { Executors.newSingleThreadExecutor() } /** * Record an event in the [AndroidEventHistoryDatabase]. * * @param event the [Event] to be recorded * @param handler [EventHistoryResultHandler] a callback which will contain a `boolean` indicating if the database operation was successful */ override fun recordEvent(event: Event, handler: EventHistoryResultHandler<Boolean>?) { executor.submit { val fnv1aHash = convertMapToFnv1aHash(event.eventData, event.mask) Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "%s hash($fnv1aHash) for Event(${event.uniqueIdentifier})", if (fnv1aHash == 0L) "Not Recording" else "Recording" ) val res = if (fnv1aHash != 0L) { androidEventHistoryDatabase.insert(fnv1aHash, event.timestamp) } else { false } notifyHandler(handler, res) } } /** * Query the [AndroidEventHistoryDatabase] for [Event]s which match the contents of * the [EventHistoryRequest] array. * * @param eventHistoryRequests an array of `EventHistoryRequest`s to be matched * @param enforceOrder `boolean` if true, consecutive lookups will use the oldest * timestamp from the previous event as their from date * @param handler If `enforceOrder` is false, `EventHistoryResultHandler<Integer>` containing the the total number of * matching events in the `EventHistoryDatabase`. If `enforceOrder` is true, the handler will contain a "1" if the event history requests * were found in the order specified in the eventHistoryRequests array and a "0" if the events were not found in the order specified. * The handler will contain a "-1" if the database failure occurred. */ override fun getEvents( eventHistoryRequests: Array<out EventHistoryRequest>, enforceOrder: Boolean, handler: EventHistoryResultHandler<Int> ) { executor.submit { var dbError = false var count = 0 var latestEventOccurrence: Long? = null eventHistoryRequests.forEachIndexed { index, request -> val eventHash = request.maskAsDecimalHash val adjustedFromDate = if (enforceOrder) request.adjustedFromDate(latestEventOccurrence) else request.fromDate val res = androidEventHistoryDatabase.query(eventHash, adjustedFromDate, request.adjustedToDate) Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "EventHistoryRequest[%d] - (%d of %d) for hash(%d)" + " with enforceOrder(%s) returned %d events", eventHistoryRequests.hashCode(), index + 1, eventHistoryRequests.size, eventHash, if (enforceOrder) "true" else "false", res?.count ?: -1 ) if (res == null) { dbError = true return@forEachIndexed } if (enforceOrder && res.count == 0) { return@forEachIndexed } latestEventOccurrence = res.newestTimeStamp count += res.count } val result = when { dbError -> -1 enforceOrder && count == eventHistoryRequests.size -> 1 enforceOrder && count != eventHistoryRequests.size -> 0 else -> count } notifyHandler(handler, result) } } /** * Delete rows from the [AndroidEventHistoryDatabase] that contain [Event]s which * match the contents of the [EventHistoryRequest] array. * * @param eventHistoryRequests an array of `EventHistoryRequest`s to be deleted * @param handler a callback which will be called with a `int` containing the total number * of rows deleted from the `AndroidEventHistoryDatabase` */ override fun deleteEvents( eventHistoryRequests: Array<out EventHistoryRequest>, handler: EventHistoryResultHandler<Int>? ) { executor.submit { val deletedRows = eventHistoryRequests.fold(0) { acc, request -> acc + androidEventHistoryDatabase.delete(request.maskAsDecimalHash, request.fromDate, request.adjustedToDate) } notifyHandler(handler, deletedRows) } } private fun <T> notifyHandler(handler: EventHistoryResultHandler<T>?, value: T) { try { handler?.call(value) } catch (ex: Exception) { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Exception executing event history result handler $ex" ) } } } private val EventHistoryRequest.adjustedToDate get() = if (this.toDate == 0L) { System.currentTimeMillis() } else { this.toDate } private fun EventHistoryRequest.adjustedFromDate(latestEventOccurrence: Long?): Long { if (latestEventOccurrence == null) { return this.fromDate } return max(latestEventOccurrence, this.fromDate) }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/eventhub/history/EventHistory.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.eventhub.history import com.adobe.marketing.mobile.Event import com.adobe.marketing.mobile.EventHistoryRequest import com.adobe.marketing.mobile.EventHistoryResultHandler /** Defines an interface for performing database operations on an [EventHistoryDatabase]. */ internal interface EventHistory { /** * Record an event in the [EventHistoryDatabase]. * * @param event the [Event] to be recorded * @param handler [EventHistoryResultHandler] a callback which will contain a `boolean` indicating if the database operation was successful */ fun recordEvent(event: Event, handler: EventHistoryResultHandler<Boolean>?) /** * Query the [EventHistoryDatabase] for [Event]s which match the contents of the * [EventHistoryRequest] array. * * @param eventHistoryRequests an array of `EventHistoryRequest`s to be matched * @param enforceOrder `boolean` if true, consecutive lookups will use the oldest * timestamp from the previous event as their from date * @param handler `EventHistoryResultHandler<Integer>` containing the the total number of * matching events in the `EventHistoryDatabase` if an "any" search was done. If an * "ordered" search was done, the handler will contain a "1" if the event history requests * were found in the order specified in the eventHistoryRequests array and a "0" if the * events were not found in the order specified. */ fun getEvents( eventHistoryRequests: Array<out EventHistoryRequest>, enforceOrder: Boolean, handler: EventHistoryResultHandler<Int> ) /** * Delete rows from the [EventHistoryDatabase] that contain [Event]s which match the * contents of the [EventHistoryRequest] array. * * @param eventHistoryRequests an array of `EventHistoryRequest`s to be deleted * @param handler a callback which will be called with a `int` containing the total number * of rows deleted from the `EventHistoryDatabase` */ fun deleteEvents( eventHistoryRequests: Array<out EventHistoryRequest>, handler: EventHistoryResultHandler<Int>? ) }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/eventhub/history/AndroidEventHistoryDatabase.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.eventhub.history import android.content.ContentValues import android.database.sqlite.SQLiteDatabase import com.adobe.marketing.mobile.internal.CoreConstants import com.adobe.marketing.mobile.internal.util.FileUtils.moveFile import com.adobe.marketing.mobile.internal.util.SQLiteDatabaseHelper import com.adobe.marketing.mobile.services.Log import com.adobe.marketing.mobile.services.ServiceProvider import java.io.File internal class AndroidEventHistoryDatabase : EventHistoryDatabase { private val dbMutex = Any() private val databaseFile: File private var database: SQLiteDatabase? = null /** * Constructor. * * @throws [EventHistoryDatabaseCreationException] if any error occurred while creating * the database or database table. */ init { databaseFile = openOrMigrateEventHistoryDatabaseFile() val tableCreationQuery = "CREATE TABLE IF NOT EXISTS $TABLE_NAME (eventHash INTEGER, timestamp INTEGER);" synchronized(dbMutex) { if (!SQLiteDatabaseHelper.createTableIfNotExist( databaseFile.path, tableCreationQuery ) ) { throw EventHistoryDatabaseCreationException( "An error occurred while creating the $TABLE_NAME table in the Android Event History database." ) } } } private fun openOrMigrateEventHistoryDatabaseFile(): File { val appContext = ServiceProvider.getInstance().appContextService.applicationContext ?: throw EventHistoryDatabaseCreationException( "Failed to create/open database $DATABASE_NAME, error message: ApplicationContext is null" ) val database = appContext.getDatabasePath(DATABASE_NAME) if (database.exists()) { return database } // If db exists in cache directory, migrate it to new path. val applicationCacheDir = ServiceProvider.getInstance().deviceInfoService.applicationCacheDir ?: return database try { val cacheDirDatabase = File(applicationCacheDir, DATABASE_NAME_1X) if (cacheDirDatabase.exists()) { moveFile(cacheDirDatabase, database) Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Successfully moved database $DATABASE_NAME_1X from cache directory to database directory" ) } } catch (e: Exception) { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Failed to move database $DATABASE_NAME_1X from cache directory to database directory" ) } return database } /** * Insert a row into a table in the database. * * @param hash `long` containing the 32-bit FNV-1a hashed representation of an Event's data * @param timestampMS `long` Event's timestamp in milliseconds * @return a `boolean` which will contain the status of the database insert operation */ override fun insert(hash: Long, timestampMS: Long): Boolean { synchronized(dbMutex) { try { openDatabase() val contentValues = ContentValues().apply { put(COLUMN_HASH, hash) put(COLUMN_TIMESTAMP, timestampMS) } val res = database?.insert(TABLE_NAME, null, contentValues) ?: -1 return res > 0 } catch (e: Exception) { Log.warning( CoreConstants.LOG_TAG, LOG_TAG, "Failed to insert rows into the table (%s)", if (e.localizedMessage != null) e.localizedMessage else e.message ) return false } finally { closeDatabase() } } } /** * Queries the database to search for the existence of events. * This method will count all records in the event history database that match the provided * hash and are within the bounds of the provided from and to timestamps. * * @param hash `long` containing the 32-bit FNV-1a hashed representation of an Event's data * @param from `long` a timestamp representing the lower bounds of the date range to use when searching for the hash * @param to `long` a timestamp representing the upper bounds of the date range to use when searching for the hash * @return a `QueryResult` object containing details of the matching records. If no database connection is available, returns null */ override fun query(hash: Long, from: Long, to: Long): EventHistoryDatabase.QueryResult? { synchronized(dbMutex) { try { openDatabase() val rawQuery = "SELECT COUNT(*) as $QUERY_COUNT, min($COLUMN_TIMESTAMP) as $QUERY_OLDEST, max($COLUMN_TIMESTAMP) as $QUERY_NEWEST FROM $TABLE_NAME WHERE $COLUMN_HASH = ? AND $COLUMN_TIMESTAMP >= ? AND $COLUMN_TIMESTAMP <= ?" val whereArgs = arrayOf(hash.toString(), from.toString(), to.toString()) val cursor = database?.rawQuery(rawQuery, whereArgs) ?: return null cursor.use { cursor.moveToFirst() val count = cursor.getInt(QUERY_COUNT_INDEX) val oldest = cursor.getLong(QUERY_OLDEST_INDEX) val newest = cursor.getLong(QUERY_NEWEST_INDEX) return EventHistoryDatabase.QueryResult(count, oldest, newest) } } catch (e: Exception) { Log.warning( CoreConstants.LOG_TAG, LOG_TAG, "Failed to execute query (%s)", if (e.localizedMessage != null) e.localizedMessage else e.message ) return null } finally { closeDatabase() } } } /** * Delete entries from the event history database. * * @param hash `long` containing the 32-bit FNV-1a hashed representation of an Event's data * @param from `long` representing the lower bounds of the date range to use when searching for the hash * @param to `long` representing the upper bounds of the date range to use when searching for the hash * @return `int` which will contain the number of rows deleted. */ override fun delete(hash: Long, from: Long, to: Long): Int { synchronized(dbMutex) { try { openDatabase() val whereClause = "$COLUMN_HASH = ? AND $COLUMN_TIMESTAMP >= ? AND $COLUMN_TIMESTAMP <= ?" val whereArgs = arrayOf(hash.toString(), from.toString(), to.toString()) val affectedRowsCount = database?.delete(TABLE_NAME, whereClause, whereArgs) ?: 0 Log.trace( CoreConstants.LOG_TAG, LOG_TAG, "Count of rows deleted in table $TABLE_NAME are $affectedRowsCount" ) return affectedRowsCount } catch (e: Exception) { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Failed to delete table rows (%s)", if (e.localizedMessage != null) e.localizedMessage else e.message ) } finally { closeDatabase() } return 0 } } private fun openDatabase() { database = SQLiteDatabaseHelper.openDatabase( databaseFile.path, SQLiteDatabaseHelper.DatabaseOpenMode.READ_WRITE ) } private fun closeDatabase() { SQLiteDatabaseHelper.closeDatabase(database) database = null } companion object { private const val LOG_TAG = "AndroidEventHistoryDatabase" private const val DATABASE_NAME = "com.adobe.module.core.eventhistory" private const val DATABASE_NAME_1X = "EventHistory" private const val TABLE_NAME = "Events" private const val COLUMN_HASH = "eventHash" private const val COLUMN_TIMESTAMP = "timestamp" private const val QUERY_COUNT = "count" private const val QUERY_COUNT_INDEX = 0 private const val QUERY_OLDEST = "oldest" private const val QUERY_OLDEST_INDEX = 1 private const val QUERY_NEWEST = "newest" private const val QUERY_NEWEST_INDEX = 2 } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/eventhub/history/EventHistoryDatabaseCreationException.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.eventhub.history /** * Constructor. * * @param message a `String` containing the [EventHistoryDatabase] creation * exception details. */ internal class EventHistoryDatabaseCreationException(message: String) : Exception(message)
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/eventhub/history/EventHistoryDatabase.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.eventhub.history /** Interface defining a database to be used by the SDK for storing event history. */ internal interface EventHistoryDatabase { data class QueryResult(val count: Int, val oldestTimestamp: Long?, val newestTimeStamp: Long?) /** * Insert a row into a table in the database. * * @param hash `long` containing the 32-bit FNV-1a hashed representation of an Event's data * @param timestampMS `long` Event's timestamp in milliseconds * @return a `boolean` which will contain the status of the database insert operation */ fun insert(hash: Long, timestampMS: Long): Boolean /** * Queries the database to search for the existence of events. * This method will count all records in the event history database that match the provided * hash and are within the bounds of the provided from and to timestamps. * * @param hash `long` containing the 32-bit FNV-1a hashed representation of an Event's data * @param from `long` a timestamp representing the lower bounds of the date range to use when searching for the hash * @param to `long` a timestamp representing the upper bounds of the date range to use when searching for the hash * @return a `QueryResult` object containing details of the matching records. If no database connection is available, returns null */ fun query(hash: Long, from: Long, to: Long): QueryResult? /** * Delete entries from the event history database. * * @param hash `long` containing the 32-bit FNV-1a hashed representation of an Event's data * @param from `long` representing the lower bounds of the date range to use when searching for the hash * @param to `long` representing the upper bounds of the date range to use when searching for the hash * @return `int` which will contain the number of rows deleted. */ fun delete(hash: Long, from: Long, to: Long): Int }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/migration/V4Migrator.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.migration import android.content.SharedPreferences import com.adobe.marketing.mobile.MobilePrivacyStatus import com.adobe.marketing.mobile.internal.CoreConstants import com.adobe.marketing.mobile.internal.migration.MigrationConstants.V4 import com.adobe.marketing.mobile.internal.migration.MigrationConstants.V5 import com.adobe.marketing.mobile.services.Log import com.adobe.marketing.mobile.services.ServiceProvider import org.json.JSONException import org.json.JSONObject import java.io.File internal class V4Migrator { private val v4SharedPreferences: SharedPreferences? by lazy { val appContext = ServiceProvider.getInstance().appContextService.applicationContext appContext?.getSharedPreferences(V4.DATASTORE_NAME, 0) } private val isMigrationRequired: Boolean get() { return v4SharedPreferences?.contains(V4.Lifecycle.INSTALL_DATE) ?: false } private val isConfigurationMigrationRequired: Boolean get() { return v4SharedPreferences?.contains(V4.Configuration.GLOBAL_PRIVACY_KEY) ?: false } private val isVisitorIdMigrationRequired: Boolean get() { val identityV5DataStore = ServiceProvider.getInstance().dataStoreService.getNamedCollection(V5.Identity.DATASTORE_NAME) return identityV5DataStore?.contains(V5.Identity.VISITOR_ID) ?: false } fun migrate() { if (v4SharedPreferences == null) { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "%s (v4 shared preferences), failed to migrate v4 storage", Log.UNEXPECTED_NULL_VALUE ) } if (isMigrationRequired) { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Migrating Adobe SDK v4 SharedPreferences for use with AEP SDK." ) migrateLocalStorage() migrateConfigurationLocalStorage() removeV4Databases() Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Full migration of v4 SharedPreferences successful." ) } else if (isConfigurationMigrationRequired) { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Migrating Adobe SDK v4 Configuration SharedPreferences for use with AEP SDK." ) migrateConfigurationLocalStorage() Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Full migration of v4 Configuration SharedPreferences successful." ) } if (isVisitorIdMigrationRequired) { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Migrating visitor identifier from Identity to Analytics." ) migrateVisitorId() Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Full migration of visitor identifier from Identity to Analytics successful." ) } } private fun migrateLocalStorage() { val v4DataStore = v4SharedPreferences ?: return val v4DataStoreEditor = v4DataStore.edit() // mobile services val mobileServicesV5DataStore = ServiceProvider.getInstance().dataStoreService.getNamedCollection(V5.MobileServices.DATASTORE_NAME) val installDateMillis = v4DataStore.getLong(V4.Lifecycle.INSTALL_DATE, 0L) if (installDateMillis > 0) { // convert milliseconds to seconds as it is handled in v5 mobileServicesV5DataStore.setLong( V5.MobileServices.DEFAULTS_KEY_INSTALLDATE, convertMsToSec(installDateMillis) ) } mobileServicesV5DataStore.setString( V5.MobileServices.REFERRER_DATA_JSON_STRING, v4DataStore.getString(V4.Acquisition.REFERRER_DATA, null) ) mobileServicesV5DataStore.setString( V5.MobileServices.DEFAULTS_KEY_REFERRER_UTM_SOURCE, v4DataStore.getString(V4.Acquisition.DEFAULTS_KEY_REFERRER_UTM_SOURCE, null) ) mobileServicesV5DataStore.setString( V5.MobileServices.DEFAULTS_KEY_REFERRER_UTM_MEDIUM, v4DataStore.getString(V4.Acquisition.DEFAULTS_KEY_REFERRER_UTM_MEDIUM, null) ) mobileServicesV5DataStore.setString( V5.MobileServices.DEFAULTS_KEY_REFERRER_UTM_TERM, v4DataStore.getString(V4.Acquisition.DEFAULTS_KEY_REFERRER_UTM_TERM, null) ) mobileServicesV5DataStore.setString( V5.MobileServices.DEFAULTS_KEY_REFERRER_UTM_CONTENT, v4DataStore.getString(V4.Acquisition.DEFAULTS_KEY_REFERRER_UTM_CONTENT, null) ) mobileServicesV5DataStore.setString( V5.MobileServices.DEFAULTS_KEY_REFERRER_UTM_CAMPAIGN, v4DataStore.getString(V4.Acquisition.DEFAULTS_KEY_REFERRER_UTM_CAMPAIGN, null) ) mobileServicesV5DataStore.setString( V5.MobileServices.DEFAULTS_KEY_REFERRER_TRACKINGCODE, v4DataStore.getString(V4.Acquisition.DEFAULTS_KEY_REFERRER_TRACKINGCODE, null) ) mobileServicesV5DataStore.setString( V5.MobileServices.SHARED_PREFERENCES_BLACK_LIST, v4DataStore.getString(V4.Messages.SHARED_PREFERENCES_BLACK_LIST, null) ) // don't remove V4.Acquisition.REFERRER_DATA at here, it will be removed by the acquisition // extension // v4DataStoreEditor.remove(V4.Acquisition.REFERRER_DATA); v4DataStoreEditor.remove(V4.Acquisition.DEFAULTS_KEY_REFERRER_UTM_SOURCE) v4DataStoreEditor.remove(V4.Acquisition.DEFAULTS_KEY_REFERRER_UTM_MEDIUM) v4DataStoreEditor.remove(V4.Acquisition.DEFAULTS_KEY_REFERRER_UTM_TERM) v4DataStoreEditor.remove(V4.Acquisition.DEFAULTS_KEY_REFERRER_UTM_CONTENT) v4DataStoreEditor.remove(V4.Acquisition.DEFAULTS_KEY_REFERRER_UTM_CAMPAIGN) v4DataStoreEditor.remove(V4.Acquisition.DEFAULTS_KEY_REFERRER_TRACKINGCODE) v4DataStoreEditor.remove(V4.Messages.SHARED_PREFERENCES_BLACK_LIST) v4DataStoreEditor.apply() Log.debug(CoreConstants.LOG_TAG, LOG_TAG, "Migration complete for Mobile Services data.") // acquisition val acquisitionV5DataStore = ServiceProvider.getInstance() .dataStoreService .getNamedCollection(V5.Acquisition.DATASTORE_NAME) acquisitionV5DataStore.setString( V5.Acquisition.REFERRER_DATA, v4DataStore.getString(V4.Acquisition.REFERRER_DATA, null) ) v4DataStoreEditor.remove(V4.Acquisition.REFERRER_DATA) v4DataStoreEditor.apply() Log.debug(CoreConstants.LOG_TAG, LOG_TAG, "Migration complete for Acquisition data.") // analytics val analyticsV5DataStore = ServiceProvider.getInstance() .dataStoreService .getNamedCollection(V5.Analytics.DATASTORE_NAME) analyticsV5DataStore.setString( V5.Analytics.AID, v4DataStore.getString(V4.Analytics.AID, null) ) analyticsV5DataStore.setBoolean( V5.Analytics.IGNORE_AID, v4DataStore.getBoolean(V4.Analytics.IGNORE_AID, false) ) analyticsV5DataStore.setString( V5.Analytics.VID, v4DataStore.getString(V4.Identity.VISITOR_ID, null) ) v4DataStoreEditor.remove(V4.Analytics.AID) v4DataStoreEditor.remove(V4.Analytics.IGNORE_AID) v4DataStoreEditor.remove(V4.Analytics.LAST_KNOWN_TIMESTAMP) v4DataStoreEditor.apply() Log.debug(CoreConstants.LOG_TAG, LOG_TAG, "Migration complete for Analytics data.") // audience manager val audienceV5DataStore = ServiceProvider.getInstance() .dataStoreService .getNamedCollection(V5.AudienceManager.DATASTORE_NAME) audienceV5DataStore.setString( V5.AudienceManager.USER_ID, v4DataStore.getString(V4.AudienceManager.USER_ID, null) ) v4DataStoreEditor.remove(V4.AudienceManager.USER_ID) v4DataStoreEditor.remove(V4.AudienceManager.USER_PROFILE) v4DataStoreEditor.apply() Log.debug(CoreConstants.LOG_TAG, LOG_TAG, "Migration complete for Audience Manager data.") // identity val identityV5DataStore = ServiceProvider.getInstance() .dataStoreService .getNamedCollection(V5.Identity.DATASTORE_NAME) identityV5DataStore.setString( V5.Identity.MID, v4DataStore.getString(V4.Identity.MID, null) ) identityV5DataStore.setString( V5.Identity.BLOB, v4DataStore.getString(V4.Identity.BLOB, null) ) identityV5DataStore.setString( V5.Identity.HINT, v4DataStore.getString(V4.Identity.HINT, null) ) identityV5DataStore.setString( V5.Identity.VISITOR_IDS, v4DataStore.getString(V4.Identity.VISITOR_IDS, null) ) identityV5DataStore.setBoolean( V5.Identity.PUSH_ENABLED, v4DataStore.getBoolean(V4.Identity.PUSH_ENABLED, false) ) v4DataStoreEditor.remove(V4.Identity.MID) v4DataStoreEditor.remove(V4.Identity.BLOB) v4DataStoreEditor.remove(V4.Identity.HINT) v4DataStoreEditor.remove(V4.Identity.VISITOR_ID) v4DataStoreEditor.remove(V4.Identity.VISITOR_IDS) v4DataStoreEditor.remove(V4.Identity.VISITOR_ID_SYNC) v4DataStoreEditor.remove(V4.Identity.VISITOR_ID_TTL) v4DataStoreEditor.remove(V4.Identity.ADVERTISING_IDENTIFIER) v4DataStoreEditor.remove(V4.Identity.PUSH_IDENTIFIER) v4DataStoreEditor.remove(V4.Identity.PUSH_ENABLED) v4DataStoreEditor.remove(V4.Identity.AID_SYNCED) v4DataStoreEditor.apply() Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Migration complete for Identity (Visitor ID Service) data." ) // lifecycle val lifecycleV5DataStore = ServiceProvider.getInstance() .dataStoreService .getNamedCollection(V5.Lifecycle.DATASTORE_NAME) if (installDateMillis > 0) { // convert milliseconds to seconds as it is handled in v5 lifecycleV5DataStore.setLong( V5.Lifecycle.INSTALL_DATE, convertMsToSec(installDateMillis) ) } lifecycleV5DataStore.setString( V5.Lifecycle.LAST_VERSION, v4DataStore.getString(V4.Lifecycle.LAST_VERSION, null) ) val lastUsedDateMillis = v4DataStore.getLong(V4.Lifecycle.LAST_USED_DATE, 0L) if (lastUsedDateMillis > 0) { lifecycleV5DataStore.setLong( V5.Lifecycle.LAST_USED_DATE, convertMsToSec(lastUsedDateMillis) ) } lifecycleV5DataStore.setInt( V5.Lifecycle.LAUNCHES, v4DataStore.getInt(V4.Lifecycle.LAUNCHES, 0) ) lifecycleV5DataStore.setBoolean( V5.Lifecycle.SUCCESFUL_CLOSE, v4DataStore.getBoolean(V4.Lifecycle.SUCCESFUL_CLOSE, false) ) v4DataStoreEditor.remove(V4.Lifecycle.INSTALL_DATE) v4DataStoreEditor.remove(V4.Lifecycle.LAST_VERSION) v4DataStoreEditor.remove(V4.Lifecycle.LAST_USED_DATE) v4DataStoreEditor.remove(V4.Lifecycle.LAUNCHES) v4DataStoreEditor.remove(V4.Lifecycle.SUCCESFUL_CLOSE) v4DataStoreEditor.remove(V4.Lifecycle.CONTEXT_DATA) v4DataStoreEditor.remove(V4.Lifecycle.START_DATE) v4DataStoreEditor.remove(V4.Lifecycle.PAUSE_DATE) v4DataStoreEditor.remove(V4.Lifecycle.LAUNCHES_AFTER_UPGRADE) v4DataStoreEditor.remove(V4.Lifecycle.UPGRADE_DATE) v4DataStoreEditor.remove(V4.Lifecycle.OS) v4DataStoreEditor.remove(V4.Lifecycle.APPLICATION_ID) v4DataStoreEditor.apply() Log.debug(CoreConstants.LOG_TAG, LOG_TAG, "Migration complete for Lifecycle data.") // target val targetV5DataStore = ServiceProvider.getInstance() .dataStoreService .getNamedCollection(V5.Target.DATASTORE_NAME) targetV5DataStore.setString( V5.Target.TNT_ID, v4DataStore.getString(V4.Target.TNT_ID, null) ) targetV5DataStore.setString( V5.Target.THIRD_PARTY_ID, v4DataStore.getString(V4.Target.THIRD_PARTY_ID, null) ) targetV5DataStore.setString( V5.Target.SESSION_ID, v4DataStore.getString(V4.Target.SESSION_ID, null) ) targetV5DataStore.setString( V5.Target.EDGE_HOST, v4DataStore.getString(V4.Target.EDGE_HOST, null) ) v4DataStoreEditor.remove(V4.Target.TNT_ID) v4DataStoreEditor.remove(V4.Target.THIRD_PARTY_ID) v4DataStoreEditor.remove(V4.Target.SESSION_ID) v4DataStoreEditor.remove(V4.Target.EDGE_HOST) v4DataStoreEditor.remove(V4.Target.LAST_TIMESTAMP) v4DataStoreEditor.remove(V4.Target.COOKIE_EXPIRES) v4DataStoreEditor.remove(V4.Target.COOKIE_VALUE) v4DataStoreEditor.apply() Log.debug(CoreConstants.LOG_TAG, LOG_TAG, "Migrating complete for Target data.") } private fun migrateConfigurationLocalStorage() { val v4DataStore = v4SharedPreferences ?: return val v4DataStoreEditor = v4DataStore.edit() // Configuration val configurationV5DataStore = ServiceProvider.getInstance() .dataStoreService .getNamedCollection(V5.Configuration.DATASTORE_NAME) val v4PrivacyStatus = v4DataStore.getInt(V4.Configuration.GLOBAL_PRIVACY_KEY, -1) if (v4PrivacyStatus in 0..2) { val v5PrivacyStatus = when (v4PrivacyStatus) { 0 -> MobilePrivacyStatus.OPT_IN 1 -> MobilePrivacyStatus.OPT_OUT 2 -> MobilePrivacyStatus.UNKNOWN else -> MobilePrivacyStatus.UNKNOWN } val v5OverriddenConfig = configurationV5DataStore.getString( V5.Configuration.PERSISTED_OVERRIDDEN_CONFIG, null ) if (v5OverriddenConfig != null) { try { val v5JsonObj = JSONObject(v5OverriddenConfig) if (!v5JsonObj.has(V5.Configuration.GLOBAL_PRIVACY_KEY)) { // V5 has overridden config data, but global privacy is not set, migrate v4 // value v5JsonObj.put( V5.Configuration.GLOBAL_PRIVACY_KEY, v5PrivacyStatus.value ) configurationV5DataStore.setString( V5.Configuration.PERSISTED_OVERRIDDEN_CONFIG, v5JsonObj.toString() ) } else { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "V5 configuration data already contains setting for global" + " privacy. V4 global privacy not migrated." ) } } catch (e: JSONException) { Log.error( CoreConstants.LOG_TAG, LOG_TAG, "Failed to serialize v5 configuration data. Unable to migrate v4" + " configuration data to v5. %s", e.localizedMessage ) } } else { // V5 does not contain overridden data, so add one with just migrated privacy status val v5ConfigMap: MutableMap<String?, Any?> = HashMap() v5ConfigMap[V5.Configuration.GLOBAL_PRIVACY_KEY] = v5PrivacyStatus.value val v5JsonObj = JSONObject(v5ConfigMap) configurationV5DataStore.setString( V5.Configuration.PERSISTED_OVERRIDDEN_CONFIG, v5JsonObj.toString() ) } } v4DataStoreEditor.remove(V4.Configuration.GLOBAL_PRIVACY_KEY) v4DataStoreEditor.apply() Log.debug(CoreConstants.LOG_TAG, LOG_TAG, "Migration complete for Configuration data.") } private fun migrateVisitorId() { val identityV5DataStore = ServiceProvider.getInstance() .dataStoreService .getNamedCollection(V5.Identity.DATASTORE_NAME) val analyticsV5DataStore = ServiceProvider.getInstance() .dataStoreService .getNamedCollection(V5.Analytics.DATASTORE_NAME) if (identityV5DataStore == null || analyticsV5DataStore == null) { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "%s (Identity or Analytics data store), failed to migrate visitor id.", Log.UNEXPECTED_NULL_VALUE ) return } if (!analyticsV5DataStore.contains(V5.Analytics.VID)) { val vid = identityV5DataStore.getString(V5.Identity.VISITOR_ID, null) analyticsV5DataStore.setString(V5.Analytics.VID, vid) } identityV5DataStore.remove(V5.Identity.VISITOR_ID) } private fun removeV4Databases() { val cacheDirectory = ServiceProvider.getInstance().deviceInfoService.applicationCacheDir if (cacheDirectory == null) { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "%s (cache directory), failed to delete V4 databases", Log.UNEXPECTED_NULL_VALUE ) return } V4.DATABASE_NAMES.forEach { databaseName -> try { val databaseFile = File(cacheDirectory, databaseName) if (databaseFile.exists() && databaseFile.delete()) { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Removed V4 database %s successfully", databaseName ) } } catch (e: SecurityException) { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "Failed to delete V4 database with name %s (%s)", databaseName, e ) } } } private fun convertMsToSec(timestampMs: Long): Long { return timestampMs / 1000 } companion object { private const val LOG_TAG = "MobileCore/V4Migrator" } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/migration/MigrationConstants.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.migration internal object MigrationConstants { object V4 { const val DATASTORE_NAME = "APP_MEASUREMENT_CACHE" object Lifecycle { const val INSTALL_DATE = "ADMS_InstallDate" const val UPGRADE_DATE = "ADMS_UpgradeDate" const val LAST_USED_DATE = "ADMS_LastDateUsed" const val LAUNCHES_AFTER_UPGRADE = "ADMS_LaunchesAfterUpgrade" const val LAUNCHES = "ADMS_Launches" const val LAST_VERSION = "ADMS_LastVersion" const val START_DATE = "ADMS_SessionStart" const val PAUSE_DATE = "ADMS_PauseDate" const val SUCCESFUL_CLOSE = "ADMS_SuccessfulClose" const val OS = "ADOBEMOBILE_STOREDDEFAULTS_OS" const val APPLICATION_ID = "ADOBEMOBILE_STOREDDEFAULTS_APPID" const val CONTEXT_DATA = "ADMS_LifecycleData" } object Acquisition { const val REFERRER_DATA = "ADMS_Referrer_ContextData_Json_String" const val DEFAULTS_KEY_REFERRER_UTM_SOURCE = "utm_source" const val DEFAULTS_KEY_REFERRER_UTM_MEDIUM = "utm_medium" const val DEFAULTS_KEY_REFERRER_UTM_TERM = "utm_term" const val DEFAULTS_KEY_REFERRER_UTM_CONTENT = "utm_content" const val DEFAULTS_KEY_REFERRER_UTM_CAMPAIGN = "utm_campaign" const val DEFAULTS_KEY_REFERRER_TRACKINGCODE = "trackingcode" } object AudienceManager { const val USER_ID = "AAMUserId" const val USER_PROFILE = "AAMUserProfile" } object Target { const val THIRD_PARTY_ID = "ADBMOBILE_TARGET_3RD_PARTY_ID" const val TNT_ID = "ADBMOBILE_TARGET_TNT_ID" const val LAST_TIMESTAMP = "ADBMOBILE_TARGET_LAST_TIMESTAMP" const val SESSION_ID = "ADBMOBILE_TARGET_SESSION_ID" const val EDGE_HOST = "ADBMOBILE_TARGET_EDGE_HOST" const val COOKIE_EXPIRES = "mboxPC_Expires" const val COOKIE_VALUE = "mboxPC_Value" } object Analytics { const val AID = "ADOBEMOBILE_STOREDDEFAULTS_AID" const val IGNORE_AID = "ADOBEMOBILE_STOREDDEFAULTS_IGNORE_AID" const val LAST_KNOWN_TIMESTAMP = "ADBLastKnownTimestampKey" } object Identity { const val MID = "ADBMOBILE_PERSISTED_MID" const val BLOB = "ADBMOBILE_PERSISTED_MID_BLOB" const val HINT = "ADBMOBILE_PERSISTED_MID_HINT" const val VISITOR_IDS = "ADBMOBILE_VISITORID_IDS" const val VISITOR_ID_SYNC = "ADBMOBILE_VISITORID_SYNC" const val VISITOR_ID_TTL = "ADBMOBILE_VISITORID_TTL" const val VISITOR_ID = "APP_MEASUREMENT_VISITOR_ID" const val ADVERTISING_IDENTIFIER = "ADOBEMOBILE_STOREDDEFAULTS_ADVERTISING_IDENTIFIER" const val PUSH_IDENTIFIER = "ADBMOBILE_KEY_PUSH_TOKEN" const val PUSH_ENABLED = "ADBMOBILE_KEY_PUSH_ENABLED" const val AID_SYNCED = "ADOBEMOBILE_STOREDDEFAULTS_AID_SYNCED" } object Messages { const val SHARED_PREFERENCES_BLACK_LIST = "messagesBlackList" } object Configuration { const val GLOBAL_PRIVACY_KEY = "PrivacyStatus" } val DATABASE_NAMES = arrayListOf( "ADBMobile3rdPartyDataCache.sqlite", // signals "ADBMobilePIICache.sqlite", // signals pii "ADBMobileDataCache.sqlite", // analytics db "ADBMobileTimedActionsCache.sqlite" // analytics timed actions ) } object V5 { object Lifecycle { const val DATASTORE_NAME = "AdobeMobile_Lifecycle" const val INSTALL_DATE = "InstallDate" const val UPGRADE_DATE = "UpgradeDate" const val LAST_USED_DATE = "LastDateUsed" const val LAUNCHES_AFTER_UPGRADE = "LaunchesAfterUpgrade" const val LAUNCHES = "Launches" const val LAST_VERSION = "LastVersion" const val START_DATE = "ADMS_SessionStart" const val PAUSE_DATE = "PauseDate" const val SUCCESFUL_CLOSE = "SuccessfulClose" const val OS = "OperatingSystem" const val APPLICATION_ID = "ApplicationId" } object Acquisition { const val DATASTORE_NAME = "Acquisition" const val REFERRER_DATA = "ADMS_Referrer_ContextData_Json_String" } object AudienceManager { const val DATASTORE_NAME = "AAMDataStore" const val USER_ID = "AAMUserId" const val USER_PROFILE = "AAMUserProfile" } object Target { const val DATASTORE_NAME = "ADOBEMOBILE_TARGET" const val THIRD_PARTY_ID = "THIRD_PARTY_ID" const val TNT_ID = "TNT_ID" const val SESSION_ID = "SESSION_ID" const val EDGE_HOST = "EDGE_HOST" } object Analytics { const val DATASTORE_NAME = "AnalyticsDataStorage" const val AID = "ADOBEMOBILE_STOREDDEFAULTS_AID" const val IGNORE_AID = "ADOBEMOBILE_STOREDDEFAULTS_IGNORE_AID" const val VID = "ADOBEMOBILE_STOREDDEFAULTS_VISITOR_IDENTIFIER" } object MobileServices { const val DATASTORE_NAME = "ADBMobileServices" const val DEFAULTS_KEY_INSTALLDATE = "ADMS_Legacy_InstallDate" const val REFERRER_DATA_JSON_STRING = "ADMS_Referrer_ContextData_Json_String" const val SHARED_PREFERENCES_BLACK_LIST = "messagesBlackList" const val DEFAULTS_KEY_REFERRER_UTM_SOURCE = "utm_source" const val DEFAULTS_KEY_REFERRER_UTM_MEDIUM = "utm_medium" const val DEFAULTS_KEY_REFERRER_UTM_TERM = "utm_term" const val DEFAULTS_KEY_REFERRER_UTM_CONTENT = "utm_content" const val DEFAULTS_KEY_REFERRER_UTM_CAMPAIGN = "utm_campaign" const val DEFAULTS_KEY_REFERRER_TRACKINGCODE = "trackingcode" } object Identity { const val DATASTORE_NAME = "visitorIDServiceDataStore" const val MID = "ADOBEMOBILE_PERSISTED_MID" const val BLOB = "ADOBEMOBILE_PERSISTED_MID_BLOB" const val HINT = "ADOBEMOBILE_PERSISTED_MID_HINT" const val VISITOR_IDS = "ADOBEMOBILE_VISITORID_IDS" const val VISITOR_ID = "ADOBEMOBILE_VISITOR_ID" const val PUSH_ENABLED = "ADOBEMOBILE_PUSH_ENABLED" } object Configuration { const val DATASTORE_NAME = "AdobeMobile_ConfigState" const val PERSISTED_OVERRIDDEN_CONFIG = "config.overridden.map" const val GLOBAL_PRIVACY_KEY = "global.privacy" } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/HitProcessing.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import androidx.annotation.NonNull; // A Type provide the functionality for processing hits. public interface HitProcessing { /** * Determines the interval at which a hit should be retried * * @param entity The hit whose retry interval is to be computed * @return Hit retry interval in seconds. */ int retryInterval(@NonNull DataEntity entity); /** * Function that is invoked with a {@link DataEntity} and provides functionality for processing * the hit. * * @param entity The <code>DataEntity</code> to be processed. * @param processingResult Return a boolean variable indicating <code>DataEntity</code> is * successfully processed or not. */ void processHit(@NonNull DataEntity entity, @NonNull HitProcessingResult processingResult); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/DataQueuing.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; /** Creates and return instances of {@link DataQueue}. */ public interface DataQueuing { /** * Creates an instance of {@link DataQueue} if it was not previously cached, otherwise the * cached instance is returned. * * @param databaseName {@link String}: name of the database, to be created for {@link * DataEntity} persistence. * @return instance of DataQueue. */ DataQueue getDataQueue(final String databaseName); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/AppContextService.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import android.app.Activity; import android.app.Application; import android.content.Context; import android.net.ConnectivityManager; import androidx.annotation.NonNull; import androidx.annotation.Nullable; public interface AppContextService { /** * Set the Android {@link Application}, which enables the SDK get the app {@code Context}, * register a {@link Application.ActivityLifecycleCallbacks} to monitor the lifecycle of the app * and get the {@link android.app.Activity} on top of the screen. * * <p>NOTE: This method should be called right after the app starts, so it gives the SDK all the * contexts it needed. * * @param application the Android {@link Application} instance. It should not be null. */ void setApplication(@NonNull final Application application); /** * Get the global {@link Application} object of the current process. * * <p>NOTE: {@link #setApplication(Application)} must be called before calling this method. * * @return the current {@code Application}, or null if no {@code Application} was set or the * {@code Application} process was destroyed. */ @Nullable Application getApplication(); /** * Returns the current {@code Activity} * * @return the current {@code Activity} */ @Nullable Activity getCurrentActivity(); /** * Returns the application {@code Context} * * @return the application {@code Context} */ @Nullable Context getApplicationContext(); /** * Get the current application state. * * @return AppState the current application state */ @NonNull AppState getAppState(); /** * Get the instance of {@link ConnectivityManager} * * @return the instance of {@link ConnectivityManager} */ @Nullable ConnectivityManager getConnectivityManager(); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/NetworkService.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import android.net.ConnectivityManager; import androidx.annotation.VisibleForTesting; import com.adobe.marketing.mobile.internal.util.NetworkUtils; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** Implementation of {@link Networking} service */ class NetworkService implements Networking { private static final String TAG = NetworkService.class.getSimpleName(); private static final String REQUEST_HEADER_KEY_USER_AGENT = "User-Agent"; private static final String REQUEST_HEADER_KEY_LANGUAGE = "Accept-Language"; private static final int THREAD_POOL_CORE_SIZE = 0; private static final int THREAD_POOL_MAXIMUM_SIZE = 32; private static final int THREAD_POOL_KEEP_ALIVE_TIME = 60; private static final int SEC_TO_MS_MULTIPLIER = 1000; private final ExecutorService executorService; NetworkService() { // define THREAD_POOL_MAXIMUM_SIZE instead of using a unbounded thread pool, mainly to // prevent a wrong usage from extensions // to blow off the Android system. executorService = new ThreadPoolExecutor( THREAD_POOL_CORE_SIZE, THREAD_POOL_MAXIMUM_SIZE, THREAD_POOL_KEEP_ALIVE_TIME, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); } @VisibleForTesting NetworkService(final ExecutorService executorService) { this.executorService = executorService; } @Override public void connectAsync(final NetworkRequest request, final NetworkCallback callback) { ConnectivityManager connectivityManager = ServiceProvider.getInstance().getAppContextService().getConnectivityManager(); if (connectivityManager != null) { if (!NetworkUtils.isInternetAvailable(connectivityManager)) { Log.trace(ServiceConstants.LOG_TAG, TAG, "The Android device is offline."); callback.call(null); return; } } else { Log.debug( ServiceConstants.LOG_TAG, TAG, "ConnectivityManager instance is null. Unable to the check the network" + " condition."); } try { executorService.submit( () -> { HttpConnecting connection = doConnection(request); if (callback != null) { callback.call(connection); } else { // If no callback is passed by the client, close the connection. if (connection != null) { connection.close(); } } }); } catch (final Exception e) { // to catch RejectedExecutionException when the thread pool is saturated Log.warning( ServiceConstants.LOG_TAG, TAG, String.format( "Failed to send request for (%s) [%s]", request.getUrl(), (e.getLocalizedMessage() != null ? e.getLocalizedMessage() : e.getMessage()))); if (callback != null) { callback.call(null); } } } /** * Performs the actual connection to the specified {@code url}. * * <p>It sets the default connection headers if none were provided through the {@code * requestProperty} parameter. You can override the default user agent and language headers if * they are present in {@code requestProperty} * * <p>This method will return null, if failed to establish connection to the resource. * * @param request {@link NetworkRequest} used for connection * @return {@link HttpConnecting} instance, representing a connection attempt */ private HttpConnecting doConnection(final NetworkRequest request) { HttpConnecting connection = null; if (request.getUrl() == null || !request.getUrl().contains("https")) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format( "Invalid URL (%s), only HTTPS protocol is supported", request.getUrl())); return null; } final Map<String, String> headers = getDefaultHeaders(); if (request.getHeaders() != null) { headers.putAll(request.getHeaders()); } try { final URL serverUrl = new URL(request.getUrl()); final String protocol = serverUrl.getProtocol(); /* * Only https is supported as of now. * No special handling for https is supported for now. */ if (protocol != null && "https".equalsIgnoreCase(protocol)) { try { final HttpConnectionHandler httpConnectionHandler = new HttpConnectionHandler(serverUrl); if (httpConnectionHandler.setCommand(request.getMethod())) { httpConnectionHandler.setRequestProperty(headers); httpConnectionHandler.setConnectTimeout( request.getConnectTimeout() * SEC_TO_MS_MULTIPLIER); httpConnectionHandler.setReadTimeout( request.getReadTimeout() * SEC_TO_MS_MULTIPLIER); connection = httpConnectionHandler.connect(request.getBody()); } } catch (final IOException | SecurityException e) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format( "Could not create a connection to URL (%s) [%s]", request.getUrl(), (e.getLocalizedMessage() != null ? e.getLocalizedMessage() : e.getMessage()))); } } } catch (final MalformedURLException e) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format( "Could not connect, invalid URL (%s) [%s]!!", request.getUrl(), e)); } return connection; } /** * Creates a {@code Map<String, String>} with the default headers: default user agent and active * language. * * <p>This method is used to retrieve the default headers to be appended to any network * connection made by the SDK. * * @return {@code Map<String, String>} containing the default user agent and active language if * {@code #DeviceInforming} is not null or an empty Map otherwise * @see DeviceInforming#getDefaultUserAgent() * @see DeviceInforming#getLocaleString() */ private Map<String, String> getDefaultHeaders() { final Map<String, String> defaultHeaders = new HashMap<>(); final DeviceInforming deviceInfoService = ServiceProvider.getInstance().getDeviceInfoService(); if (deviceInfoService == null) { return defaultHeaders; } String userAgent = deviceInfoService.getDefaultUserAgent(); if (!isNullOrEmpty(userAgent)) { defaultHeaders.put(REQUEST_HEADER_KEY_USER_AGENT, userAgent); } String locale = deviceInfoService.getLocaleString(); if (!isNullOrEmpty(locale)) { defaultHeaders.put(REQUEST_HEADER_KEY_LANGUAGE, locale); } return defaultHeaders; } private boolean isNullOrEmpty(final String str) { return str == null || str.trim().isEmpty(); } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/NetworkingConstants.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.Arrays; public class NetworkingConstants { private NetworkingConstants() {} public class Headers { private Headers() {} public static final String IF_MODIFIED_SINCE = "If-Modified-Since"; public static final String IF_NONE_MATCH = "If-None-Match"; public static final String LAST_MODIFIED = "Last-Modified"; public static final String ETAG = "Etag"; public static final String CONTENT_TYPE = "Content-Type"; public static final String ACCEPT_LANGUAGE = "Accept-Language"; public static final String ACCEPT = "Accept"; } public class HeaderValues { private HeaderValues() {} public static final String CONTENT_TYPE_JSON_APPLICATION = "application/json"; public static final String CONTENT_TYPE_URL_ENCODED = "application/x-www-form-urlencoded"; public static final String ACCEPT_TEXT_HTML = "text/html"; } public static ArrayList<Integer> RECOVERABLE_ERROR_CODES = new ArrayList<Integer>( Arrays.asList( HttpURLConnection.HTTP_CLIENT_TIMEOUT, HttpURLConnection.HTTP_GATEWAY_TIMEOUT, HttpURLConnection.HTTP_UNAVAILABLE)); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/DisplayInfoService.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import android.util.DisplayMetrics; class DisplayInfoService implements DeviceInforming.DisplayInformation { private final DisplayMetrics displayMetrics; DisplayInfoService(final DisplayMetrics displayMetrics) { this.displayMetrics = displayMetrics; } @Override public int getWidthPixels() { return displayMetrics.widthPixels; } @Override public int getHeightPixels() { return displayMetrics.heightPixels; } @Override public int getDensityDpi() { return displayMetrics.densityDpi; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/DeviceInforming.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import java.io.File; import java.io.InputStream; import java.util.Locale; public interface DeviceInforming { /** Represents the possible network connection status for the Adobe SDK. */ enum ConnectionStatus { /** Network connectivity exists. */ CONNECTED, /** No Network connectivity. */ DISCONNECTED, /** Unknown when unable to access the connectivity status. */ UNKNOWN, } /** Represents the possible device types. */ enum DeviceType { PHONE, TABLET, WATCH, UNKNOWN, } interface NetworkConnectionActiveListener { /** Invoked when the connection has become active. */ void onActive(); } interface DisplayInformation { /** * Returns absolute width of the available display size in pixels. * * @return width in pixels if available. -1 otherwise. */ int getWidthPixels(); /** * Returns absolute height of the available display size in pixels. * * @return height in pixels if available. -1 otherwise. */ int getHeightPixels(); /** * Returns the screen dots-per-inch * * @return dpi if available. -1 otherwise. */ int getDensityDpi(); } /** * Returns the directory which can be used as a application data directory. * * @return A {@link File} representing the application data directory, or null if not available * on the platform */ File getApplicationBaseDir(); /** * Returns active locale's value in string format. The default value is en-US * * @return Locale as {@code String} */ String getLocaleString(); /** * Returns the default platform/device user agent value * * @return {@link String} containing the default user agent */ String getDefaultUserAgent(); /** * Returns the application specific cache directory. The application will be able to read and * write to the directory, but there is no guarantee made as to the persistence of the data (it * may be deleted by the system when storage is required). * * @return A {@link File} representing the application cache directory, or null if not available * on the platform. */ File getApplicationCacheDir(); /** * Open the requested asset returns an InputStream to read its contents. * * @param fileName asset's name which is to be retrieved * @return an {@link InputStream} to read file's content, or null if not available on the * platform */ InputStream getAsset(String fileName); /** * Returns the property value specific to the key from the manifest file. * * @param resourceKey resource key * @return A {@link String} value of the requested property, or null if there is no value * defined for the key */ String getPropertyFromManifest(String resourceKey); /** * Returns the application name. * * @return A {@link String} representing Application name if available, null otherwise */ String getApplicationName(); /** * Returns the application package name. * * @return A {@link String} representing Application package name if available, null otherwise */ String getApplicationPackageName(); /** * Returns the application version. * * @return A {@link String} representing Application version if available, null otherwise */ String getApplicationVersion(); /** * Returns the application version code as a string. * * @return application version code formatted as {@link String} using the active locale, if * available. null otherwise */ String getApplicationVersionCode(); /** * Returns the currently selected / active locale value with respect to the application context. * * @return A {@link Locale} value, if available, null otherwise */ Locale getActiveLocale(); /** * Returns the currently selected / active locale value on the device settings as set by the * user. * * @return A {@link Locale} value, if available, null otherwise */ Locale getSystemLocale(); /** * Returns information about the display hardware, as returned by the underlying OS. * * @return {@link DeviceInforming.DisplayInformation} instance, or null if application context * is null * @see DeviceInforming.DisplayInformation */ DeviceInforming.DisplayInformation getDisplayInformation(); /** * Returns the current screen orientation * * @return a {@code int} value indicates the orientation. 0 for unknown, 1 for portrait and 2 * for landscape */ int getCurrentOrientation(); /** * Returns the string representation of the operating system name. * * @return Operating system name {@link String}. */ String getOperatingSystemName(); /** * Returns the string representation of the canonical platform name. * * @return Platform name {@link String}. */ String getCanonicalPlatformName(); /** * Returns the string representation of the operating system version. * * @return Operating system version {@link String}. */ String getOperatingSystemVersion(); /** * Returns the device brand. * * @return {@code String} containing the consumer-visible brand name */ String getDeviceBrand(); /** * The device manufacturer's name. * * @return Device manufacturer name {@link String} if available. null otherwise */ String getDeviceManufacturer(); /** * Returns the device name. * * @return {@link String} Device name if available, null otherwise */ String getDeviceName(); /** * Returns name of the industrial design for the device * * @return {@code String} containing the name of the industrial design */ String getDevice(); /** * Returns the device type. * * <ul> * <li>If {@link DeviceInforming.DeviceType#PHONE}, for a Phone type device * <li>If {@link DeviceInforming.DeviceType#TABLET}, for a Tablet type device * <li>If {@link DeviceInforming.DeviceType#WATCH}, for a Watch type device * <li>If {@link DeviceInforming.DeviceType#UNKNOWN}, when device type cannot be determined * </ul> * * @return {@link DeviceInforming.DeviceType} representing the device type * @see DeviceInforming.DeviceType */ DeviceInforming.DeviceType getDeviceType(); /** * Returns a string that identifies a particular device OS build. This value may be present on * Android devices, with a value like "M4-rc20". The value is platform dependent and platform * specific. * * @return {@link String} Build ID string if available. null otherwise */ String getDeviceBuildId(); /** * Returns the device's mobile carrier name. * * @return A {@link String} representing the carrier name. null if this value is not available */ String getMobileCarrierName(); /** * Indicates whether network connectivity exists and it is possible to establish connections and * pass data. * * <p>Always call this before attempting to perform data transactions. * * <ul> * <li>If {@link DeviceInforming.ConnectionStatus#CONNECTED}, if we have network connectivity. * <li>If {@link DeviceInforming.ConnectionStatus#DISCONNECTED}, if do not have network * connectivity. * <li>If {@link DeviceInforming.ConnectionStatus#UNKNOWN}, if unable to determine the network * connectivity. * </ul> * * @return {@link DeviceInforming.ConnectionStatus} representing the current network status * @see DeviceInforming.ConnectionStatus */ DeviceInforming.ConnectionStatus getNetworkConnectionStatus(); /** * Invokes a callback when the network connection status changes. * * @param listener {@link DeviceInforming.NetworkConnectionActiveListener} listener that will * get invoked once when the connection status changes. * @see #getNetworkConnectionStatus() * @return whether the registration was successful */ boolean registerOneTimeNetworkConnectionActiveListener( DeviceInforming.NetworkConnectionActiveListener listener); /** * Returns a string that identifies the SDK running mode, e.g. Application, Extension. * * @return {@link String} containing running mode */ String getRunMode(); /** * Get unique identifier for device. * * @return {@code String} containing the device UUID or null if application {@code Context} is * null */ String getDeviceUniqueId(); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/HttpConnecting.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import java.io.InputStream; // The HttpConnecting represents the response to NetworkRequest, to be used for network completion // handlers and when overriding the network stack in place of internal network connection // implementation. public interface HttpConnecting { /** * Returns an input stream from the connection to read the application server response, if * available. * * @return {@link InputStream} connection response input stream */ InputStream getInputStream(); /** * Returns an input stream from the connection to read the application server error response, if * available. * * @return {@link InputStream} connection response error stream */ InputStream getErrorStream(); /** * Returns the connection attempt response code for the connection request. * * @return {@code int} indicating connection response code */ int getResponseCode(); /** * Returns a connection attempt response message, if available. * * @return {@link String} containing connection response message */ String getResponseMessage(); /** * Returns a value for the response property key that might have been set when a connection was * made to the resource pointed to by the Url. * * <p>This is protocol specific. For example, HTTP urls could have properties like * "last-modified", or "ETag" set. * * @param responsePropertyKey {@link String} containing response property key * @return {@code String} corresponding to the response property value for the key specified, or * null, if the key does not exist. */ String getResponsePropertyValue(final String responsePropertyKey); /** Close this connection. */ void close(); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/NetworkRequest.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import java.util.Map; // NetworkRequest class contains the data needed to initiate a network request public class NetworkRequest { private final String url; private final HttpMethod method; private final byte[] body; private final Map<String, String> headers; private final int connectTimeout; private final int readTimeout; /** * Constructor for NetworkRequest * * @param url {@link String} containing the full url for connection * @param method {@link com.adobe.marketing.mobile.services.HttpMethod}, for example "POST", * "GET" etc. * @param body {@code byte[]} array specifying payload to send to the server * @param headers {@code Map<String, String>} containing any additional key value pairs to be * used while requesting a connection to the url depending on the {@code method} used * @param connectTimeout {@code int} indicating connect timeout value in seconds * @param readTimeout {@code int} indicating the timeout, in seconds, that will be used to wait * for a read to finish after a successful connect */ public NetworkRequest( final String url, final HttpMethod method, final byte[] body, final Map<String, String> headers, final int connectTimeout, final int readTimeout) { this.method = method; this.body = body; this.url = url; this.headers = headers; this.connectTimeout = connectTimeout; this.readTimeout = readTimeout; } public String getUrl() { return url; } public HttpMethod getMethod() { return method; } public byte[] getBody() { return body; } public Map<String, String> getHeaders() { return headers; } public int getConnectTimeout() { return connectTimeout; } public int getReadTimeout() { return readTimeout; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/DataQueue.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import java.util.List; /** A Thread-Safe Queue used to store {@link DataEntity} Objects. */ public interface DataQueue { /** * Add a new {@link DataEntity} Object to {@link DataQueue} * * @param dataEntity, instance of {@link DataEntity} * @return true if successfully added else false. */ boolean add(final DataEntity dataEntity); /** Retrieves the head of {@link DataQueue} else returns null if {@link DataQueue} is empty. */ DataEntity peek(); /** * Retrieves the first n entries in this {@link DataQueue}. Returns null if {@link DataQueue} is * empty. */ List<DataEntity> peek(final int n); /** * Removes the head of this {@link DataQueue} * * @return true if successfully removed else returns false. */ boolean remove(); /** * Removed the first n elements in this {@link DataQueue} * * @return true if successfully removed else returns false. */ boolean remove(final int n); /** * Removes all stored {@link DataEntity} objects. * * @return true if successfully removed else returns false. */ boolean clear(); /** Returns the count of {@link DataEntity} objects in this {@link DataQueue}. */ int count(); /** Closes the current {@link DataQueue}. */ void close(); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/HitProcessingResult.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; @FunctionalInterface public interface HitProcessingResult { void complete(boolean result); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/DeviceInfoService.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.content.res.Configuration; import android.content.res.Resources; import android.net.ConnectivityManager; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.telephony.TelephonyManager; import android.util.DisplayMetrics; import com.adobe.marketing.mobile.internal.util.NetworkUtils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.Locale; /** Implementation of {@link DeviceInforming} service */ class DeviceInfoService implements DeviceInforming { private static final String LOG_TAG = "DeviceInfoService"; private static final String CANONICAL_PLATFORM_NAME = "android"; private static final String ANDROID_OS_STRING = "Android"; private static final String UNEXPECTED_NULL_VALUE = "Unexpected Null Value"; DeviceInfoService() {} /** * Returns the currently selected / active locale value with respect to the application context. * * @return A {@link Locale} value, if available, null otherwise */ public Locale getActiveLocale() { final Context context = getApplicationContext(); if (context == null) { return null; } return getLocaleFromResources(context.getResources()); } /** * Returns the currently selected / active locale value on the device settings as set by the * user. * * @return A {@link Locale} value, if available, null otherwise */ @Override public Locale getSystemLocale() { return getLocaleFromResources(Resources.getSystem()); } @Override public DisplayInformation getDisplayInformation() { final Context context = getApplicationContext(); if (context == null) { return null; } Resources resources = context.getResources(); if (resources == null) { return null; } return new DisplayInfoService(resources.getDisplayMetrics()); } @Override public int getCurrentOrientation() { Activity currentActivity = getCurrentActivity(); if (currentActivity == null) { return 0; // neither landscape nor portrait } return currentActivity.getResources().getConfiguration().orientation; } @Override public String getCanonicalPlatformName() { return CANONICAL_PLATFORM_NAME; } /** * Returns the string representation of the operating system name. * * @return Operating system name {@link String}. */ @Override public String getOperatingSystemName() { return ANDROID_OS_STRING; } /** * Returns the string representation of the operating system version. * * @return Operating system version {@link String}. */ public String getOperatingSystemVersion() { return Build.VERSION.RELEASE; } /** * Returns the device brand. * * @return {@code String} containing the consumer-visible brand name */ @Override public String getDeviceBrand() { return Build.BRAND; } @Override public String getDeviceManufacturer() { return Build.MANUFACTURER; } /** * Returns a human readable device name. * * @return Device name {@link String} if available. null otherwise. */ public String getDeviceName() { return Build.MODEL; } /** * Returns name of the industrial design for the device * * @return {@code String} containing the name of the industrial design */ @Override public String getDevice() { return Build.DEVICE; } @Override public DeviceType getDeviceType() { final Context context = getApplicationContext(); final double MIN_TABLET_INCHES = 6.5d; if (context == null) { return DeviceInforming.DeviceType.UNKNOWN; } final Resources resources = context.getResources(); if (resources == null) { return DeviceInforming.DeviceType.UNKNOWN; } final int uiMode = resources.getConfiguration().uiMode; if ((uiMode & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_WATCH) { return DeviceType.WATCH; } final DisplayMetrics displayMetrics = resources.getDisplayMetrics(); final float yInches = displayMetrics.heightPixels / displayMetrics.ydpi; final float xInches = displayMetrics.widthPixels / displayMetrics.xdpi; final double diagonalInches = Math.sqrt(xInches * xInches + yInches * yInches); return diagonalInches >= MIN_TABLET_INCHES ? DeviceInforming.DeviceType.TABLET : DeviceInforming.DeviceType.PHONE; } /** * Returns a string that identifies a particular device OS build. This value may be present on * Android devices, with a value like "M4-rc20". The value is platform dependent and platform * specific. * * @return {@link String} Build ID string if available. null otherwise. */ public String getDeviceBuildId() { return Build.ID; } @Override public String getMobileCarrierName() { final Context context = getApplicationContext(); if (context == null) { return null; } TelephonyManager telephonyManager = ((TelephonyManager) context.getSystemService(Application.TELEPHONY_SERVICE)); return telephonyManager != null ? telephonyManager.getNetworkOperatorName() : null; } @Override public ConnectionStatus getNetworkConnectionStatus() { ConnectivityManager connectivityManager = ServiceProvider.getInstance().getAppContextService().getConnectivityManager(); if (connectivityManager == null) { return ConnectionStatus.UNKNOWN; } return NetworkUtils.isInternetAvailable(connectivityManager) ? ConnectionStatus.CONNECTED : ConnectionStatus.DISCONNECTED; } @Override public boolean registerOneTimeNetworkConnectionActiveListener( final NetworkConnectionActiveListener listener) { return false; } @Override public String getRunMode() { return "Application"; } @Override public String getDeviceUniqueId() { Context context = getApplicationContext(); if (context == null) { return null; } return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); } /** * Returns the default platform/device user agent value * * @return {@link String} containing the default user agent */ @Override public String getDefaultUserAgent() { final String unknown = "unknown"; final String operatingSystemNameWithVersion = this.getOperatingSystemName() + " " + this.getOperatingSystemVersion(); final String operatingSystem = isNullOrEmpty(operatingSystemNameWithVersion) ? unknown : operatingSystemNameWithVersion; final String locale = getLocaleString(); final String localeString = isNullOrEmpty(locale) ? unknown : locale; final String deviceName = isNullOrEmpty(this.getDeviceName()) ? unknown : this.getDeviceName(); final String deviceBuildId = isNullOrEmpty(this.getDeviceBuildId()) ? unknown : this.getDeviceBuildId(); return String.format( "Mozilla/5.0 (Linux; U; %s; %s; %s Build/%s)", operatingSystem, localeString, deviceName, deviceBuildId); } @Override public File getApplicationCacheDir() { final Context context = getApplicationContext(); if (context == null) { return null; } return context.getCacheDir(); } @Override public InputStream getAsset(final String fileName) { final Context context = getApplicationContext(); if (isNullOrEmpty(fileName) || context == null) { return null; } InputStream inputStream = null; Resources resources = context.getResources(); if (resources == null) { Log.debug( ServiceConstants.LOG_TAG, LOG_TAG, String.format( "%s (Resources), unable to read (%s) from the the assets folder.", UNEXPECTED_NULL_VALUE, fileName)); return null; } AssetManager assetManager = resources.getAssets(); if (assetManager == null) { Log.debug( ServiceConstants.LOG_TAG, LOG_TAG, String.format( "%s (AssetManager), unable to read (%s) from the the assets folder.", UNEXPECTED_NULL_VALUE, fileName)); return null; } try { inputStream = assetManager.open(fileName); } catch (IOException e) { Log.debug( ServiceConstants.LOG_TAG, LOG_TAG, String.format( "Unable to read (%s) from the the assets folder. (%s)", fileName, e)); } return inputStream; } @Override public String getPropertyFromManifest(final String propertyKey) { final Context context = getApplicationContext(); if (isNullOrEmpty(propertyKey) || context == null) { return null; } String propertyValue = null; PackageManager packageManager = context.getPackageManager(); if (packageManager == null) { Log.debug( ServiceConstants.LOG_TAG, LOG_TAG, String.format( "%s (Package Manager), unable to read property for key (%s).", UNEXPECTED_NULL_VALUE, propertyKey)); return null; } try { ApplicationInfo ai = packageManager.getApplicationInfo( context.getPackageName(), PackageManager.GET_META_DATA); if (ai == null) { Log.debug( ServiceConstants.LOG_TAG, LOG_TAG, String.format( "%s (Application info), unable to read property for key (%s).", UNEXPECTED_NULL_VALUE, propertyKey)); return null; } Bundle bundle = ai.metaData; if (bundle == null) { Log.debug( ServiceConstants.LOG_TAG, LOG_TAG, String.format( "%s (ApplicationInfo's metaData), unable to read property for key" + " (%s).", UNEXPECTED_NULL_VALUE, propertyKey)); return null; } propertyValue = bundle.getString(propertyKey); } catch (Exception e) { // In rare cases, package manager throws run time exception. Log.debug( ServiceConstants.LOG_TAG, LOG_TAG, String.format( "Unable to read property for key (%s). Exception - (%s)", propertyKey, e)); } return propertyValue; } @Override public String getApplicationName() { final Context context = getApplicationContext(); if (context == null) { return null; } String appName = null; try { PackageManager packageManager = context.getPackageManager(); if (packageManager == null) { return null; } ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0); if (applicationInfo != null) { appName = (String) packageManager.getApplicationLabel(applicationInfo); } } catch (Exception e) { // In rare cases, package manager throws run time exception. Log.debug( ServiceConstants.LOG_TAG, LOG_TAG, String.format("PackageManager couldn't find application name (%s)", e)); } return appName; } @Override public String getApplicationPackageName() { final Context context = getApplicationContext(); if (context == null) { return null; } return context.getPackageName(); } @Override public String getApplicationVersion() { PackageInfo packageInfo = getPackageInfo(); return packageInfo != null ? packageInfo.versionName : null; } @Override public String getApplicationVersionCode() { PackageInfo packageInfo = getPackageInfo(); if (packageInfo == null) { return null; } Locale locale = Locale.US; final int buildVersion = Build.VERSION.SDK_INT; int versionCode = 0; if (buildVersion >= Build.VERSION_CODES.P) { // 28 try { Method method = packageInfo.getClass().getDeclaredMethod("getLongVersionCode"); long longVersion = (Long) method.invoke(packageInfo); // getLongVersionCode contains versionCode in the lower 32bits and versionCodeMajor // in the higher 32 bits. Casting to int will give us the lower 32 bits. versionCode = (int) longVersion; } catch (Exception e) { Log.debug( ServiceConstants.LOG_TAG, LOG_TAG, String.format("Failed to get app version code, (%s)", e)); } } else { versionCode = packageInfo.versionCode; } return versionCode > 0 ? String.format(locale, "%d", versionCode) : null; } @Override public File getApplicationBaseDir() { final Context context = getApplicationContext(); if (context == null) { return null; } ApplicationInfo applicationInfo = context.getApplicationInfo(); if (applicationInfo == null) { return null; } return new File(context.getApplicationInfo().dataDir); } /** * Returns active locale's value in string format. The default value is en-US * * @return Locale as {@code String} */ public String getLocaleString() { Locale localeValue = this.getActiveLocale(); if (localeValue == null) { localeValue = Locale.US; } String result = localeValue.getLanguage(); final String countryCode = localeValue.getCountry(); if (!countryCode.isEmpty()) { result += "-" + countryCode; } return result; } /** * Returns the preferred locale value from the Resources object. * * @return A {@link Locale} value, if available, null otherwise */ private Locale getLocaleFromResources(final Resources resources) { if (resources == null) { return null; } final Configuration configuration = resources.getConfiguration(); if (configuration == null) { return null; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { return configuration.locale; } else { return configuration.getLocales().get(0); } } /** * Checks if a {@code String} is null, empty or it only contains whitespaces. * * @param str the {@link String} that we want to check * @return {@code boolean} with the evaluation result */ private boolean isNullOrEmpty(final String str) { return str == null || str.trim().isEmpty(); } private Context getApplicationContext() { return ServiceProvider.getInstance().getAppContextService().getApplicationContext(); } private Activity getCurrentActivity() { return ServiceProvider.getInstance().getAppContextService().getCurrentActivity(); } private PackageInfo getPackageInfo() { final Context context = getApplicationContext(); if (context == null) { return null; } try { PackageManager packageManager = context.getPackageManager(); if (packageManager == null) { return null; } return packageManager.getPackageInfo(context.getPackageName(), 0); } catch (Exception e) { // In rare cases, package manager throws run time exception. Log.debug( ServiceConstants.LOG_TAG, LOG_TAG, String.format( "PackageManager couldn't find application version (%s)", e.getLocalizedMessage())); return null; } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/HttpMethod.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; // Enum for HTTP request methods public enum HttpMethod { GET, POST; HttpMethod() {} }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/PersistentHitQueue.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import androidx.annotation.VisibleForTesting; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * Provides functionality for asynchronous processing of hits in a synchronous manner while * providing the ability to retry hits. */ public class PersistentHitQueue extends HitQueuing { private final DataQueue queue; private final HitProcessing processor; private final AtomicBoolean suspended = new AtomicBoolean(true); private final ScheduledExecutorService scheduledExecutorService; private final AtomicBoolean isTaskScheduled = new AtomicBoolean(false); /** * Constructor to create {@link HitQueuing} with underlying {@link DataQueue} * * @param queue object of <code>DataQueue</code> for persisting hits * @param processor object of {@link HitProcessing} for processing hits * @throws IllegalArgumentException when queue or processor is null */ public PersistentHitQueue(final DataQueue queue, final HitProcessing processor) throws IllegalArgumentException { this(queue, processor, Executors.newSingleThreadScheduledExecutor()); } @VisibleForTesting PersistentHitQueue( final DataQueue queue, final HitProcessing processor, final ScheduledExecutorService executorService) { if (queue == null || processor == null) { throw new IllegalArgumentException( "Null value is not allowed in PersistentHitQueue Constructor."); } this.queue = queue; this.processor = processor; this.scheduledExecutorService = executorService; } @Override public boolean queue(final DataEntity entity) { final boolean result = queue.add(entity); processNextHit(); return result; } @Override public void beginProcessing() { suspended.set(false); processNextHit(); } @Override public void suspend() { suspended.set(true); } @Override public void clear() { queue.clear(); } @Override public int count() { return queue.count(); } @Override public void close() { suspend(); queue.close(); scheduledExecutorService.shutdown(); } /** * A Recursive function for processing persisted hits. I will continue processing all the Hits * until none are left in the DataQueue. */ private void processNextHit() { if (suspended.get()) { return; } // If taskScheduled is false, then set to true and return true. // If taskScheduled is true, then compareAndSet returns false if (!isTaskScheduled.compareAndSet(false, true)) { return; } scheduledExecutorService.execute( () -> { DataEntity entity = queue.peek(); if (entity == null) { isTaskScheduled.set(false); return; } processor.processHit( entity, result -> { if (result) { queue.remove(); isTaskScheduled.set(false); processNextHit(); } else { long delay = processor.retryInterval(entity); scheduledExecutorService.schedule( () -> { isTaskScheduled.set(false); processNextHit(); }, delay, TimeUnit.SECONDS); } }); }); } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/DataQueueService.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import android.content.Context; import androidx.annotation.NonNull; import com.adobe.marketing.mobile.internal.util.FileUtils; import com.adobe.marketing.mobile.util.StringUtils; import java.io.File; import java.util.HashMap; import java.util.Map; /** * Class to create instances of {@link DataQueue}. It caches the instances of DataQueue to ensure * one instance is created per database. */ class DataQueueService implements DataQueuing { private static final String LOG_TAG = "DataQueueService"; private final Map<String, DataQueue> dataQueueCache; DataQueueService() { dataQueueCache = new HashMap<>(); } @SuppressWarnings("checkstyle:NestedIfDepth") @Override public DataQueue getDataQueue(final String databaseName) { if (StringUtils.isNullOrEmpty(databaseName)) { Log.warning( ServiceConstants.LOG_TAG, LOG_TAG, "Failed to create DataQueue, database name is null"); return null; } DataQueue dataQueue = dataQueueCache.get(databaseName); if (dataQueue == null) { synchronized (this) { dataQueue = dataQueueCache.get(databaseName); if (dataQueue == null) { final File databaseDirDataQueue = openOrMigrateExistingDataQueue(databaseName); if (databaseDirDataQueue == null) { Log.warning( ServiceConstants.LOG_TAG, LOG_TAG, "Failed to create DataQueue for database (%s).", databaseName); return null; } dataQueue = new SQLiteDataQueue(databaseName, databaseDirDataQueue.getPath()); dataQueueCache.put(databaseName, dataQueue); } } } return dataQueue; } /** * Returns the database if it exists in the path returned by {@link * Context#getDatabasePath(String)} Else copies the existing database from {@link * Context#getCacheDir()} to {@code Context#getDatabasePath(String)} Database is migrated from * cache directory because of Android 12 app hibernation changes which can clear app's cache * folder when user doesn't interact with app for few months. * * @param databaseName name of the database to be migrated or opened * @return {@code File} representing the database in {@code Context#getDatabasePath(String)} */ private File openOrMigrateExistingDataQueue(@NonNull final String databaseName) { Context appContext = ServiceProvider.getInstance().getAppContextService().getApplicationContext(); if (appContext == null) { Log.debug( ServiceConstants.LOG_TAG, LOG_TAG, "Failed to create DataQueue for database (%s), the ApplicationContext is null", databaseName); return null; } final String cleanedDatabaseName = FileUtils.removeRelativePath(databaseName); final File databaseDirDataQueue = appContext.getDatabasePath(cleanedDatabaseName); // Return the db which exists in database directory. if (databaseDirDataQueue.exists()) { return databaseDirDataQueue; } // If db exists in cache directory, migrate it to new path. try { final File cacheDir = ServiceProvider.getInstance().getDeviceInfoService().getApplicationCacheDir(); if (cacheDir != null) { final File cacheDirDataQueue = new File(cacheDir, cleanedDatabaseName); if (cacheDirDataQueue.exists()) { FileUtils.moveFile(cacheDirDataQueue, databaseDirDataQueue); Log.debug( ServiceConstants.LOG_TAG, LOG_TAG, "Successfully moved DataQueue for database (%s) from cache directory" + " to database directory", databaseName); } } } catch (Exception ex) { Log.debug( ServiceConstants.LOG_TAG, LOG_TAG, "Failed to move DataQueue for database (%s) from cache directory to database" + " directory", databaseName); } return databaseDirDataQueue; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/DataStoring.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; /** Represents the service for persisting key-value pairs */ public interface DataStoring { /** * Get a NamedCollection containing persistent key-value pairs * * @param collectionName name of the Collection * @return NamedCollection object containing persisted data for collectionName. */ NamedCollection getNamedCollection(String collectionName); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/AndroidLoggingService.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import android.util.Log; /** The Android implementation for for {@link Logging}. */ class AndroidLoggingService implements Logging { private static final String TAG = "AdobeExperienceSDK"; @Override public void trace(final String tag, final String message) { Log.v(TAG, tag + " - " + message); } @Override public void debug(final String tag, final String message) { Log.d(TAG, tag + " - " + message); } @Override public void warning(final String tag, final String message) { Log.w(TAG, tag + " - " + message); } @Override public void error(final String tag, final String message) { Log.e(TAG, tag + " - " + message); } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/NamedCollection.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import java.util.Map; public interface NamedCollection { /** * Set or update an int value * * @param key String key name * @param value int value */ void setInt(String key, int value); /** * Get int value for key * * @param key String key name * @param defaultValue int the default value to return if key does not exist * @return persisted value if it exists, defaultValue otherwise */ int getInt(String key, int defaultValue); /** * Set or update a String value for key * * @param key String key name * @param value String the default value to return if key does not exist */ void setString(String key, String value); /** * Get String value for key * * @param key String key name * @param defaultValue String the default value to return if key does not exist * @return persisted value if it exists, defaultValue otherwise */ String getString(String key, String defaultValue); /** * Set or update a double value for key * * @param key String key name * @param value double the default value to return if key does not exist */ void setDouble(String key, double value); /** * Get double value for key * * @param key String key name * @param defaultValue double the default value to return if key does not exist * @return persisted value if it exists, defaultValue otherwise */ double getDouble(String key, double defaultValue); /** * Set or update a long value for key * * @param key String key name * @param value long the default value to return if key does not exist */ void setLong(String key, long value); /** * Get long value for key * * @param key String key name * @param defaultValue long the default value to return if key does not exist * @return persisted value if it exists, defaultValue otherwise */ long getLong(String key, long defaultValue); /** * Set or update a float value for key * * @param key String key name * @param value float the default value to return if key does not exist */ void setFloat(String key, float value); /** * Get float value for key * * @param key String key name * @param defaultValue float the default value to return if key does not exist * @return persisted value if it exists, defaultValue otherwise */ float getFloat(String key, float defaultValue); /** * Set or update a boolean value for key * * @param key String key name * @param value boolean the default value to return if key does not exist */ void setBoolean(String key, boolean value); /** * Get boolean value for key * * @param key String key name * @param defaultValue boolean the default value to return if key does not exist * @return persisted value if it exists, defaultValue otherwise */ boolean getBoolean(String key, boolean defaultValue); /** * Set or update a Map value for key * * @param key String key name * @param value Map the default value to return if key does not exist */ void setMap(String key, Map<String, String> value); /** * Get Map value for key * * @param key String key name * @return persisted value if it exists, null otherwise */ Map<String, String> getMap(String key); /** * Check if the named collection contains key * * @param key String key name * @return true if key exists, false otherwise */ boolean contains(String key); /** * Remove persisted value for key * * @param key String key name */ void remove(String key); /** Remove all key-value pairs from this named collection */ void removeAll(); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ServiceProvider.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import androidx.annotation.VisibleForTesting; import com.adobe.marketing.mobile.services.caching.CacheService; import com.adobe.marketing.mobile.services.internal.caching.FileCacheService; import com.adobe.marketing.mobile.services.internal.context.App; import com.adobe.marketing.mobile.services.ui.AEPUIService; import com.adobe.marketing.mobile.services.ui.UIService; import com.adobe.marketing.mobile.services.uri.UriOpening; import com.adobe.marketing.mobile.services.uri.UriService; /** Maintains the current set of provided services and any potential service overrides */ public class ServiceProvider { private static class ServiceProviderSingleton { private static final ServiceProvider INSTANCE = new ServiceProvider(); } /** * Singleton method to get the instance of ServiceProvider * * @return the {@link ServiceProvider} singleton */ public static ServiceProvider getInstance() { return ServiceProviderSingleton.INSTANCE; } private DeviceInfoService defaultDeviceInfoService; private DeviceInforming overrideDeviceInfoService; private NetworkService defaultNetworkService; private Networking overrideNetworkService; private DataQueuing dataQueueService; private DataStoring defaultDataStoreService; private UIService defaultUIService; private Logging defaultLoggingService; private Logging overrideLoggingService; private CacheService defaultCacheService; private AppContextService overrideAppContextService; private UriOpening defaultUriService; private ServiceProvider() { defaultNetworkService = new NetworkService(); defaultDeviceInfoService = new DeviceInfoService(); dataQueueService = new DataQueueService(); defaultDataStoreService = new LocalDataStoreService(); defaultUIService = new AEPUIService(); defaultLoggingService = new AndroidLoggingService(); defaultCacheService = new FileCacheService(); defaultUriService = new UriService(); } /** * Returns the current {@link Logging} * * @return the current {@link Logging} */ public Logging getLoggingService() { return overrideLoggingService != null ? overrideLoggingService : defaultLoggingService; } /** * Overrides the {@link Logging} service. * * @param loggingService the new {@link Logging} service which will override the default {@link * Logging} service */ public void setLoggingService(final Logging loggingService) { overrideLoggingService = loggingService; } /** * Gets the {@link DataStoring} service * * @return the {@link DataStoring} service */ public DataStoring getDataStoreService() { return defaultDataStoreService; } /** * Gets the {@link DeviceInforming} service * * @return the {@link DeviceInforming} service */ public DeviceInforming getDeviceInfoService() { return overrideDeviceInfoService != null ? overrideDeviceInfoService : defaultDeviceInfoService; } /** * For testing purpose. Overrides the default {@link DeviceInforming} service * * @param deviceInfoService new {@link DeviceInforming} service */ @VisibleForTesting void setDeviceInfoService(final DeviceInforming deviceInfoService) { overrideDeviceInfoService = deviceInfoService; } /** * Gets the current {@link Networking} service. * * @return the override {@link Networking} service if it has been provided, otherwise the * default {@link Networking} service is returned */ public Networking getNetworkService() { return overrideNetworkService != null ? overrideNetworkService : defaultNetworkService; } /** * Overrides the {@link Networking} service. * * @param networkService the new {@link Networking} service which will override the default * {@link Networking} service */ public void setNetworkService(final Networking networkService) { overrideNetworkService = networkService; } /** * Gets the {@link DataQueuing} service * * @return the {@link DataQueuing} service */ public DataQueuing getDataQueueService() { return dataQueueService; } /** * Gets the {@link UIService} service * * @return the {@link UIService} service */ public UIService getUIService() { return defaultUIService; } /** * Gets the {@link CacheService} service * * @return the {@link UIService} service */ public CacheService getCacheService() { return defaultCacheService; } /** * Gets the {@link AppContextService} service * * @return the {@link AppContextService} service */ public AppContextService getAppContextService() { return overrideAppContextService != null ? overrideAppContextService : App.INSTANCE; } /** * Gets the {@link UriOpening} service * * @return the {@link UriOpening} service */ public UriOpening getUriService() { return defaultUriService; } /** * For testing purpose. Overrides the default {@link AppContextService} service * * @param appContextService new {@link AppContextService} service */ @VisibleForTesting void setAppContextService(final AppContextService appContextService) { overrideAppContextService = appContextService; } /** * Reset the {@code ServiceProvider} to its default state. Any previously set services are reset * to their default state. */ @VisibleForTesting void resetServices() { defaultDeviceInfoService = new DeviceInfoService(); defaultNetworkService = new NetworkService(); dataQueueService = new DataQueueService(); defaultDataStoreService = new LocalDataStoreService(); defaultLoggingService = new AndroidLoggingService(); defaultUIService = new AEPUIService(); defaultCacheService = new FileCacheService(); defaultUriService = new UriService(); overrideDeviceInfoService = null; overrideNetworkService = null; overrideAppContextService = null; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/Log.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import androidx.annotation.NonNull; import com.adobe.marketing.mobile.LoggingMode; /** Logging class to handle log levels and platform-specific log output */ public class Log { private static LoggingMode loggingMode = LoggingMode.ERROR; public static final String UNEXPECTED_NULL_VALUE = "Unexpected Null Value"; public static final String UNEXPECTED_EMPTY_VALUE = "Unexpected Empty Value"; public static final String INVALID_FORMAT = "Invalid Format"; /** private constructor to prevent accidental instantiation */ private Log() {} /** * Sets the log level to operate at * * @param loggingMode LoggingMode to use for log output * @see LoggingMode */ public static void setLogLevel(final LoggingMode loggingMode) { Log.loggingMode = loggingMode; } /** * Gets the log level that the SDK is currently operating at * * @return LoggingMode describing the current level of logging. */ public static LoggingMode getLogLevel() { return Log.loggingMode; } /** * Used to print more verbose information. Info logging is expected to follow end-to-end every * method an event hits. Prints information to the console only when the SDK is in LoggingMode: * VERBOSE * * @param extension the extension name * @param source the source of the information to be logged * @param format the string format to be logged * @param params values to be inserted into the format * @see LoggingMode */ public static void trace( @NonNull final String extension, @NonNull final String source, @NonNull final String format, final Object... params) { Logging loggingService = ServiceProvider.getInstance().getLoggingService(); if (loggingService != null && loggingMode.id >= LoggingMode.VERBOSE.id) { try { loggingService.trace(extension + "/" + source, String.format(format, params)); } catch (Exception e) { loggingService.trace(source, format); } } } /** * Information provided to the debug method should contain high-level details about the data * being processed. Prints information to the console only when the SDK is in LoggingMode: * VERBOSE, DEBUG * * @param extension the extension name * @param source the source of the information to be logged * @param format the string format to be logged * @param params values to be inserted into the format * @see LoggingMode */ public static void debug( @NonNull final String extension, @NonNull final String source, @NonNull final String format, final Object... params) { Logging loggingService = ServiceProvider.getInstance().getLoggingService(); if (loggingService != null && loggingMode.id >= LoggingMode.DEBUG.id) { try { loggingService.debug(extension + "/" + source, String.format(format, params)); } catch (Exception e) { loggingService.debug(source, format); } } } /** * Information provided to the warning method indicates that a request has been made to the SDK, * but the SDK will be unable to perform the requested task. An example is catching an expected * or unexpected but recoverable exception. Prints information to the console only when the SDK * is in LoggingMode: VERBOSE, DEBUG, WARNING * * @param extension the extension name * @param source the source of the information to be logged * @param format the string format to be logged * @param params values to be inserted into the format * @see LoggingMode */ public static void warning( @NonNull final String extension, @NonNull final String source, @NonNull final String format, final Object... params) { Logging loggingService = ServiceProvider.getInstance().getLoggingService(); if (loggingService != null && loggingMode.ordinal() >= LoggingMode.WARNING.id) { try { loggingService.warning(extension + "/" + source, String.format(format, params)); } catch (Exception e) { loggingService.warning(source, format); } } } /** * Information provided to the error method indicates that there has been an unrecoverable * error. Prints information to the console regardless of current LoggingMode of the SDK. * * @param extension the extension name * @param source the source of the information to be logged * @param format the string format to be logged * @param params values to be inserted into the format * @see LoggingMode */ public static void error( @NonNull final String extension, @NonNull final String source, @NonNull final String format, final Object... params) { Logging loggingService = ServiceProvider.getInstance().getLoggingService(); if (loggingService != null && loggingMode.ordinal() >= LoggingMode.ERROR.id) { try { loggingService.error(extension + "/" + source, String.format(format, params)); } catch (Exception e) { loggingService.error(source, format); } } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/HttpConnection.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.UnknownServiceException; class HttpConnection implements HttpConnecting { private static final String TAG = HttpConnection.class.getSimpleName(); private final HttpURLConnection httpUrlConnection; /** * Constructor * * @param httpURLConnection {@link HttpURLConnection} instance, supports HTTP specific features */ HttpConnection(final HttpURLConnection httpURLConnection) { this.httpUrlConnection = httpURLConnection; } /** * Returns an input stream to read the application server response from this open connection, if * available. * * <p>This method invokes {@link HttpURLConnection#getInputStream()} and returns null if {@code * getInputSream()} throws an exception. * * @return {@link InputStream} connection response input stream */ @Override public InputStream getInputStream() { try { return httpUrlConnection.getInputStream(); } catch (final UnknownServiceException e) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format( "Could not get the input stream, protocol does not support input. (%s)", e)); } catch (final Exception | Error e) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format("Could not get the input stream. (%s)", e)); } return null; } /** * Returns an input stream from the connection to read the application server error response, if * available. * * @return {@link InputStream} connection response error stream */ @Override public InputStream getErrorStream() { try { return httpUrlConnection.getErrorStream(); } catch (final Exception | Error e) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format("Could not get the input stream. (%s)", e)); } return null; } /** * Returns the connection attempt response code for this connection request. * * <p>This method invokes {@link HttpURLConnection#getResponseCode()} and returns -1 if {@code * getResponseCode()} throws an exception or the response is not valid HTTP. * * @return {@code int} indicating connection status code */ @Override public int getResponseCode() { try { return httpUrlConnection.getResponseCode(); } catch (final Exception | Error e) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format("Could not get response code. (%s)", e)); } return -1; } /** * Returns the connection attempt response message for this connection request, if available. * * <p>This method invokes {@link HttpURLConnection#getResponseMessage()} and returns null if * {@code getResponseMessage()} throws an exception or the result is not valid HTTP. * * @return {@link String} containing connection response message */ @Override public String getResponseMessage() { try { return httpUrlConnection.getResponseMessage(); } catch (final Exception | Error e) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format("Could not get the response message. (%s)", e)); } return null; } /** * Returns the value of the header field specified by the {@code responsePropertyKey} that might * have been set when a connection was made to the resource pointed to by the URL. * * <p>This is protocol specific. For example, HTTP urls could have properties like * "last-modified", or "ETag" set. * * @param responsePropertyKey {@link String} containing response property key * @return {@code String} corresponding to the response property value for the key specified, or * null, if the key does not exist */ @Override public String getResponsePropertyValue(final String responsePropertyKey) { return httpUrlConnection.getHeaderField(responsePropertyKey); } /** * Closes this open connection. * * <p>Invokes {@link HttpURLConnection#disconnect()} method to release the resources for this * connection. */ @Override public void close() { final InputStream inputStream = this.getInputStream(); final InputStream errorStream = this.getErrorStream(); if (inputStream != null) { try { inputStream.close(); } catch (final Exception | Error e) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format("Could not close the input stream. (%s)", e)); } } if (errorStream != null) { try { errorStream.close(); } catch (final Exception | Error e) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format("Could not close the error stream. (%s)", e)); } } httpUrlConnection.disconnect(); } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/HitQueuing.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import com.adobe.marketing.mobile.MobilePrivacyStatus; // Provides the functionality for Queuing Hits. public abstract class HitQueuing { /** * Queues a {@link DataEntity} to be processed * * @param entity the entity to be processed * @return a boolean indication whether queuing the entity was successful or not */ public abstract boolean queue(DataEntity entity); /** Puts the Queue in non-suspended state and begin processing hits */ public abstract void beginProcessing(); /** Puts the Queue in suspended state and discontinue processing hits */ public abstract void suspend(); /** Removes all the persisted hits from the queue */ public abstract void clear(); /** Returns the number of items in the queue */ public abstract int count(); /** Close the current <code>HitQueuing</code> */ public abstract void close(); public void handlePrivacyChange(final MobilePrivacyStatus privacyStatus) { switch (privacyStatus) { case OPT_IN: beginProcessing(); break; case OPT_OUT: suspend(); clear(); break; default: suspend(); } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/LocalDataStoreService.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import android.content.Context; import android.content.SharedPreferences; /** Implementation of {@link DataStoring} service */ class LocalDataStoreService implements DataStoring { private static final String TAG = LocalDataStoreService.class.getSimpleName(); @Override public NamedCollection getNamedCollection(final String collectionName) { if (collectionName == null || collectionName.isEmpty()) { Log.error( ServiceConstants.LOG_TAG, TAG, String.format( "Failed to create an instance of NamedCollection with name - %s: the" + " collection name is null or empty.", collectionName)); return null; } Context appContext = ServiceProvider.getInstance().getAppContextService().getApplicationContext(); if (appContext == null) { Log.error( ServiceConstants.LOG_TAG, TAG, String.format( "Failed to create an instance of NamedCollection with name - %s: the" + " ApplicationContext is null", collectionName)); return null; } SharedPreferences sharedPreferences = appContext.getSharedPreferences(collectionName, 0); SharedPreferences.Editor sharedPreferencesEditor = null; if (sharedPreferences != null) { sharedPreferencesEditor = sharedPreferences.edit(); } if (sharedPreferences == null || sharedPreferencesEditor == null) { Log.error( ServiceConstants.LOG_TAG, TAG, "Failed to create a valid SharedPreferences object or SharedPreferences.Editor" + " object"); return null; } return new SharedPreferencesNamedCollection(sharedPreferences, sharedPreferencesEditor); } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/NetworkCallback.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; // the callback for handling network response public interface NetworkCallback { /** * Callback method invoked with the {@code HttpConnection} instance once the connection is * established. * * @param connection {@link HttpConnecting} instance */ void call(final HttpConnecting connection); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/HttpConnectionHandler.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.SocketTimeoutException; import java.net.URL; import java.util.Map; import java.util.Set; import javax.net.ssl.HttpsURLConnection; class HttpConnectionHandler { private static final String TAG = HttpConnectionHandler.class.getSimpleName(); protected final HttpsURLConnection httpsUrlConnection; protected Command command = Command.GET; // Default /** Commands supported by this {@code HttpConnectionHandler}. */ protected enum Command { GET(false), POST(true); private final boolean doOutputSetting; /** * Constructor which initializes the {@link #doOutputSetting}. * * <p>Set the {@code doOutputSetting} flag to true if you intend to write data to the URL * connection, otherwise set it to false. * * @param doOutputSetting {@code boolean} indicating whether this command writes to the * connection output stream */ Command(final boolean doOutputSetting) { this.doOutputSetting = doOutputSetting; } /** * Returns the setting specifying whether this command will need to write data to the URL * connection. * * @return {@code boolean} indicating whether this command writes to the connection output * stream */ public boolean isDoOutput() { return doOutputSetting; } } /** * Constructor to create a connection to the resource indicated by the specified {@code url}. * * <p>Initializes {@link #httpsUrlConnection} with a {@link java.net.URLConnection} instance * representing the connection, returned by a call to {@link URL#openConnection()}. * * @param url {@link URL} to connect to * @throws IOException if an exception occurs */ HttpConnectionHandler(final URL url) throws IOException { httpsUrlConnection = (HttpsURLConnection) url.openConnection(); } /** * Sets the command to be used for this connection attempt. * * <p>The command should be set before {@link #connect(byte[])} method is called. * * @param command {@link HttpMethod} representing the command to be used * @return {@code boolean} indicating whether the command was successfully set * @see HttpsURLConnection#setRequestMethod(String) */ boolean setCommand(final HttpMethod command) { if (command == null) { return false; } try { Command requestedCommand = Command.valueOf(command.name()); // Set the HTTP method for this request. Supported methods - GET/POST. httpsUrlConnection.setRequestMethod(requestedCommand.name()); // Set doOutput flag for this URLConnection. A true value indicates intention to write // data to URL connection, read otherwise. httpsUrlConnection.setDoOutput(requestedCommand.isDoOutput()); // AMSDK-8629, avoid a crash inside Android code httpsUrlConnection.setUseCaches(false); this.command = requestedCommand; return true; } catch (final ProtocolException e) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format("%s is not a valid HTTP command (%s)!", command, e)); } catch (final IllegalStateException e) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format("Cannot set command after connect (%s)!", e)); } catch (final IllegalArgumentException e) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format("%s command is not supported (%s)!", command, e)); } catch (final Exception | Error e) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format("Failed to set http command (%s)!", e)); } return false; } /** * Sets the header fields specified by the {@code requestProperty} for the connection. * * <p>This method should be called before {@link #connect(byte[])} is called. * * @param requestProperty {@code Map<String, String>} containing the header fields and their * values * @see HttpsURLConnection#setRequestProperty(String, String) */ void setRequestProperty(final Map<String, String> requestProperty) { if (requestProperty == null || requestProperty.isEmpty()) { return; } Set<Map.Entry<String, String>> entries = requestProperty.entrySet(); for (Map.Entry<String, String> entry : entries) { try { httpsUrlConnection.setRequestProperty(entry.getKey(), entry.getValue()); } catch (final IllegalStateException e) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format("Cannot set header field after connect (%s)!", e)); return; } catch (final Exception | Error e) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format("Failed to set request property (%s)!", e)); } } } /** * Sets the connect timeout value for this connection. * * @param connectTimeout {@code int} indicating connect timeout value in milliseconds * @see HttpURLConnection#setConnectTimeout(int) */ void setConnectTimeout(final int connectTimeout) { try { httpsUrlConnection.setConnectTimeout(connectTimeout); } catch (final IllegalArgumentException e) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format(connectTimeout + " is not valid timeout value (%s)", e)); } catch (final Exception | Error e) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format("Failed to set connection timeout (%s)!", e)); } } /** * Sets the timeout that will be used to wait for a read to finish after a successful connect. * * @param readTimeout {@code int} indicating read timeout value in milliseconds * @see HttpURLConnection#setReadTimeout(int) */ void setReadTimeout(final int readTimeout) { try { httpsUrlConnection.setReadTimeout(readTimeout); } catch (final IllegalArgumentException e) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format(readTimeout + " is not valid timeout value (%s)", e)); } catch (final Exception | Error e) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format("Failed to set read timeout (%s)!", e)); } } /** * Performs the actual connection to the resource referenced by this {@code httpUrlConnection}. * * <p>If the {@code command} set for this connection is {@link Command#POST}, then the {@code * payload} will be sent to the server, otherwise ignored. * * @param payload {@code byte} array representing the payload to be sent to the server * @return {@link HttpConnecting} instance, representing a connection attempt * @see HttpURLConnection#connect() */ HttpConnecting connect(final byte[] payload) { Log.debug( ServiceConstants.LOG_TAG, TAG, String.format( "Connecting to URL %s (%s)", (httpsUrlConnection.getURL() == null ? "" : httpsUrlConnection.getURL().toString()), command.toString())); // If the command to be used is POST, set the length before connection if (command == Command.POST && payload != null) { httpsUrlConnection.setFixedLengthStreamingMode(payload.length); } // Try to connect try { httpsUrlConnection.connect(); // if the command is POST, send the data to the URL. if (command == Command.POST && payload != null) { // Consume the payload OutputStream os = new BufferedOutputStream(httpsUrlConnection.getOutputStream()); os.write(payload); os.flush(); os.close(); } } catch (final SocketTimeoutException e) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format("Connection failure, socket timeout (%s)", e)); } catch (final IOException e) { Log.warning( ServiceConstants.LOG_TAG, TAG, String.format( "Connection failure (%s)", (e.getLocalizedMessage() != null ? e.getLocalizedMessage() : e.getMessage()))); } catch (final Exception | Error e) { Log.warning(ServiceConstants.LOG_TAG, TAG, String.format("Connection failure (%s)", e)); } // Create a connection object here // Even if there might be an IOException, let the user query for response code etc. return new HttpConnection(httpsUrlConnection); } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/Networking.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; public interface Networking { /** * Initiates an asynchronous network connection * * @param request {@link NetworkRequest} used for connection * @param callback {@link NetworkCallback} that will receive the {@link HttpConnecting} instance * after the connection has been made; if the current network is unavailable, callback will * be invoked immediately with a null connection. */ void connectAsync(final NetworkRequest request, final NetworkCallback callback); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/DataEntity.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import java.util.Date; import java.util.UUID; /** * Data Model class for entities stored in {@link com.adobe.marketing.mobile.services.DataQueuing} */ public final class DataEntity { private final String uniqueIdentifier; private final Date timestamp; private final String data; /** * Generates a new {@link DataEntity} * * @param data a {@link String} to be stored in database entity. */ public DataEntity(final String data) { this(UUID.randomUUID().toString(), new Date(), data); } /** * Generates a new {@link DataEntity} * * @param data a {@link String} to be stored in database entity. * @param uniqueIdentifier unique {@link String} value. * @param timestamp instance of {@link Date} for retrieving {@link Date#getTime()}. */ public DataEntity(final String uniqueIdentifier, final Date timestamp, final String data) { this.uniqueIdentifier = uniqueIdentifier; this.timestamp = timestamp; this.data = data; } public String getUniqueIdentifier() { return uniqueIdentifier; } public Date getTimestamp() { return timestamp; } public String getData() { return data; } @Override public String toString() { return ("DataEntity{" + "uniqueIdentifier='" + uniqueIdentifier + '\'' + ", timeStamp=" + timestamp + ", data=" + data + '}'); } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/SharedPreferencesNamedCollection.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import android.annotation.SuppressLint; import android.content.SharedPreferences; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; /** Implementation of {@link NamedCollection} */ @SuppressLint("CommitPrefEdits") class SharedPreferencesNamedCollection implements NamedCollection { private static final String TAG = SharedPreferencesNamedCollection.class.getSimpleName(); private final SharedPreferences sharedPreferences; private final SharedPreferences.Editor sharedPreferencesEditor; SharedPreferencesNamedCollection( final SharedPreferences sharedPreferences, final SharedPreferences.Editor sharedPreferencesEditor) { this.sharedPreferences = sharedPreferences; this.sharedPreferencesEditor = sharedPreferencesEditor; } @Override public void setInt(final String key, final int value) { if (sharedPreferencesEditor == null) { return; } sharedPreferencesEditor.putInt(key, value); sharedPreferenceCommit(); } @Override public int getInt(final String key, final int defaultValue) { return sharedPreferences.getInt(key, defaultValue); } @Override public void setString(final String key, final String value) { sharedPreferencesEditor.putString(key, value); sharedPreferenceCommit(); } @Override public String getString(final String key, final String defaultValue) { return sharedPreferences.getString(key, defaultValue); } @Override public void setDouble(final String key, final double value) { sharedPreferencesEditor.putLong(key, Double.doubleToRawLongBits(value)); sharedPreferenceCommit(); } @Override public double getDouble(final String key, final double defaultValue) { long doubleRawLongBits = sharedPreferences.getLong(key, Double.doubleToRawLongBits(defaultValue)); return Double.longBitsToDouble(doubleRawLongBits); } @Override public void setLong(final String key, final long value) { sharedPreferencesEditor.putLong(key, value); sharedPreferenceCommit(); } @Override public long getLong(final String key, final long defaultValue) { return sharedPreferences.getLong(key, defaultValue); } @Override public void setFloat(final String key, final float value) { sharedPreferencesEditor.putFloat(key, value); sharedPreferenceCommit(); } @Override public float getFloat(final String key, final float defaultValue) { return sharedPreferences.getFloat(key, defaultValue); } @Override public void setBoolean(final String key, final boolean value) { sharedPreferencesEditor.putBoolean(key, value); sharedPreferenceCommit(); } @Override public boolean getBoolean(final String key, final boolean defaultValue) { return sharedPreferences.getBoolean(key, defaultValue); } @Override public void setMap(final String key, final Map<String, String> value) { try { JSONObject jsonFromMap = new JSONObject(value); sharedPreferencesEditor.putString(key, jsonFromMap.toString()); sharedPreferenceCommit(); } catch (NullPointerException e) { Log.error(ServiceConstants.LOG_TAG, TAG, "Map contains null key."); } } @Override public Map<String, String> getMap(final String key) { String mapJsonString = sharedPreferences.getString(key, null); Map<String, String> map = new HashMap<>(); if (mapJsonString == null) { return null; } try { JSONObject jsonObject = new JSONObject(mapJsonString); Iterator<String> keyItr = jsonObject.keys(); while (keyItr.hasNext()) { String keyName = keyItr.next(); try { map.put(keyName, jsonObject.getString(keyName)); } catch (JSONException jsonException) { Log.error( ServiceConstants.LOG_TAG, TAG, String.format( "Unable to convert jsonObject key %s into map, %s", keyName, jsonException.getLocalizedMessage())); } } } catch (Exception e) { Log.error( ServiceConstants.LOG_TAG, TAG, String.format( "Failed to convert [%s] to String Map, %s", mapJsonString, e.getLocalizedMessage())); map = null; } return map; } @Override public boolean contains(final String key) { return sharedPreferences.contains(key); } @Override public void remove(final String key) { sharedPreferencesEditor.remove(key); sharedPreferenceCommit(); } @Override public void removeAll() { sharedPreferencesEditor.clear(); sharedPreferenceCommit(); } private void sharedPreferenceCommit() { if (!sharedPreferencesEditor.commit()) { Log.error( ServiceConstants.LOG_TAG, TAG, "Android SharedPreference unable to commit the persisted data"); } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/Logging.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; public interface Logging { void trace(String tag, String message); void debug(String tag, String message); void warning(String tag, String message); void error(String tag, String message); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ServiceConstants.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services internal object ServiceConstants { const val LOG_TAG = "Services" }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/AppState.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; /** Enum representing application states. */ public enum AppState { FOREGROUND, BACKGROUND, UNKNOWN, }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/SQLiteDataQueue.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services; import android.content.ContentValues; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteStatement; import com.adobe.marketing.mobile.internal.util.FileUtils; import com.adobe.marketing.mobile.internal.util.SQLiteDatabaseHelper; import java.io.File; import java.util.ArrayList; import java.util.Date; import java.util.List; /** SQLite backed implementation of {@link DataQueue}. */ final class SQLiteDataQueue implements DataQueue { private static final String TABLE_NAME = "TB_AEP_DATA_ENTITY"; private static final String TB_KEY_UNIQUE_IDENTIFIER = "uniqueIdentifier"; private static final String TB_KEY_TIMESTAMP = "timestamp"; private static final String TB_KEY_DATA = "data"; private final String LOG_PREFIX; private final String databasePath; private boolean isClose = false; private final Object dbMutex = new Object(); SQLiteDataQueue(final String databaseName, final String databasePath) { this.LOG_PREFIX = "SQLiteDataQueue-" + databaseName; this.databasePath = databasePath; createTableIfNotExists(); } @Override public boolean add(final DataEntity dataEntity) { if (dataEntity == null) { Log.debug( ServiceConstants.LOG_TAG, LOG_PREFIX, "add - Returning false, DataEntity is null."); return false; } synchronized (dbMutex) { if (isClose) { Log.debug( ServiceConstants.LOG_TAG, LOG_PREFIX, "add - Returning false, DataQueue is closed."); return false; } boolean result = tryAddEntity(dataEntity); if (!result) { resetDatabase(); // Retry adding the data after resetting the database. result = tryAddEntity(dataEntity); } return result; } } @Override public List<DataEntity> peek(final int n) { if (n <= 0) { Log.warning(ServiceConstants.LOG_TAG, LOG_PREFIX, "peek n - Returning null, n <= 0."); return null; } final List<ContentValues> rows = new ArrayList<>(); synchronized (dbMutex) { if (isClose) { Log.warning( ServiceConstants.LOG_TAG, LOG_PREFIX, "peek n - Returning null, DataQueue is closed."); return null; } SQLiteDatabaseHelper.process( databasePath, SQLiteDatabaseHelper.DatabaseOpenMode.READ_ONLY, database -> { if (database == null) { return false; } try (Cursor cursor = database.query( TABLE_NAME, new String[] { TB_KEY_TIMESTAMP, TB_KEY_UNIQUE_IDENTIFIER, TB_KEY_DATA }, null, null, null, null, "id ASC", String.valueOf(n))) { if (cursor.moveToFirst()) { do { ContentValues contentValues = new ContentValues(); DatabaseUtils.cursorRowToContentValues(cursor, contentValues); rows.add(contentValues); } while (cursor.moveToNext()); } Log.trace( ServiceConstants.LOG_TAG, LOG_PREFIX, String.format( "query - Successfully read %d rows from table.", rows.size())); return true; } catch (final SQLiteException e) { Log.warning( ServiceConstants.LOG_TAG, LOG_PREFIX, String.format( "query - Error in querying database table. Error:" + " (%s)", e.getLocalizedMessage())); return false; } }); } final List<DataEntity> dataEntitiesList = new ArrayList<>(rows.size()); for (ContentValues row : rows) { dataEntitiesList.add( new DataEntity( row.getAsString(TB_KEY_UNIQUE_IDENTIFIER), new Date(row.getAsLong(TB_KEY_TIMESTAMP)), row.getAsString(TB_KEY_DATA))); } Log.trace( ServiceConstants.LOG_TAG, LOG_PREFIX, String.format( "peek n - Successfully returned %d DataEntities", dataEntitiesList.size())); return dataEntitiesList; } @Override public DataEntity peek() { final List<DataEntity> dataEntities = peek(1); if (dataEntities == null) { Log.debug( ServiceConstants.LOG_TAG, LOG_PREFIX, "peek - Unable to fetch DataEntity, returning null"); return null; } if (dataEntities.isEmpty()) { Log.debug( ServiceConstants.LOG_TAG, LOG_PREFIX, "peek - 0 DataEntities fetch, returning null"); return null; } Log.trace( ServiceConstants.LOG_TAG, LOG_PREFIX, String.format( "peek - Successfully returned DataEntity (%s)", dataEntities.get(0).toString())); return dataEntities.get(0); } @Override public boolean remove(final int n) { if (n <= 0) { Log.debug(ServiceConstants.LOG_TAG, LOG_PREFIX, "remove n - Returning false, n <= 0"); return false; } synchronized (dbMutex) { if (isClose) { Log.warning( ServiceConstants.LOG_TAG, LOG_PREFIX, "remove n - Returning false, DataQueue is closed"); return false; } boolean result = SQLiteDatabaseHelper.process( databasePath, SQLiteDatabaseHelper.DatabaseOpenMode.READ_WRITE, database -> { if (database == null) { return false; } String builder = "DELETE FROM " + TABLE_NAME + " WHERE id in (" + "SELECT id from " + TABLE_NAME + " order by id ASC" + " limit " + n + ')'; try (SQLiteStatement statement = database.compileStatement(builder)) { int deletedRowsCount = statement.executeUpdateDelete(); Log.trace( ServiceConstants.LOG_TAG, LOG_PREFIX, String.format( "remove n - Removed %d DataEntities", deletedRowsCount)); return deletedRowsCount > -1; } catch (final SQLiteException e) { Log.warning( ServiceConstants.LOG_TAG, LOG_PREFIX, String.format( "removeRows - Error in deleting rows from" + " table. Returning 0. Error: (%s)", e.getMessage())); return false; } }); if (!result) { resetDatabase(); } return result; } } @Override public boolean remove() { return remove(1); } @Override public boolean clear() { synchronized (dbMutex) { if (isClose) { Log.warning( ServiceConstants.LOG_TAG, LOG_PREFIX, "clear - Returning false, DataQueue is closed"); return false; } boolean result = SQLiteDatabaseHelper.clearTable(databasePath, TABLE_NAME); Log.trace( ServiceConstants.LOG_TAG, LOG_PREFIX, String.format( "clear - %s in clearing table", (result ? "Successful" : "Failed"))); if (!result) { resetDatabase(); } return true; } } @Override public int count() { synchronized (dbMutex) { if (isClose) { Log.warning( ServiceConstants.LOG_TAG, LOG_PREFIX, "count - Returning 0, DataQueue is closed"); return 0; } return SQLiteDatabaseHelper.getTableSize(databasePath, TABLE_NAME); } } @Override public void close() { synchronized (dbMutex) { isClose = true; } } /** * Creates a Table with name {@link #TABLE_NAME}, if not already exists in database at path * {@link #databasePath}. */ private void createTableIfNotExists() { final String tableCreationQuery = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, " + "uniqueIdentifier TEXT NOT NULL UNIQUE, " + "timestamp INTEGER NOT NULL, " + "data TEXT);"; synchronized (dbMutex) { if (SQLiteDatabaseHelper.createTableIfNotExist(databasePath, tableCreationQuery)) { Log.trace( ServiceConstants.LOG_TAG, LOG_PREFIX, "createTableIfNotExists - Successfully created/already existed" + " table."); return; } } Log.warning( ServiceConstants.LOG_TAG, LOG_PREFIX, "createTableIfNotExists - Error creating/accessing table."); } /** * Add a new {@link DataEntity} Object to {@link DataQueue}. NOTE: The caller must hold the * dbMutex. */ private boolean tryAddEntity(final DataEntity dataEntity) { return SQLiteDatabaseHelper.process( databasePath, SQLiteDatabaseHelper.DatabaseOpenMode.READ_WRITE, database -> { if (database == null) { return false; } final int INDEX_UUID = 1; final int INDEX_TIMESTAMP = 2; final int INDEX_DATA = 3; try (SQLiteStatement insertStatement = database.compileStatement( "INSERT INTO " + TABLE_NAME + " (uniqueIdentifier, timestamp, data) VALUES (?," + " ?, ?)")) { insertStatement.bindString(INDEX_UUID, dataEntity.getUniqueIdentifier()); insertStatement.bindLong( INDEX_TIMESTAMP, dataEntity.getTimestamp().getTime()); insertStatement.bindString( INDEX_DATA, dataEntity.getData() != null ? dataEntity.getData() : ""); long rowId = insertStatement.executeInsert(); return rowId >= 0; } catch (Exception e) { Log.debug( ServiceConstants.LOG_TAG, LOG_PREFIX, "add - Returning false: " + e.getLocalizedMessage()); return false; } }); } /** Resets the database. NOTE: The caller must hold the dbMutex. */ private void resetDatabase() { Log.warning( ServiceConstants.LOG_TAG, LOG_PREFIX, "resetDatabase - Resetting database (%s) as it is corrupted", databasePath); try { FileUtils.deleteFile(new File(databasePath), false); createTableIfNotExists(); } catch (Exception ex) { Log.warning( ServiceConstants.LOG_TAG, LOG_PREFIX, "resetDatabase - Error resetting database (%s) ", databasePath); } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/Presentation.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui import com.adobe.marketing.mobile.services.ui.alert.AlertEventListener import com.adobe.marketing.mobile.services.ui.alert.AlertSettings import com.adobe.marketing.mobile.services.ui.floatingbutton.FloatingButtonEventHandler import com.adobe.marketing.mobile.services.ui.floatingbutton.FloatingButtonEventListener import com.adobe.marketing.mobile.services.ui.floatingbutton.FloatingButtonSettings import com.adobe.marketing.mobile.services.ui.message.InAppMessageEventHandler import com.adobe.marketing.mobile.services.ui.message.InAppMessageEventListener import com.adobe.marketing.mobile.services.ui.message.InAppMessageSettings import java.util.UUID /** * Defines types of [Presentable]s supported by the AEP SDK. * Holds the [PresentationEventListener] for the presentation. */ sealed class Presentation<T : Presentation<T>>(val listener: PresentationEventListener<T>) { /** * The unique identifier for this presentation. */ val id: String = UUID.randomUUID().toString() } // ---- Presentation Types ---- // /** * Represents an InAppMessage presentation. * @param settings the settings for the InAppMessage * @param eventListener the listener for getting notifications about InAppMessage lifecycle events * @param eventHandler the event handler performing operations on the InAppMessage */ class InAppMessage( val settings: InAppMessageSettings, val eventListener: InAppMessageEventListener ) : Presentation<InAppMessage>(eventListener) { /** * The event handler for the InAppMessage. */ lateinit var eventHandler: InAppMessageEventHandler internal set } /** * Represents a FloatingButton presentation. * @param eventListener the listener for getting notifications about FloatingButton lifecycle events * @param settings the settings for the FloatingButton */ class FloatingButton( val settings: FloatingButtonSettings, val eventListener: FloatingButtonEventListener ) : Presentation<FloatingButton>(eventListener) { /** * The event handler for the FloatingButton. */ lateinit var eventHandler: FloatingButtonEventHandler internal set } /** * Represents an Alert presentation. * @param settings the settings for the Alert * @param eventListener the listener for getting notifications about Alert lifecycle events */ class Alert( val settings: AlertSettings, val eventListener: AlertEventListener ) : Presentation<Alert>(eventListener)
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/PresentationUtilityProvider.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui import android.app.Activity import android.app.Application import java.io.InputStream /** * The PresentationUtilityProvider is used to provide the necessary utilities for the UI SDK to function */ interface PresentationUtilityProvider { /** * Retrieves the [Application] instance for the host application. * * @return the [Application] instance for the host application */ fun getApplication(): Application? /** * Retrieves the current activity being shown to the user. * * @return the current activity being shown to the user if one exists, null otherwise */ fun getCurrentActivity(): Activity? /** * Retrieves any cached content for the given cache name and key. * @param cacheName the name of the cache to retrieve content from * @param key the key of the content to retrieve * @return an [InputStream] containing the cached content if it exists, null otherwise. */ fun getCachedContent(cacheName: String, key: String): InputStream? /** * Opens the given [uri]. * @param uri the URI to open * @return true if the URI was opened successfully, false otherwise. */ fun openUri(uri: String): Boolean }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/PresentationEventListener.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui /** * A notification mechanism for the component that created the associated [Presentable] to receive events * about a presentation in response to user interaction, system events, or operations performed programmatically. */ interface PresentationEventListener<T : Presentation<T>> { /** * Invoked when the presentable is shown. * @param presentable the presentable that was shown */ fun onShow(presentable: Presentable<T>) /** * Invoked when the presentable is hidden. * @param presentable the presentable that was hidden */ fun onHide(presentable: Presentable<T>) /** * Invoked when the presentable is dismissed. * @param presentable the presentable that was dismissed */ fun onDismiss(presentable: Presentable<T>) /** * Invoked when an error occurs while managing the presentable. * @param presentable the presentable that encountered the error * @param error the error that occurred */ fun onError(presentable: Presentable<T>, error: PresentationError) }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/Presentable.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui /** * Represents a component that can be presented on the screen. */ interface Presentable<T : Presentation<*>> { /** * Represents the current visibility & activeness of the presentable. */ enum class State { /** * Indicates that the presentable is visible on the screen. */ VISIBLE, /** * Indicates that the presentable was previously VISIBLE but is now hidden from the screen. */ HIDDEN, /** * Indicates that the presentable has either been removed from the screen or has not been shown yet. */ DETACHED } /** * Shows the presentable on the screen. */ fun show() /** * Hides the presentable from the screen. * Contents of the presentable can be restored by calling [show] after this operation. */ fun hide() /** * Dismisses the presentable from the screen. * Contents of the presentable are not retained after this operation. */ fun dismiss() /** * Returns the current [State] of the presentable. */ fun getState(): State /** * Returns the presentation associated with the presentable. * @return the [Presentation] associated with the presentable */ fun getPresentation(): T }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/AEPUIService.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui import android.app.Application import com.adobe.marketing.mobile.services.Log import com.adobe.marketing.mobile.services.ServiceConstants import com.adobe.marketing.mobile.services.ui.alert.AlertPresentable import com.adobe.marketing.mobile.services.ui.common.AppLifecycleProvider import com.adobe.marketing.mobile.services.ui.floatingbutton.FloatingButtonPresentable import com.adobe.marketing.mobile.services.ui.floatingbutton.FloatingButtonViewModel import com.adobe.marketing.mobile.services.ui.message.InAppMessagePresentable import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob /** * UI Service implementation for AEP SDK */ internal class AEPUIService : UIService { companion object { private const val LOG_TAG = "AEPUIService" } private var presentationDelegate: PresentationDelegate? = null private val exceptionHandler = CoroutineExceptionHandler { _, throwable -> Log.error( ServiceConstants.LOG_TAG, LOG_TAG, "An error occurred while processing the presentation: ${throwable.message}", throwable ) } private val mainScope by lazy { CoroutineScope(Dispatchers.Main + SupervisorJob() + exceptionHandler) } @Suppress("UNCHECKED_CAST") override fun <T : Presentation<T>> create( presentation: T, presentationUtilityProvider: PresentationUtilityProvider ): Presentable<T> { // start the app lifecycle provider if not started. Calling this multiple times is safe. val application: Application = presentationUtilityProvider.getApplication() ?: throw IllegalStateException("Application is null. Please provide a valid application instance.") AppLifecycleProvider.INSTANCE.start(application) when (presentation) { is InAppMessage -> { return InAppMessagePresentable( presentation, presentationDelegate, presentationUtilityProvider, AppLifecycleProvider.INSTANCE, mainScope ) as Presentable<T> } is Alert -> { return AlertPresentable( presentation, presentationDelegate, presentationUtilityProvider, AppLifecycleProvider.INSTANCE, mainScope ) as Presentable<T> } is FloatingButton -> { return FloatingButtonPresentable( presentation, FloatingButtonViewModel(presentation.settings), presentationDelegate, presentationUtilityProvider, AppLifecycleProvider.INSTANCE, mainScope ) as Presentable<T> } else -> { throw IllegalArgumentException("Presentation type: $presentation not supported") } } } override fun setPresentationDelegate(presentationDelegate: PresentationDelegate) { this.presentationDelegate = presentationDelegate } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/PresentationListener.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui /** * A listener for observing the lifecycle of presentations managed by the SDK. */ interface PresentationListener { /** * Invoked when a the presentable is shown. * @param presentable the [Presentable] that was shown */ fun onShow(presentable: Presentable<*>) /** * Invoked when a presentable is hidden. * @param presentable the [Presentable] that was hidden */ fun onHide(presentable: Presentable<*>) /** * Invoked when a presentable is dismissed. * @param presentable the [Presentable] that was dismissed */ fun onDismiss(presentable: Presentable<*>) /** * Invoked when the content in the presentable is loaded. * @param presentable the [Presentable] into which that was loaded * @param presentationContent optional [PresentationContent] that was loaded into the presentable */ fun onContentLoaded(presentable: Presentable<*>, presentationContent: PresentationContent?) /** * Defines the types of content that can be loaded into a [Presentable]. */ sealed class PresentationContent { /** * Content loaded from a URL. * @param url the URL from which the content was loaded */ class UrlContent(val url: String) : PresentationContent() } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/PresentationError.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui /** * Defines a hierarchy of errors that can occur when managing a UI element */ sealed interface PresentationError /** * Types of Presentation errors and each of these classes represent their type hierarchies as needed. */ sealed class ShowFailed(val reason: String) : PresentationError sealed class HideFailed(val reason: String) : PresentationError sealed class DismissFailed(val reason: String) : PresentationError // ---- ShowFailed types ---- // /** * Represents a failure to show a Presentable because a conflicting presentation is already shown. */ object ConflictingPresentation : ShowFailed("Conflict") /** * Represents a failure to show a Presentable because there is no activity to show it on. */ object NoAttachableActivity : ShowFailed("No attachable activity available.") /** * Represents a failure to show a Presentable because the delegate gate was not met. */ @Deprecated("Use SuppressedByAppDeveloper instead", ReplaceWith("SuppressedByAppDeveloper")) object DelegateGateNotMet : ShowFailed("PresentationDelegate suppressed the presentation from being shown.") /** * Represents a failure to show a Presentable because the app developer has suppressed [Presentable]s. */ object SuppressedByAppDeveloper : ShowFailed("SuppressedByAppDeveloper") /** * Represents a failure to show a Presentable because it is already shown. */ object AlreadyShown : ShowFailed("Presentable is already being shown.") // ---- HideFailed types ---- // /** * Represents a failure to hide a Presentable because there is no activity to hide it from. */ object AlreadyHidden : HideFailed("Presentable is already hidden.") // ---- DismissFailed types ---- // /** * Represents a failure to dismiss a Presentable because there is no activity to dismiss it from. */ object NoActivityToDetachFrom : DismissFailed("No activity available to detach from.") /** * Represents a failure to dismiss a Presentable because it is not shown. */ object AlreadyDismissed : DismissFailed("Presentable is already dismissed.")
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/UIService.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui /** * Represents a component capable of creating and managing UI elements. */ interface UIService { /** * Creates a Presentable for the given [presentation]. * @param presentation The [Presentation] type to be created * @param presentationUtilityProvider a [PresentationUtilityProvider] that provides components * that should be used for creating the presentation. * @return a [Presentable] that is associated with the [presentation]. */ fun <T : Presentation<T>> create( presentation: T, presentationUtilityProvider: PresentationUtilityProvider ): Presentable<T> /** * Sets the presentation delegate for the SDK. * @param presentationDelegate a [PresentationDelegate] that will be used to notify presentation events * and query for approval before presentation is displayed. */ fun setPresentationDelegate(presentationDelegate: PresentationDelegate) }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/PresentationDelegate.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui /** * A delegate that can be used to observe and control the lifecycle of [Presentation]'s managed by the SDK. */ interface PresentationDelegate : PresentationListener, PresentationLever
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/PresentationLever.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui /** * A gating mechanism for implementers to restrict the display of a [Presentable] based on specific * set of conditions. */ interface PresentationLever { /** * Returns true if [presentable] can be shown, false otherwise. * @param presentable the [Presentable] to check if it can be shown * @return true if [presentable] can be shown, false otherwise */ fun canShow(presentable: Presentable<*>): Boolean }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/alert/AlertEventListener.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.alert import com.adobe.marketing.mobile.services.ui.Alert import com.adobe.marketing.mobile.services.ui.Presentable import com.adobe.marketing.mobile.services.ui.PresentationEventListener /** * Interface for listening to events related to an Alert presentation. */ interface AlertEventListener : PresentationEventListener<Alert> { /** * Called when positive button on the alert is clicked. * @param alert the alert that was clicked */ fun onPositiveResponse(alert: Presentable<Alert>) /** * Called when negative button on the alert is clicked. * @param alert the alert that was clicked */ fun onNegativeResponse(alert: Presentable<Alert>) }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/alert/AlertSettings.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.alert import com.adobe.marketing.mobile.services.ui.Alert /** * Settings for an [Alert] presentation. * @param title the title of the alert * @param message the message of the alert * @param positiveButtonText the text for the positive button * @param negativeButtonText the text for the negative button */ class AlertSettings private constructor( val title: String, val message: String, val positiveButtonText: String?, val negativeButtonText: String? ) { class Builder { private var title: String = "" private var message: String = "" private var positiveButtonText: String? = null private var negativeButtonText: String? = null /** * Sets the title of the alert. * @param title the title of the alert */ fun title(title: String) = apply { this.title = title } /** * Sets the message of the alert. * @param message the message of the alert */ fun message(message: String) = apply { this.message = message } /** * Sets the text for the positive button. * @param positiveButtonText the text for the positive button */ fun positiveButtonText(positiveButtonText: String) = apply { this.positiveButtonText = positiveButtonText } /** * Sets the text for the negative button. * @param negativeButtonText the text for the negative button */ fun negativeButtonText(negativeButtonText: String) = apply { this.negativeButtonText = negativeButtonText } fun build() = run { if (positiveButtonText == null && negativeButtonText == null) { throw IllegalArgumentException("At least one button must be defined.") } AlertSettings( title, message, positiveButtonText, negativeButtonText ) } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/alert/AlertPresentable.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.alert import android.content.Context import androidx.compose.ui.platform.ComposeView import com.adobe.marketing.mobile.services.ui.Alert import com.adobe.marketing.mobile.services.ui.InAppMessage import com.adobe.marketing.mobile.services.ui.Presentation import com.adobe.marketing.mobile.services.ui.PresentationDelegate import com.adobe.marketing.mobile.services.ui.PresentationUtilityProvider import com.adobe.marketing.mobile.services.ui.alert.views.AlertScreen import com.adobe.marketing.mobile.services.ui.common.AEPPresentable import com.adobe.marketing.mobile.services.ui.common.AppLifecycleProvider import kotlinx.coroutines.CoroutineScope /** * Represents an Alert presentable. * @param alert the alert that this presentable will be tied to * @param presentationDelegate the presentation delegate to use for notifying lifecycle events * @param presentationUtilityProvider the presentation utility provider to use for performing operations on the presentable * @param appLifecycleProvider the app lifecycle provider to use for listening to lifecycle events */ internal class AlertPresentable( val alert: Alert, presentationDelegate: PresentationDelegate?, presentationUtilityProvider: PresentationUtilityProvider, appLifecycleProvider: AppLifecycleProvider, mainScope: CoroutineScope ) : AEPPresentable<Alert>( alert, presentationUtilityProvider, presentationDelegate, appLifecycleProvider, mainScope ) { override fun getContent(activityContext: Context): ComposeView { return ComposeView(activityContext).apply { setContent { AlertScreen( presentationStateManager = presentationStateManager, alertSettings = alert.settings, onPositiveResponse = { alert.eventListener.onPositiveResponse(this@AlertPresentable) dismiss() }, onNegativeResponse = { alert.eventListener.onNegativeResponse(this@AlertPresentable) dismiss() }, onBackPressed = { dismiss() } ) } } } override fun gateDisplay(): Boolean { return false } override fun getPresentation(): Alert { return alert } override fun hasConflicts(visiblePresentations: List<Presentation<*>>): Boolean { // Only show if there are no other alerts or in-app messages visible return visiblePresentations.any { (it is Alert || it is InAppMessage) } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/alert/views/AlertScreen.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.alert.views import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.fadeIn import androidx.compose.material.AlertDialog import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.window.DialogProperties import com.adobe.marketing.mobile.services.ui.alert.AlertSettings import com.adobe.marketing.mobile.services.ui.common.PresentationStateManager /** * Composable function to display an alert dialog. * @param presentationStateManager [PresentationStateManager] to manage the visibility state of the alert dialog. * @param alertSettings [AlertSettings] to configure the alert dialog. * @param onPositiveResponse callback to be invoked when the user clicks on the positive button. * @param onNegativeResponse callback to be invoked when the user clicks on the negative button. * @param onBackPressed callback to be invoked when the user performs back navigation. */ @Composable internal fun AlertScreen( presentationStateManager: PresentationStateManager, alertSettings: AlertSettings, onPositiveResponse: () -> Unit, onNegativeResponse: () -> Unit, onBackPressed: () -> Unit ) { AnimatedVisibility( visibleState = presentationStateManager.visibilityState, enter = fadeIn() ) { AlertDialog( title = { Text( text = alertSettings.title, modifier = Modifier.testTag(AlertTestTags.TITLE_TEXT) ) }, text = { Text( text = alertSettings.message, modifier = Modifier.testTag(AlertTestTags.MESSAGE_TEXT) ) }, confirmButton = { alertSettings.positiveButtonText?.let { positiveButtonText -> TextButton( onClick = { onPositiveResponse() }, modifier = Modifier.testTag(AlertTestTags.POSITIVE_BUTTON) ) { Text(text = positiveButtonText) } } }, dismissButton = { alertSettings.negativeButtonText?.let { negativeButtonText -> TextButton( onClick = { onNegativeResponse() }, modifier = Modifier.testTag(AlertTestTags.NEGATIVE_BUTTON) ) { Text(text = negativeButtonText) } } }, onDismissRequest = { // Slightly roundabout way to dismiss the dialog! DialogProperties determine when a // dismiss request is received. They are set to dismiss on back press and not any clicks outside. // So all dismiss requests are from back press. onBackPressed() }, properties = DialogProperties( dismissOnBackPress = true, dismissOnClickOutside = false ) ) } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/alert/views/AlertTestTags.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.alert.views internal object AlertTestTags { internal const val TITLE_TEXT = "titleText" internal const val MESSAGE_TEXT = "messageText" internal const val POSITIVE_BUTTON = "positiveButton" internal const val NEGATIVE_BUTTON = "negativeButton" }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/floatingbutton/FloatingButtonEventListener.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.floatingbutton import com.adobe.marketing.mobile.services.ui.FloatingButton import com.adobe.marketing.mobile.services.ui.Presentable import com.adobe.marketing.mobile.services.ui.PresentationEventListener /** * Interface for listening to events on a floating button presentation. */ interface FloatingButtonEventListener : PresentationEventListener<FloatingButton> { /** * Called when a tap is detected on the floating button. * @param presentable the floating button presentable on which the tap was detected */ fun onTapDetected(presentable: Presentable<FloatingButton>) /** * Called when a pan is detected on the floating button. * @param presentable the floating button presentable on which the pan was detected */ fun onPanDetected(presentable: Presentable<FloatingButton>) }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/floatingbutton/FloatingButtonEventHandler.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.floatingbutton import android.graphics.Bitmap /** * Interface for taking actions on an FloatingButton presentation. */ interface FloatingButtonEventHandler { /** * Updates the current content of the floating button. * @param graphic the new content of the floating button */ fun updateGraphic(graphic: Bitmap) }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/floatingbutton/FloatingButtonPresentable.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.floatingbutton import android.content.Context import android.graphics.Bitmap import androidx.compose.ui.platform.ComposeView import com.adobe.marketing.mobile.services.ui.FloatingButton import com.adobe.marketing.mobile.services.ui.Presentation import com.adobe.marketing.mobile.services.ui.PresentationDelegate import com.adobe.marketing.mobile.services.ui.PresentationUtilityProvider import com.adobe.marketing.mobile.services.ui.common.AEPPresentable import com.adobe.marketing.mobile.services.ui.common.AppLifecycleProvider import com.adobe.marketing.mobile.services.ui.floatingbutton.views.FloatingButtonScreen import kotlinx.coroutines.CoroutineScope /** * Represents a presentable floating button presentation * @param floatingButton the floating button to be presented * @param floatingButtonViewModel the view model for the floating button * @param presentationDelegate the presentation delegate used when for notifying actions on the floating button * @param presentationUtilityProvider the presentation utility provider used for performing actions on the floating button * @param appLifecycleProvider the app lifecycle provider used for listening to app lifecycle events */ internal class FloatingButtonPresentable( private val floatingButton: FloatingButton, private val floatingButtonViewModel: FloatingButtonViewModel, presentationDelegate: PresentationDelegate?, presentationUtilityProvider: PresentationUtilityProvider, appLifecycleProvider: AppLifecycleProvider, mainScope: CoroutineScope ) : AEPPresentable<FloatingButton>( floatingButton, presentationUtilityProvider, presentationDelegate, appLifecycleProvider, mainScope ) { // event handler for the floating button private val floatingButtonEventHandler = object : FloatingButtonEventHandler { override fun updateGraphic(graphic: Bitmap) { floatingButtonViewModel.onGraphicUpdate(graphic) } } init { floatingButton.eventHandler = floatingButtonEventHandler // update the initial graphic on the view model floatingButton.settings.initialGraphic.let { floatingButtonViewModel.onGraphicUpdate(it) } } override fun getContent(activityContext: Context): ComposeView { return ComposeView(activityContext).apply { setContent { FloatingButtonScreen( presentationStateManager = presentationStateManager, floatingButtonSettings = floatingButton.settings, floatingButtonViewModel = floatingButtonViewModel, onTapDetected = { floatingButton.eventListener.onTapDetected(this@FloatingButtonPresentable) }, onPanDetected = { floatingButton.eventListener.onPanDetected(this@FloatingButtonPresentable) } ) } } } override fun gateDisplay(): Boolean { // Floating button presentation display does not need to be gated via delegate consultation return false } override fun getPresentation(): FloatingButton { return floatingButton } override fun hasConflicts(visiblePresentations: List<Presentation<*>>): Boolean { // Floating button presentation can be shown irrespective of other visible presentations return false } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/floatingbutton/FloatingButtonSettings.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.floatingbutton import android.graphics.Bitmap import java.lang.IllegalArgumentException /** * Settings for the FloatingButton * @param height height of the button in dp * @param width width of the button in dp * @param initialGraphic initial graphic to be displayed on the button * @param cornerRadius corner radius of the button in dp */ class FloatingButtonSettings private constructor( val height: Int, val width: Int, val initialGraphic: Bitmap, val cornerRadius: Float ) { class Builder { private var height: Int = 56 // default height per material design spec private var width: Int = 56 // default width per material design spec private var initialGraphic: Bitmap? = null private var cornerRadius: Float = 5f /** * Sets the height of the floating button. * @param height height of the button in dp */ fun height(height: Int) = apply { this.height = height } /** * Sets the width in of the floating button. * @param width width of the button in dp */ fun width(width: Int) = apply { this.width = width } /** * Sets the corner radius of the floating button. * @param cornerRadius corner radius of the button in dp */ fun cornerRadius(cornerRadius: Float) = apply { this.cornerRadius = cornerRadius } /** * Sets the initial graphic to be displayed on the floating button. * @param initialGraphic initial graphic to be displayed on the button */ fun initialGraphic(initialGraphic: Bitmap) = apply { this.initialGraphic = initialGraphic } fun build() = run { initialGraphic?.let { graphic -> FloatingButtonSettings(height, width, graphic, cornerRadius) } ?: throw IllegalArgumentException("Initial graphic must be set") } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/floatingbutton/FloatingButtonViewModel.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.floatingbutton import android.content.res.Configuration import android.graphics.Bitmap import androidx.compose.runtime.MutableState import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.asImageBitmap /** * A simple view model for the FloatingButton screen. Maintains the state for the Floating Button and has * auxiliary methods for updating the state. Responsible for ensuring the state of the button is * maintained and updated across orientation changes. */ internal class FloatingButtonViewModel(settings: FloatingButtonSettings) { companion object { private const val LOG_TAG = "FloatingButtonViewModel" } // Current graphic as a state to be displayed on the floating button. // ImageBitmap should at least have a size of 1x1 to be created. private val _currentGraphic: MutableState<ImageBitmap> = mutableStateOf(settings.initialGraphic.asImageBitmap()) internal val currentGraphic: State<ImageBitmap> = _currentGraphic // Offsets of the floating button in landscape and portrait mode internal var landscapeOffSet: Offset = Offset.Unspecified internal var portraitOffSet: Offset = Offset.Unspecified /** * Updates the current graphic of the floating button. * @param graphic the new content of the floating button */ internal fun onGraphicUpdate(graphic: Bitmap) { _currentGraphic.value = graphic.asImageBitmap() } /** * Updates the current position of the floating button. * @param offset the new position of the floating button * @param orientation the orientation ([Configuration.ORIENTATION_LANDSCAPE] or [Configuration.ORIENTATION_PORTRAIT]) * of the device */ internal fun onPositionUpdate(offset: Offset, orientation: Int) { if (offset.x < 0 || offset.y < 0) { return } if (orientation == Configuration.ORIENTATION_LANDSCAPE) { landscapeOffSet = offset } else { portraitOffSet = offset } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/floatingbutton/views/FloatingButton.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.floatingbutton.views import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.FloatingActionButton import androidx.compose.material.FloatingActionButtonDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.input.pointer.consumeAllChanges import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.testTag import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import com.adobe.marketing.mobile.services.ui.floatingbutton.FloatingButtonSettings import kotlin.math.roundToInt /** * Represents the floating button view. * @param settings the settings for the floating button * @param graphic the graphic to display on the floating button * @param offset the offset of the floating button from the top left corner of the screen * @param onClick the action to take when the floating button is clicked */ @Composable internal fun FloatingButton( settings: FloatingButtonSettings, graphic: State<ImageBitmap>, offset: Offset = Offset.Unspecified, onClick: () -> Unit, onDragFinished: (Offset) -> Unit ) { // Floating button draggable area dimensions val heightDp = with(LocalConfiguration.current) { mutableStateOf(screenHeightDp.dp) } val widthDp = with(LocalConfiguration.current) { mutableStateOf(screenWidthDp.dp) } // Floating button dimensions val fbHeightDp: Dp = remember { settings.height.dp } val fbWidthDp: Dp = remember { settings.width.dp } val padding: Dp = remember { 4.dp } // Calculate initial offset of the floating button. The default offset is the top right corner // of the screen. If the offset is specified, then use that value instead. val widthPx = with(LocalDensity.current) { remember { widthDp.value.toPx() } } val fbWidthPx = with(LocalDensity.current) { remember { fbWidthDp.toPx() } } val paddingPx = with(LocalDensity.current) { remember { padding.toPx() } } val correctedOffset = remember { if (offset == Offset.Unspecified) { Offset( widthPx - fbWidthPx - paddingPx, 0f ) } else { offset } } // Tracks the offset of the floating button as a result of dragging val offsetState = remember { mutableStateOf(correctedOffset) } // The draggable area for the floating button Box( modifier = Modifier .height(heightDp.value) .width(widthDp.value) .testTag(FloatingButtonTestTags.FLOATING_BUTTON_AREA) ) { FloatingActionButton( modifier = Modifier .height(fbHeightDp) .width(fbWidthDp) .padding(padding) .wrapContentSize() .offset { IntOffset( offsetState.value.x.roundToInt(), offsetState.value.y.roundToInt() ) } .pointerInput(Unit) { detectDragGestures( onDragEnd = { onDragFinished(offsetState.value) } ) { change, dragAmount -> change.consumeAllChanges() // Calculate new offset as a result of dragging val newX = (offsetState.value.x + dragAmount.x) val newY = (offsetState.value.y + dragAmount.y) // Update the offset state with the new calculated offset while ensuring // that the floating button stays within the draggable area. // Offset values are in pixels, so we need to convert Dp to Px offsetState.value = Offset( newX.coerceIn(0f, (widthDp.value - fbWidthDp).toPx()), newY.coerceIn(0f, (heightDp.value - fbHeightDp).toPx()) ) } } .testTag(FloatingButtonTestTags.FLOATING_BUTTON), // Remove the default elevation and background color of the floating button to ensure // that the floating button graphic is the only thing that is displayed without any // additional white background or shadow elevation = FloatingActionButtonDefaults.elevation(0.dp, 0.dp), onClick = { onClick() }, shape = RoundedCornerShape(settings.cornerRadius.dp), backgroundColor = Color.Transparent ) { // Represents the floating button graphic Image( bitmap = graphic.value, contentDescription = "Floating Button", modifier = Modifier .background(Color.Transparent) .wrapContentSize() .testTag(FloatingButtonTestTags.FLOATING_BUTTON_GRAPHIC) ) } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/floatingbutton/views/FloatingButtonScreen.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.floatingbutton.views import android.content.res.Configuration import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.fadeIn import androidx.compose.runtime.Composable import androidx.compose.ui.geometry.Offset import androidx.compose.ui.platform.LocalConfiguration import com.adobe.marketing.mobile.services.ui.common.PresentationStateManager import com.adobe.marketing.mobile.services.ui.floatingbutton.FloatingButtonSettings import com.adobe.marketing.mobile.services.ui.floatingbutton.FloatingButtonViewModel /** * Represents the floating button screen. Composes the [FloatingButton] composable and * manages its visibility. * @param presentationStateManager the [PresentationStateManager] for the floating button * @param floatingButtonSettings the [FloatingButtonSettings] for the floating button * @param floatingButtonViewModel the [FloatingButtonViewModel] for the floating button * @param onTapDetected the callback to be notified when the floating button is tapped * @param onPanDetected the callback to be notified when the floating button is dragged */ @Composable internal fun FloatingButtonScreen( presentationStateManager: PresentationStateManager, floatingButtonSettings: FloatingButtonSettings, floatingButtonViewModel: FloatingButtonViewModel, onTapDetected: () -> Unit, onPanDetected: (Offset) -> Unit ) { AnimatedVisibility( visibleState = presentationStateManager.visibilityState, enter = fadeIn() ) { val orientation = LocalConfiguration.current.orientation FloatingButton( settings = floatingButtonSettings, graphic = floatingButtonViewModel.currentGraphic, offset = if (orientation == Configuration.ORIENTATION_LANDSCAPE) { floatingButtonViewModel.landscapeOffSet } else { floatingButtonViewModel.portraitOffSet }, onClick = { onTapDetected() }, onDragFinished = { floatingButtonViewModel.onPositionUpdate(it, orientation) onPanDetected(it) } ) } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/floatingbutton/views/FloatingButtonTestTags.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.floatingbutton.views internal object FloatingButtonTestTags { internal const val FLOATING_BUTTON_AREA = "floatingButtonArea" internal const val FLOATING_BUTTON = "floatingButton" internal const val FLOATING_BUTTON_GRAPHIC = "floatingButtonGraphic" }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/message/InAppMessageWebViewClient.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.message import android.net.Uri import android.webkit.MimeTypeMap import android.webkit.WebResourceRequest import android.webkit.WebResourceResponse import android.webkit.WebView import android.webkit.WebViewClient import com.adobe.marketing.mobile.services.Log import com.adobe.marketing.mobile.services.ServiceConstants import com.adobe.marketing.mobile.services.ui.PresentationUtilityProvider import java.io.InputStream import java.net.MalformedURLException import java.net.URL /** * A [WebViewClient] that handles content loading for an in-app message. * @param messageSettings the [InAppMessageSettings] for the current message. * @param presentationUtilityProvider the [PresentationUtilityProvider] for accessing cached resources. * @param onUrlLoading a callback invoked when a url is intercepted by the webview. The callback returns true if the * url was handled by the SDK or false if the url will not be handled. */ internal class InAppMessageWebViewClient( private val messageSettings: InAppMessageSettings, private val presentationUtilityProvider: PresentationUtilityProvider, private val onUrlLoading: (String) -> Boolean ) : WebViewClient() { companion object { private const val LOG_TAG = "InAppMessageWebViewClient" fun isValidUrl(stringUrl: String?): Boolean { return if (stringUrl.isNullOrBlank()) { false } else { try { URL(stringUrl) true } catch (ex: MalformedURLException) { false } } } } override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean { val uri: Uri? = request?.url return handleUrl(uri?.toString()) } override fun shouldInterceptRequest( view: WebView?, request: WebResourceRequest ): WebResourceResponse? { val webResourceResponse: WebResourceResponse? = handleWebResourceRequest(request.url.toString()) return webResourceResponse ?: super.shouldInterceptRequest(view, request) } /** * Passes a URL string to the AEP SDK for processing. * * @param url a []String] url intercepted from a on the webview. * @return false if the SDK didn't handle the url or true if the url was handled. */ private fun handleUrl(url: String?): Boolean { if (url.isNullOrBlank()) { Log.trace( ServiceConstants.LOG_TAG, LOG_TAG, "Unable to handle a null or empty url." ) // returning true here implies we "handled" the url by preventing the url loading return true } return onUrlLoading(url) } /** * Returns an instance of [WebResourceResponse] containing an input stream from a cached * remote resource. * * @param url a `String` URL to a remote resource. * @return an instance of `WebResourceResponse` containing an input stream from a cached * remote resource if it exists, otherwise null. Also returns null in the following cases: * <li> If the url is not a http/https URL. </li> * <li> If the cache location in the asset map is null. </li> * <li> If the cached image is not present </li> */ private fun handleWebResourceRequest(url: String?): WebResourceResponse? { if (url.isNullOrBlank() || !isValidUrl(url)) { Log.trace( ServiceConstants.LOG_TAG, LOG_TAG, "Cannot handle url: $url" ) return null } val cacheLocation: String? = messageSettings.assetMap[url] if (cacheLocation.isNullOrBlank()) { Log.trace( ServiceConstants.LOG_TAG, LOG_TAG, "No cache location found for url: $url" ) return null } val cachedContent: InputStream? = presentationUtilityProvider.getCachedContent(cacheLocation, url) if (cachedContent == null) { Log.trace( ServiceConstants.LOG_TAG, LOG_TAG, "Cached asset not found for url: $url from cache location $cacheLocation." ) return null } val mimeType = MimeTypeMap.getSingleton() .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url)) return WebResourceResponse(mimeType, null, cachedContent) } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/message/GestureTracker.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.message import androidx.compose.animation.ExitTransition import com.adobe.marketing.mobile.services.Log import com.adobe.marketing.mobile.services.ServiceConstants import com.adobe.marketing.mobile.services.ui.message.mapping.MessageAnimationMapper import kotlin.math.abs /** * Keeps track of the gestures on the InAppMessage and translates them to [ExitTransition] to be used * for the exit animation. */ internal class GestureTracker( defaultExitTransition: ExitTransition = ExitTransition.None, private val acceptedGestures: Set<InAppMessageSettings.MessageGesture> = setOf(), private val onGestureDetected: (InAppMessageSettings.MessageGesture) -> Unit ) { companion object { private const val LOG_SOURCE = "GestureTracker" private const val DRAG_THRESHOLD_OFFSET = 400 private const val DRAG_THRESHOLD_VELOCITY = 300 } private var currentExitTransition: ExitTransition = defaultExitTransition /** * Called when the drag is finished. * @param x the x coordinate of the drag (positive is right, negative is left) * @param y the y coordinate of the drag (positive is down, negative is up) * @param velocity the velocity of the drag */ internal fun onDragFinished(x: Float, y: Float, velocity: Float) { val gesture: InAppMessageSettings.MessageGesture? = if (abs(x) > abs(y)) { if (x > 0 && abs(velocity) > DRAG_THRESHOLD_VELOCITY && abs(x) > DRAG_THRESHOLD_OFFSET) { InAppMessageSettings.MessageGesture.SWIPE_RIGHT } else if (x < 0 && abs(velocity) > DRAG_THRESHOLD_VELOCITY && abs(x) > DRAG_THRESHOLD_OFFSET) { InAppMessageSettings.MessageGesture.SWIPE_LEFT } else { null } } else { if (y > 0 && abs(velocity) > DRAG_THRESHOLD_VELOCITY && abs(y) > DRAG_THRESHOLD_OFFSET) { InAppMessageSettings.MessageGesture.SWIPE_DOWN } else if (y < 0 && abs(velocity) > DRAG_THRESHOLD_VELOCITY && abs(y) > DRAG_THRESHOLD_OFFSET) { InAppMessageSettings.MessageGesture.SWIPE_UP } else { null } } gesture?.let { Log.trace(ServiceConstants.LOG_TAG, LOG_SOURCE, "Gesture detected: $gesture with $x, $y, $velocity") onGesture(it) } } /** * To be invoked when a gesture is detected. Responsible for changing the exit transition. */ internal fun onGesture(gesture: InAppMessageSettings.MessageGesture) { Log.trace(ServiceConstants.LOG_TAG, LOG_SOURCE, "Gesture detected: $gesture") // Change the exit transition only if the gesture is supported if (gesture !in acceptedGestures) return currentExitTransition = MessageAnimationMapper.getExitTransitionFor(gesture) onGestureDetected(gesture) } /** * Returns the most recent exit transition to be used for the exit animation, based on * the gestures detected. */ internal fun getExitTransition(): ExitTransition { return currentExitTransition } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/message/DefaultInAppMessageEventHandler.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.message import android.webkit.JavascriptInterface import android.webkit.WebView import androidx.annotation.MainThread import androidx.annotation.VisibleForTesting import com.adobe.marketing.mobile.AdobeCallback import com.adobe.marketing.mobile.services.Log import com.adobe.marketing.mobile.services.ServiceConstants import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import java.io.UnsupportedEncodingException import java.lang.ref.WeakReference import java.net.URLDecoder /** * Default implementation of [InAppMessageEventHandler] that handles inbound interactions with the web view * associated with an in-app message. */ internal class DefaultInAppMessageEventHandler internal constructor( private val scriptHandlers: MutableMap<String, WebViewJavascriptInterface>, private val mainScope: CoroutineScope ) : InAppMessageEventHandler { companion object { private const val LOG_SOURCE = "DefaultInAppMessageEventHandler" } internal var webView: WeakReference<WebView?> = WeakReference(null) @VisibleForTesting get private set override fun handleJavascriptMessage(handlerName: String, callback: AdobeCallback<String>) { val javascriptInterface = WebViewJavascriptInterface { js -> callback.call(js) } scriptHandlers[handlerName] = javascriptInterface Log.debug( ServiceConstants.LOG_TAG, LOG_SOURCE, "Adding javascript interface for handler: $handlerName" ) mainScope.launch { val activeWebView = webView.get() if (activeWebView == null) { Log.warning( ServiceConstants.LOG_TAG, LOG_SOURCE, "Web view is null. Cannot add javascript interface." ) return@launch } activeWebView.addJavascriptInterface(javascriptInterface, handlerName) } } override fun evaluateJavascript(jsContent: String, callback: AdobeCallback<String>) { if (jsContent.isEmpty()) { Log.debug( ServiceConstants.LOG_TAG, LOG_SOURCE, "Javascript content is empty. Cannot evaluate javascript." ) return } val activeWebView = webView.get() if (activeWebView == null) { Log.debug( ServiceConstants.LOG_TAG, LOG_SOURCE, "Web view is null. Cannot evaluate javascript." ) return } val urlDecodedString = try { URLDecoder.decode(jsContent, "UTF-8") } catch (encodingException: UnsupportedEncodingException) { Log.warning( ServiceConstants.LOG_TAG, LOG_SOURCE, "Unsupported encoding exception while decoding javascript content. ${encodingException.message}" ) return } mainScope.launch { activeWebView.evaluateJavascript(urlDecodedString) { result -> Log.trace( ServiceConstants.LOG_TAG, LOG_SOURCE, "Invoking callback with result: $result" ) callback.call(result) } } } /** * Called when the web view associated with the in-app message is reset. * This will re-add all the javascript interfaces to the new web view. * @param webView the new web view associated with the in-app message */ @MainThread internal fun onNewWebView(webView: WebView?) { Log.debug(ServiceConstants.LOG_TAG, LOG_SOURCE, "Internal web view was reset.") webView?.let { this@DefaultInAppMessageEventHandler.webView = WeakReference(it) // re-add all the javascript interfaces scriptHandlers.forEach { (handlerName, javascriptInterface) -> Log.debug( ServiceConstants.LOG_TAG, LOG_SOURCE, "Re-adding javascript interface for handler: $handlerName" ) it.addJavascriptInterface(javascriptInterface, handlerName) } } } /** * A wrapper class for annotating the [callback] as a javascript interface for adding to the web view. */ internal class WebViewJavascriptInterface(private val callback: (String) -> Unit) { @JavascriptInterface fun run(js: String) { callback(js) } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/message/InAppMessageSettings.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.message /** * An immutable class that holds the settings and configuration for the InAppMessage. * * @param content the HTML content for the message * @param width the width of the message as a percentage of the screen width * @param height the height of the message as a percentage of the screen height * @param verticalInset the vertical inset of the message. This is the padding from the top and bottom of the screen * expressed as a percentage of the screen height * @param horizontalInset the horizontal inset of the message. This is the padding from the left and right of the screen * expressed as a percentage of the screen width * @param verticalAlignment the vertical alignment of the message on the screen * @param horizontalAlignment the horizontal alignment of the message on the screen * @param displayAnimation the animation to use when displaying the message * @param dismissAnimation the animation to use when dismissing the message * @param backdropColor the color of the backdrop behind the message. This the color behind the message when the message is taking over the UI. * @param backdropOpacity the opacity of the backdrop behind the message. This the opacity behind the message when the message is taking over the UI. * @param cornerRadius the corner radius of the message * @param shouldTakeOverUi whether interactions with the elements outside the message should be disabled. * Should be set to true if the message should take over the UI, false otherwise. * @param assetMap a map of asset names to asset URLs * @param gestureMap a map of gestures to the names of the actions to be performed when the gesture is detected */ class InAppMessageSettings private constructor( val content: String, val width: Int, val height: Int, val verticalInset: Int, val horizontalInset: Int, val verticalAlignment: MessageAlignment, val horizontalAlignment: MessageAlignment, val displayAnimation: MessageAnimation, val dismissAnimation: MessageAnimation, val backdropColor: String, val backdropOpacity: Float, val cornerRadius: Float, val shouldTakeOverUi: Boolean, val assetMap: Map<String, String>, val gestureMap: Map<MessageGesture, String> ) { /** Enum representing Message alignment. */ enum class MessageAlignment { CENTER, LEFT, RIGHT, TOP, BOTTOM } /** Enum representing Message animations. */ enum class MessageAnimation { NONE, LEFT, RIGHT, TOP, BOTTOM, CENTER, FADE } enum class MessageGesture(private val gestureName: String) { SWIPE_UP("swipeUp"), SWIPE_DOWN("swipeDown"), SWIPE_LEFT("swipeLeft"), SWIPE_RIGHT("swipeRight"), TAP_BACKGROUND("tapBackground"); internal companion object { private val gestureToEnumMap: Map<String, MessageGesture> = values().associateBy { it.gestureName } internal fun getGestureForName(gestureName: String): MessageGesture? = gestureToEnumMap[gestureName] } } /** * Builder class for [InAppMessageSettings]. */ class Builder { private var content: String = "" private var width: Int = 100 private var height: Int = 100 private var verticalInset: Int = 0 private var horizontalInset: Int = 0 private var verticalAlignment: MessageAlignment = MessageAlignment.CENTER private var horizontalAlignment: MessageAlignment = MessageAlignment.CENTER private var displayAnimation: MessageAnimation = MessageAnimation.NONE private var dismissAnimation: MessageAnimation = MessageAnimation.NONE private var backgroundColor: String = "#000000" private var backdropOpacity: Float = 0.0f private var cornerRadius: Float = 0.0f private var shouldTakeOverUi: Boolean = false private var assetMap: MutableMap<String, String> = mutableMapOf() private var gestures: MutableMap<MessageGesture, String> = mutableMapOf() /** * Sets the HTML content for the message. * @param content the HTML content for the message */ fun content(content: String) = apply { this.content = content } /** * Sets the width of the message as a percentage of the screen width. * @param width the width of the message as a percentage of the screen width */ fun width(width: Int) = apply { this.width = clipToPercent(width) } /** * Sets the height of the message as a percentage of the screen height. * @param height the height of the message as a percentage of the screen height */ fun height(height: Int) = apply { this.height = clipToPercent(height) } /** * Sets the vertical inset of the message. This is the padding from the top and bottom * of the screen as a percentage of the screen height. * @param verticalInset the vertical inset of the message */ fun verticalInset(verticalInset: Int) = apply { this.verticalInset = clipToPercent(verticalInset, true) } /** * Sets the horizontal inset of the message. This is the padding from the left and right * of the screen as a percentage of the screen width. */ fun horizontalInset(horizontalInset: Int) = apply { this.horizontalInset = clipToPercent(horizontalInset, true) } /** * Sets the vertical alignment of the message on the screen. * @param verticalAlignment the vertical [MessageAlignment] of the message on the screen */ fun verticalAlignment(verticalAlignment: MessageAlignment) = apply { this.verticalAlignment = verticalAlignment } /** * Sets the horizontal alignment of the message on the screen. * @param horizontalAlignment the horizontal [MessageAlignment] of the message on the screen */ fun horizontalAlignment(horizontalAlignment: MessageAlignment) = apply { this.horizontalAlignment = horizontalAlignment } /** * Sets the animation to use when displaying the message. * @param displayAnimation the [MessageAnimation] to use when displaying the message */ fun displayAnimation(displayAnimation: MessageAnimation) = apply { this.displayAnimation = displayAnimation } /** * Sets the animation to use when dismissing the message. * @param dismissAnimation the [MessageAnimation] to use when dismissing the message */ fun dismissAnimation(dismissAnimation: MessageAnimation) = apply { this.dismissAnimation = dismissAnimation } /** * Sets the color of the backdrop behind the message. This is the color behind the message when the message is taking over the UI. * @param backgroundColor the hex color of the backdrop behind the message. */ fun backgroundColor(backgroundColor: String) = apply { this.backgroundColor = backgroundColor } /** * Sets the opacity of the backdrop behind the message. This is the opacity behind the message when the message is taking over the UI. * @param backdropOpacity the opacity of the backdrop behind the message. This should be a value between 0.0f (transparent) and 1.0f(opaque). */ fun backdropOpacity(backdropOpacity: Float) = apply { this.backdropOpacity = backdropOpacity } /** * Sets the corner radius of the message. * @param cornerRadius the corner radius of the message */ fun cornerRadius(cornerRadius: Float) = apply { this.cornerRadius = cornerRadius } /** * Configures whether the message should take over the UI. * @param shouldTakeOverUi whether the message should take over the UI. Should be set to true if the message should take over the UI, false otherwise. */ fun shouldTakeOverUi(shouldTakeOverUi: Boolean) = apply { this.shouldTakeOverUi = shouldTakeOverUi } /** * Sets the asset map for the message. This is a map of asset names to asset URLs. * @param assetMap the asset map for the message */ fun assetMap(assetMap: Map<String, String>) = apply { this.assetMap = assetMap.toMutableMap() } /** * Sets the gesture map for the message. This is a map of gesture names * (as defined by [InAppMessageSettings.MessageGesture]'s) to gesture actions. * @param gestureMap the gesture map for the message */ fun gestureMap(gestureMap: Map<String, String>) = apply { for ((key, value) in gestureMap) { val gesture: MessageGesture? = MessageGesture.getGestureForName(key) gesture?.let { this@Builder.gestures[gesture] = value } } } fun build() = InAppMessageSettings( content, width, height, verticalInset, horizontalInset, verticalAlignment, horizontalAlignment, displayAnimation, dismissAnimation, backgroundColor, backdropOpacity, cornerRadius, shouldTakeOverUi, assetMap, gestures ) private companion object { /** * Clips a value to a percentage. This is used to ensure that values are between -100 and 100 * when negative values are allowed and between 0 and 100 when negative values are not allowed. * @param toClip the value to clip * @param allowNegative whether negative values are allowed * @return the clipped value */ fun clipToPercent(toClip: Int, allowNegative: Boolean = false) = when { !allowNegative && toClip <= 0 -> 0 toClip <= -100 -> -100 toClip >= 100 -> 100 else -> toClip } } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/message/InAppMessagePresentable.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.message import android.content.Context import android.view.ViewGroup import android.webkit.WebSettings import android.webkit.WebView import androidx.annotation.VisibleForTesting import androidx.compose.ui.platform.ComposeView import com.adobe.marketing.mobile.services.ui.Alert import com.adobe.marketing.mobile.services.ui.InAppMessage import com.adobe.marketing.mobile.services.ui.Presentable import com.adobe.marketing.mobile.services.ui.Presentation import com.adobe.marketing.mobile.services.ui.PresentationDelegate import com.adobe.marketing.mobile.services.ui.PresentationListener import com.adobe.marketing.mobile.services.ui.PresentationUtilityProvider import com.adobe.marketing.mobile.services.ui.common.AEPPresentable import com.adobe.marketing.mobile.services.ui.common.AppLifecycleProvider import com.adobe.marketing.mobile.services.ui.message.views.MessageScreen import kotlinx.coroutines.CoroutineScope import java.nio.charset.StandardCharsets /** * Presentable for InAppMessage visuals. * @param inAppMessage the in-app message that this presentable will be tied to * @param presentationDelegate the presentation delegate to use for lifecycle events * @param presentationUtilityProvider the presentation utility provider to use for the presentable */ internal class InAppMessagePresentable( private val inAppMessage: InAppMessage, private val presentationDelegate: PresentationDelegate?, private val presentationUtilityProvider: PresentationUtilityProvider, appLifecycleProvider: AppLifecycleProvider, mainScope: CoroutineScope ) : AEPPresentable<InAppMessage>( inAppMessage, presentationUtilityProvider, presentationDelegate, appLifecycleProvider, mainScope ) { companion object { private const val LOG_SOURCE = "InAppMessagePresentable" internal const val TEXT_HTML_MIME_TYPE = "text/html" internal const val BASE_URL = "file:///android_asset/" } private val inAppMessageEventHandler: DefaultInAppMessageEventHandler = DefaultInAppMessageEventHandler( scriptHandlers = mutableMapOf(), mainScope = mainScope ) init { // Set the event handler for the in-app message right at creation inAppMessage.eventHandler = inAppMessageEventHandler } private var animationCompleteCallback: (() -> Unit)? = null override fun getPresentation(): InAppMessage { return inAppMessage } /** * Returns the content of the Message presentable i.e MessageScreen as a ComposeView. * @param activityContext the context of the activity */ override fun getContent(activityContext: Context): ComposeView { return ComposeView(activityContext).apply { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) setContent { MessageScreen( presentationStateManager = presentationStateManager, inAppMessageSettings = inAppMessage.settings, onCreated = { applyWebViewSettings(it) // Notify the event handler that there is a new webview ready inAppMessageEventHandler.onNewWebView(webView = it) }, onDisposed = { if (getState() != Presentable.State.DETACHED) { // If the state is not DETACHED, the the presentable will be reattached // again, so don't cleanup return@MessageScreen } animationCompleteCallback?.invoke() animationCompleteCallback = null }, onBackPressed = { inAppMessage.eventListener.onBackPressed(this@InAppMessagePresentable) dismiss() }, onGestureDetected = { gesture -> // The message creation wizard only allows gesture association with message dismissal // So always dismiss the message when a gesture is detected dismiss() // If a gesture mapping exists, the notify the listener about the uri associated with the gesture inAppMessage.settings.gestureMap[gesture]?.let { link -> handleInAppUri(link) } } ) } } } override fun gateDisplay(): Boolean { // InAppMessages require consulting the presentation delegate to determine if they should be displayed return true } override fun awaitExitAnimation(onAnimationComplete: () -> Unit) { animationCompleteCallback = onAnimationComplete // now wait for onDisposed to be called on the composable } override fun hasConflicts(visiblePresentations: List<Presentation<*>>): Boolean { // InAppMessages can be shown if there are no other visible in-app messages or alerts return visiblePresentations.any { (it is InAppMessage || it is Alert) } } /** * Applies the default webview configuration to the webview and attaches an internal webview client for * handling in-app urls. * @param webView the webview to apply the settings to * @return the webview with the settings applied */ private fun applyWebViewSettings(webView: WebView): WebView { webView.settings.apply { // base settings javaScriptEnabled = true allowFileAccess = false domStorageEnabled = true layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL defaultTextEncodingName = StandardCharsets.UTF_8.name() mediaPlaybackRequiresUserGesture = false databaseEnabled = true } webView.apply { // do not enable if gestures have to be handled isVerticalScrollBarEnabled = inAppMessage.settings.gestureMap.isEmpty() isHorizontalScrollBarEnabled = inAppMessage.settings.gestureMap.isEmpty() isScrollbarFadingEnabled = true scrollBarStyle = WebView.SCROLLBARS_INSIDE_OVERLAY setBackgroundColor(0) } webView.webViewClient = createWebViewClient() return webView } private fun createWebViewClient(): InAppMessageWebViewClient { return InAppMessageWebViewClient( inAppMessage.settings, presentationUtilityProvider ) { url -> handleInAppUri(url) } } /** * Handles the in-app uri. Does so by first checking if the component that created this message * is able to handle the uri. * @param uri the uri to handle * @return true if the url was handled internally by the web-view client, false otherwise */ @VisibleForTesting internal fun handleInAppUri(uri: String): Boolean { // First check if the component that created this message is able to handle the uri. // Otherwise check if this URI can be opened by the utility provider via UriOpening service val handled = inAppMessage.eventListener.onUrlLoading(this@InAppMessagePresentable, uri) || presentationUtilityProvider.openUri(uri) // Notify the presentation delegate only if the url was handled if (handled) { presentationDelegate?.onContentLoaded( this@InAppMessagePresentable, PresentationListener.PresentationContent.UrlContent(uri) ) } return handled } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/message/InAppMessageEventHandler.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.message import com.adobe.marketing.mobile.AdobeCallback /** * Interface for take actions on an InAppMessage presentation. */ interface InAppMessageEventHandler { /** * Registers a {@link JavascriptInterface} for the provided handler name to the {@link WebView} * associated with the InAppMessage presentation to handle Javascript messages. When the registered * handlers are executed via the HTML the result will be passed back to the associated [callback]. * @param handlerName the name of the handler to register * @param callback the callback to be invoked with the result of the javascript execution */ fun handleJavascriptMessage(handlerName: String, callback: AdobeCallback<String>) /** * Evaluates the provided javascript content in the {@link WebView} maintained by the InAppMessage * and passes the result to the provided [callback]. * @param jsContent the javascript content to be executed * @param callback the callback to be invoked with the result of the javascript execution */ fun evaluateJavascript(jsContent: String, callback: AdobeCallback<String>) }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/message/InAppMessageEventListener.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.message import com.adobe.marketing.mobile.services.ui.InAppMessage import com.adobe.marketing.mobile.services.ui.Presentable import com.adobe.marketing.mobile.services.ui.PresentationEventListener /** * Interface for listening to events related to an InAppMessage presentation. * @see PresentationEventListener */ interface InAppMessageEventListener : PresentationEventListener<InAppMessage> { /** * Invoked when the back button is pressed via a button or a gesture while * the InAppMessage is being presented. */ fun onBackPressed(message: Presentable<InAppMessage>) /** * Invoked when a url is about to be loaded into the InAppMessage WebView. * @param message the InAppMessage that is being presented * @param url the url that is about to be loaded * @return true if the url will be handled, false otherwise */ fun onUrlLoading(message: Presentable<InAppMessage>, url: String): Boolean }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/message/mapping/MessageAlignmentMapper.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.message.mapping import androidx.compose.ui.Alignment import com.adobe.marketing.mobile.services.ui.message.InAppMessageSettings /** * Utility class that maps the [InAppMessageSettings.MessageAlignment] to Compose [Alignment] */ internal object MessageAlignmentMapper { /** * Mapping between [InAppMessageSettings.MessageAlignment] to [Alignment.Vertical] */ private val verticalAlignmentMap: Map<InAppMessageSettings.MessageAlignment, Alignment.Vertical> = mapOf( InAppMessageSettings.MessageAlignment.TOP to Alignment.Top, InAppMessageSettings.MessageAlignment.BOTTOM to Alignment.Bottom, InAppMessageSettings.MessageAlignment.CENTER to Alignment.CenterVertically // Vertical alignment is not supported for LEFT and RIGHT ) /** * Mapping between [InAppMessageSettings.MessageAlignment] to [Alignment.Horizontal] */ private val horizontalAlignmentMap: Map<InAppMessageSettings.MessageAlignment, Alignment.Horizontal> = mapOf( InAppMessageSettings.MessageAlignment.LEFT to Alignment.Start, InAppMessageSettings.MessageAlignment.RIGHT to Alignment.End, InAppMessageSettings.MessageAlignment.CENTER to Alignment.CenterHorizontally // Horizontal alignment is not supported for TOP and BOTTOM ) /** * Returns the [Alignment.Vertical] for the given [InAppMessageSettings.MessageAlignment] * @param alignment [InAppMessageSettings.MessageAlignment] whose vertical alignment is needed * @return [Alignment.Vertical] for the given [InAppMessageSettings.MessageAlignment] */ internal fun getVerticalAlignment(alignment: InAppMessageSettings.MessageAlignment): Alignment.Vertical { return verticalAlignmentMap[alignment] ?: Alignment.CenterVertically } /** * Returns the [Alignment.Horizontal] for the given [InAppMessageSettings.MessageAlignment] * @param alignment [InAppMessageSettings.MessageAlignment] whose horizontal alignment is needed * @return [Alignment.Horizontal] for the given [InAppMessageSettings.MessageAlignment] */ internal fun getHorizontalAlignment(alignment: InAppMessageSettings.MessageAlignment): Alignment.Horizontal { return horizontalAlignmentMap[alignment] ?: Alignment.CenterHorizontally } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/message/mapping/MessageAnimationMapper.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.message.mapping import androidx.compose.animation.EnterTransition import androidx.compose.animation.ExitTransition import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutHorizontally import androidx.compose.animation.slideOutVertically import com.adobe.marketing.mobile.services.ui.message.InAppMessageSettings /** * Mapper class to map [InAppMessageSettings.MessageAnimation] to a Compose [EnterTransition] and [ExitTransition] */ internal object MessageAnimationMapper { private const val DEFAULT_ANIMATION_DURATION_MS = 300 /** * Map of [InAppMessageSettings.MessageAnimation] to [EnterTransition]` */ private val enterAnimationMap: Map<InAppMessageSettings.MessageAnimation, EnterTransition> = mapOf( InAppMessageSettings.MessageAnimation.LEFT to slideInHorizontally( initialOffsetX = { -it }, animationSpec = tween(DEFAULT_ANIMATION_DURATION_MS) ), InAppMessageSettings.MessageAnimation.RIGHT to slideInHorizontally( initialOffsetX = { it }, animationSpec = tween(DEFAULT_ANIMATION_DURATION_MS) ), InAppMessageSettings.MessageAnimation.TOP to slideInVertically( initialOffsetY = { -it }, animationSpec = tween(DEFAULT_ANIMATION_DURATION_MS) ), InAppMessageSettings.MessageAnimation.BOTTOM to slideInVertically( initialOffsetY = { it }, animationSpec = tween(DEFAULT_ANIMATION_DURATION_MS) ), InAppMessageSettings.MessageAnimation.FADE to fadeIn( animationSpec = tween(DEFAULT_ANIMATION_DURATION_MS) ) ) /** * Map of [InAppMessageSettings.MessageAnimation] to [ExitTransition] */ private val exitAnimationMap: Map<InAppMessageSettings.MessageAnimation, ExitTransition> = mapOf( InAppMessageSettings.MessageAnimation.LEFT to slideOutHorizontally( animationSpec = tween(DEFAULT_ANIMATION_DURATION_MS), targetOffsetX = { -it } ), InAppMessageSettings.MessageAnimation.RIGHT to slideOutHorizontally( animationSpec = tween(DEFAULT_ANIMATION_DURATION_MS), targetOffsetX = { it } ), InAppMessageSettings.MessageAnimation.TOP to slideOutVertically( animationSpec = tween(DEFAULT_ANIMATION_DURATION_MS), targetOffsetY = { -it } ), InAppMessageSettings.MessageAnimation.BOTTOM to slideOutVertically( animationSpec = tween(DEFAULT_ANIMATION_DURATION_MS), targetOffsetY = { it } ), InAppMessageSettings.MessageAnimation.FADE to fadeOut( animationSpec = tween(DEFAULT_ANIMATION_DURATION_MS) ) ) private val gestureAnimationMap: Map<InAppMessageSettings.MessageGesture, ExitTransition> = mapOf( InAppMessageSettings.MessageGesture.SWIPE_UP to slideOutVertically( animationSpec = tween(DEFAULT_ANIMATION_DURATION_MS), targetOffsetY = { -it } ), InAppMessageSettings.MessageGesture.SWIPE_DOWN to slideOutVertically( animationSpec = tween(DEFAULT_ANIMATION_DURATION_MS), targetOffsetY = { it } ), InAppMessageSettings.MessageGesture.SWIPE_LEFT to slideOutHorizontally( animationSpec = tween(DEFAULT_ANIMATION_DURATION_MS), targetOffsetX = { -it } ), InAppMessageSettings.MessageGesture.SWIPE_RIGHT to slideOutHorizontally( animationSpec = tween(DEFAULT_ANIMATION_DURATION_MS), targetOffsetX = { it } ), InAppMessageSettings.MessageGesture.TAP_BACKGROUND to fadeOut( animationSpec = tween(DEFAULT_ANIMATION_DURATION_MS) ) ) /** * Get the [EnterTransition] for the given [InAppMessageSettings.MessageAnimation] */ fun getEnterTransitionFor(animation: InAppMessageSettings.MessageAnimation): EnterTransition = enterAnimationMap[animation] ?: EnterTransition.None /** * Get the [ExitTransition] for the given [InAppMessageSettings.MessageAnimation] */ fun getExitTransitionFor(animation: InAppMessageSettings.MessageAnimation): ExitTransition = exitAnimationMap[animation] ?: ExitTransition.None fun getExitTransitionFor(gesture: InAppMessageSettings.MessageGesture): ExitTransition = gestureAnimationMap[gesture] ?: ExitTransition.None }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/message/mapping/MessageOffsetMapper.kt
/* Copyright 2024 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.message.mapping import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.adobe.marketing.mobile.services.ui.message.InAppMessageSettings /** * A mapper to calculate the horizontal and vertical offset for the InAppMessage based * on the alignment and offset percent. */ internal object MessageOffsetMapper { /** * Returns the horizontal offset for the InAppMessage based on the alignment and offset percent * relative to the screen width. * * LEFT alignment with +ve offset will move the message to the right. * LEFT alignment with -ve offset will move the message to the left. * RIGHT alignment with +ve offset will move the message to the left. * RIGHT alignment with -ve offset will move the message to the right. * * @param horizontalAlignment the horizontal alignment of the message * @param offsetPercent the offset percent of the message * @param screenWidthDp the screen width in dp * @return the horizontal offset in dp */ internal fun getHorizontalOffset( horizontalAlignment: InAppMessageSettings.MessageAlignment, offsetPercent: Int, screenWidthDp: Dp ): Dp { val offset = ((offsetPercent * screenWidthDp.value) / 100).dp return when (horizontalAlignment) { InAppMessageSettings.MessageAlignment.LEFT -> offset InAppMessageSettings.MessageAlignment.RIGHT -> -offset InAppMessageSettings.MessageAlignment.CENTER -> 0.dp else -> 0.dp } } /** * Returns the vertical offset for the InAppMessage based on the alignment and offset percent * relative to the screen height. * * TOP alignment with +ve offset will move the message down. * TOP alignment with -ve offset will move the message up. * BOTTOM alignment with +ve offset will move the message up. * BOTTOM alignment with -ve offset will move the message down. * * @param verticalAlignment the vertical alignment of the message * @param offsetPercent the offset percent of the message * @param screenHeightDp the screen height in dp * @return the vertical offset in dp */ internal fun getVerticalOffset( verticalAlignment: InAppMessageSettings.MessageAlignment, offsetPercent: Int, screenHeightDp: Dp ): Dp { val offset = ((offsetPercent * screenHeightDp.value) / 100).dp return when (verticalAlignment) { InAppMessageSettings.MessageAlignment.TOP -> offset InAppMessageSettings.MessageAlignment.BOTTOM -> -offset InAppMessageSettings.MessageAlignment.CENTER -> 0.dp else -> 0.dp } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/message/mapping/MessageArrangementMapper.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.message.mapping import androidx.compose.foundation.layout.Arrangement import com.adobe.marketing.mobile.services.ui.message.InAppMessageSettings /** * Maps the [InAppMessageSettings.MessageAlignment] to a compose [Arrangement.Horizontal] and [Arrangement.Vertical] arrangement */ internal object MessageArrangementMapper { /** * Maps the [InAppMessageSettings.MessageAlignment] to compose [Arrangement.Horizontal] arrangement */ private val horizontalArrangementMap: Map<InAppMessageSettings.MessageAlignment, Arrangement.Horizontal> = mapOf( InAppMessageSettings.MessageAlignment.LEFT to Arrangement.Start, InAppMessageSettings.MessageAlignment.RIGHT to Arrangement.End, InAppMessageSettings.MessageAlignment.CENTER to Arrangement.Center // Horizontal alignment is not supported for TOP and BOTTOM ) /** * Maps the [InAppMessageSettings.MessageAlignment] to compose [Arrangement.Vertical] arrangement */ private val verticalArrangementMap: Map<InAppMessageSettings.MessageAlignment, Arrangement.Vertical> = mapOf( InAppMessageSettings.MessageAlignment.TOP to Arrangement.Top, InAppMessageSettings.MessageAlignment.BOTTOM to Arrangement.Bottom, InAppMessageSettings.MessageAlignment.CENTER to Arrangement.Center // Vertical alignment is not supported for LEFT and RIGHT ) /** * Returns the compose [Arrangement.Horizontal] arrangement for the given [InAppMessageSettings.MessageAlignment] * @param alignment the [InAppMessageSettings.MessageAlignment] whose compose [Arrangement.Horizontal] arrangement is needed * @return the compose [Arrangement.Horizontal] arrangement for the given [InAppMessageSettings.MessageAlignment] */ internal fun getHorizontalArrangement(alignment: InAppMessageSettings.MessageAlignment): Arrangement.Horizontal { return horizontalArrangementMap[alignment] ?: Arrangement.Center } /** * Returns the compose [Arrangement.Vertical] arrangement for the given [InAppMessageSettings.MessageAlignment] * @param alignment the [InAppMessageSettings.MessageAlignment] whose compose [Arrangement.Vertical] arrangement is needed * @return the compose [Arrangement.Vertical] arrangement for the given [InAppMessageSettings.MessageAlignment] */ internal fun getVerticalArrangement(alignment: InAppMessageSettings.MessageAlignment): Arrangement.Vertical { return verticalArrangementMap[alignment] ?: Arrangement.Center } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/message/views/MessageTestTags.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.message.views /** * Test tags for message views */ internal object MessageTestTags { const val MESSAGE_BACKDROP = "messageBackdrop" const val MESSAGE_FRAME = "messageFrame" const val MESSAGE_CONTENT = "messageContent" }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/message/views/MessageFrame.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.message.views import android.app.Activity import android.content.Context import android.content.ContextWrapper import android.os.Build import android.view.View import android.webkit.WebView import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.MutableTransitionState import androidx.compose.foundation.background import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.draggable import androidx.compose.foundation.gestures.rememberDraggableState import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Card import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.onPlaced import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.testTag import androidx.compose.ui.unit.dp import com.adobe.marketing.mobile.services.Log import com.adobe.marketing.mobile.services.ServiceConstants import com.adobe.marketing.mobile.services.ui.message.GestureTracker import com.adobe.marketing.mobile.services.ui.message.InAppMessageSettings import com.adobe.marketing.mobile.services.ui.message.mapping.MessageAlignmentMapper import com.adobe.marketing.mobile.services.ui.message.mapping.MessageAnimationMapper import com.adobe.marketing.mobile.services.ui.message.mapping.MessageArrangementMapper import com.adobe.marketing.mobile.services.ui.message.mapping.MessageOffsetMapper /** * Represents the frame of the InAppMessage that contains the content of the message. * Manages the animations associated with the message, and message arrangement/alignment on the screen. * @param visibility the visibility of the message * @param inAppMessageSettings the settings of the message * @param gestureTracker the gesture tracker of the message * @param onCreated the callback to be invoked when the message is created */ @Composable internal fun MessageFrame( visibility: MutableTransitionState<Boolean>, inAppMessageSettings: InAppMessageSettings, gestureTracker: GestureTracker, onCreated: (WebView) -> Unit, onDisposed: () -> Unit ) { // The current context is the activity that is hosting the message. We can safely cast it to // an Activity because this composable is always used within the context of the activity in // the current implementation of UIService val currentActivity = LocalContext.current.findActivity() ?: run { onDisposed() Log.debug(ServiceConstants.LOG_TAG, "MessageFrame", "Unable to get the current activity. Dismissing the message.") return } // We want to calculate the height and width of the message based on the host activity's // content view. This is because the message is displayed on top of the content view and // we want to ensure that the message is displayed relative to the activity's size. // This allows the message to be displayed correctly in split screen mode and other // multi-window modes. val density = LocalDensity.current val contentView = currentActivity.findViewById<View>(android.R.id.content) val contentHeightDp = with(density) { contentView.height.toDp() } val contentWidthDp = with(density) { contentView.width.toDp() } val heightDp = remember { mutableStateOf(((contentHeightDp * inAppMessageSettings.height) / 100)) } val widthDp = remember { mutableStateOf(((contentWidthDp * inAppMessageSettings.width) / 100)) } val horizontalOffset = MessageOffsetMapper.getHorizontalOffset( inAppMessageSettings.horizontalAlignment, inAppMessageSettings.horizontalInset, widthDp.value ) val verticalOffset = MessageOffsetMapper.getVerticalOffset( inAppMessageSettings.verticalAlignment, inAppMessageSettings.verticalInset, heightDp.value ) val allowGestures = remember { inAppMessageSettings.gestureMap.isNotEmpty() } val offsetX = remember { mutableStateOf(0f) } val offsetY = remember { mutableStateOf(0f) } val dragVelocity = remember { mutableStateOf(0f) } val adjustAlphaForClipping = remember { Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1 } AnimatedVisibility( visibleState = visibility, enter = MessageAnimationMapper.getEnterTransitionFor(inAppMessageSettings.displayAnimation), // Use a combination of the exit transition and the most recent gesture to animate the message out of the screen // This allows animating out in the direction of the gesture as opposed to the default exit animation always exit = gestureTracker.getExitTransition() ) { Row( modifier = Modifier .fillMaxSize() .onPlaced { heightDp.value = with(density) { ((contentView.height.toDp() * inAppMessageSettings.height) / 100) } widthDp.value = with(density) { ((contentView.width.toDp() * inAppMessageSettings.width) / 100) } } .offset(x = horizontalOffset, y = verticalOffset) .background(Color.Transparent) .testTag(MessageTestTags.MESSAGE_FRAME), horizontalArrangement = MessageArrangementMapper.getHorizontalArrangement( inAppMessageSettings.horizontalAlignment ), verticalAlignment = MessageAlignmentMapper.getVerticalAlignment(inAppMessageSettings.verticalAlignment) ) { // The content of the InAppMessage. Card( backgroundColor = Color.Transparent, elevation = 0.dp, // Ensure that the card does not cast a shadow modifier = Modifier .clip(RoundedCornerShape(inAppMessageSettings.cornerRadius.dp)) .let { // Needs .99 alpha to ensure that the WebView message is clipped to // the rounded corners for API versions 22 and below. if (adjustAlphaForClipping) it.alpha(0.99f) else it } .draggable( enabled = allowGestures, state = rememberDraggableState { delta -> offsetX.value += delta }, orientation = Orientation.Horizontal, onDragStopped = { velocity -> gestureTracker.onDragFinished( offsetX.value, offsetY.value, velocity ) dragVelocity.value = 0f offsetY.value = 0f offsetX.value = 0f } ) .draggable( enabled = allowGestures, state = rememberDraggableState { delta -> offsetY.value += delta }, orientation = Orientation.Vertical, onDragStopped = { velocity -> gestureTracker.onDragFinished( offsetX.value, offsetY.value, velocity ) dragVelocity.value = 0f offsetY.value = 0f offsetX.value = 0f } ) ) { MessageContent(Modifier.height(heightDp.value).width(widthDp.value), inAppMessageSettings, onCreated) } // This is a one-time effect that will be called when this composable is completely removed from the composition // (after any animations if any). Use this to clean up any resources that were created in onCreated. DisposableEffect(Unit) { onDispose { onDisposed() } } } } } /** * An extension for finding the activity from a context. */ private fun Context.findActivity(): Activity? { var context = this while (context is ContextWrapper) { if (context is Activity) return context context = context.baseContext } return null }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/message/views/Message.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.message.views import android.webkit.WebView import androidx.activity.compose.BackHandler import androidx.compose.animation.core.MutableTransitionState import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalView import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties import androidx.compose.ui.window.DialogWindowProvider import com.adobe.marketing.mobile.services.ui.Presentable import com.adobe.marketing.mobile.services.ui.common.PresentationStateManager import com.adobe.marketing.mobile.services.ui.message.GestureTracker import com.adobe.marketing.mobile.services.ui.message.InAppMessageSettings import com.adobe.marketing.mobile.services.ui.message.mapping.MessageAnimationMapper /** * Represents the InAppMessage screen. Composes a Message and a BackHandler. This component is primarily responsible * for hosting the overall InAppMessage and provides notifications about the creation, disposal, handling * the back buttons and gestures. * @param presentationStateManager [PresentationStateManager] to manage the presentation of the InAppMessage * @param inAppMessageSettings [InAppMessageSettings] for the InAppMessage * @param onCreated callback invoked when the [WebView] that holds the message content is created * @param onDisposed callback invoked when the composable that holds message content is disposed. This signifies the completion * exit animations * @param onBackPressed callback invoked when the back button is pressed while the message is visible * @param onGestureDetected callback invoked when a gesture is detected on the message */ @Composable internal fun MessageScreen( presentationStateManager: PresentationStateManager, inAppMessageSettings: InAppMessageSettings, onCreated: (WebView) -> Unit, onDisposed: () -> Unit, onBackPressed: () -> Unit, onGestureDetected: (InAppMessageSettings.MessageGesture) -> Unit ) { // A gesture tracker to be injected into all subcomponents for identifying and // propagating gestures val gestureTracker: GestureTracker = remember { GestureTracker( defaultExitTransition = MessageAnimationMapper.getExitTransitionFor( inAppMessageSettings.dismissAnimation ), acceptedGestures = inAppMessageSettings.gestureMap.keys ) { onGestureDetected(it) } } // BackHandler conditionally handles the back press event based on the visibility of the message BackHandler(enabled = presentationStateManager.presentableState.value == Presentable.State.VISIBLE) { onBackPressed() } Message( isVisible = presentationStateManager.visibilityState, inAppMessageSettings = inAppMessageSettings, gestureTracker = gestureTracker, onCreated = { onCreated(it) }, onDisposed = { onDisposed() }, onBackPressed = onBackPressed ) } /** * Represents an InAppMessage view. Composes an optional MessageBackdrop and MessageFrame. * @param isVisible transition state of the visibility of the InAppMessage * @param inAppMessageSettings [InAppMessageSettings] for the InAppMessage * @param gestureTracker * @param onCreated callback invoked when the [WebView] that holds the message content is created * @param onDisposed callback invoked when the composable that holds message content is disposed */ @Composable internal fun Message( isVisible: MutableTransitionState<Boolean>, inAppMessageSettings: InAppMessageSettings, gestureTracker: GestureTracker, onCreated: (WebView) -> Unit, onDisposed: () -> Unit, onBackPressed: () -> Unit ) { if (inAppMessageSettings.shouldTakeOverUi) { /* Dialog is used to take over the UI when the InAppMessage is set to take over the UI. This is necessary to ensure that the InAppMessage is displayed on top of the UI. Which will ensure that ScreenReader can read the content of the InAppMessage only and not the underlying UI. */ Dialog( properties = DialogProperties( usePlatformDefaultWidth = false, dismissOnBackPress = true, dismissOnClickOutside = false ), onDismissRequest = { onBackPressed() } ) { /* Remove the default dim and animations for the dialog window Customer can set their own dim and animations if needed and those will be honoured in MessageBackdrop inside Message */ val dialogWindow = (LocalView.current.parent as? DialogWindowProvider)?.window SideEffect { dialogWindow?.let { it.setDimAmount(0f) it.setWindowAnimations(-1) } } // Backdrop for the InAppMessage only takes into effect if the InAppMessage is taking over the UI MessageBackdrop( visibility = isVisible, inAppMessageSettings = inAppMessageSettings, gestureTracker = gestureTracker ) // Frame that holds the InAppMessage MessageFrame( visibility = isVisible, inAppMessageSettings = inAppMessageSettings, gestureTracker = gestureTracker, onCreated = onCreated, onDisposed = onDisposed ) } } else { // Frame that holds the InAppMessage MessageFrame( visibility = isVisible, inAppMessageSettings = inAppMessageSettings, gestureTracker = gestureTracker, onCreated = onCreated, onDisposed = onDisposed ) } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/message/views/MessageBackdrop.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.message.views import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.MutableTransitionState import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag import androidx.core.graphics.toColorInt import com.adobe.marketing.mobile.services.ui.message.GestureTracker import com.adobe.marketing.mobile.services.ui.message.InAppMessageSettings /** * A composable representing the backdrop for the InAppMessage. * @param visibility the visibility state of the backdrop * @param inAppMessageSettings the settings for the InAppMessage */ @Composable internal fun MessageBackdrop( visibility: MutableTransitionState<Boolean>, inAppMessageSettings: InAppMessageSettings, gestureTracker: GestureTracker ) { val backdropColor = remember { Color(inAppMessageSettings.backdropColor.toColorInt()) } // Note that the background enter and exit animations are simple fades. Primarily used to ease in and out the backdrop // separate from the message itself. This allows smoother visuals and reduces flicker in the animation. AnimatedVisibility(visibleState = visibility, enter = fadeIn(), exit = fadeOut()) { Box( modifier = Modifier .fillMaxSize() .background(backdropColor.copy(alpha = inAppMessageSettings.backdropOpacity)) .clickable( enabled = true, indication = null, interactionSource = remember { MutableInteractionSource() }, onClick = { gestureTracker.onGesture(InAppMessageSettings.MessageGesture.TAP_BACKGROUND) } ) .testTag(MessageTestTags.MESSAGE_BACKDROP) ) } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/message/views/MessageContent.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.message.views import android.view.ViewGroup import android.webkit.WebView import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.platform.testTag import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import com.adobe.marketing.mobile.services.Log import com.adobe.marketing.mobile.services.ServiceConstants import com.adobe.marketing.mobile.services.ui.message.InAppMessagePresentable import com.adobe.marketing.mobile.services.ui.message.InAppMessageSettings import java.nio.charset.StandardCharsets /** * Represents the content of the InAppMessage. Holds a WebView that loads the HTML content of the message * @param modifier [Modifier] to apply to the content (AndroidView holding the WebView) * @param inAppMessageSettings [InAppMessageSettings] settings for the InAppMessage * @param onCreated callback to be invoked when the WenView that this composable holds is created */ @Composable internal fun MessageContent( modifier: Modifier, inAppMessageSettings: InAppMessageSettings, onCreated: (WebView) -> Unit ) { AndroidView( factory = { WebView(it).apply { Log.debug( ServiceConstants.LOG_TAG, "MessageContent", "Creating MessageContent" ) // Needed to force the HTML to be rendered within bounds of the AndroidView // allowing HTML content with "overflow" css to work properly layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) // call on created before loading the content. This is to ensure that the webview script // handlers and interfaces are ready to be used onCreated(this) loadDataWithBaseURL( InAppMessagePresentable.BASE_URL, inAppMessageSettings.content, InAppMessagePresentable.TEXT_HTML_MIME_TYPE, StandardCharsets.UTF_8.name(), null ) } }, modifier = modifier .clip(RoundedCornerShape(inAppMessageSettings.cornerRadius.dp)) .testTag(MessageTestTags.MESSAGE_CONTENT) ) }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/common/PresentationStateManager.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.common import androidx.compose.animation.core.MutableTransitionState import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import com.adobe.marketing.mobile.services.ui.Presentable /** * A state manager that tracks the visibility state of the presentable. */ internal class PresentationStateManager { private val _presentableState = mutableStateOf(Presentable.State.DETACHED) val presentableState: State<Presentable.State> = _presentableState val visibilityState = MutableTransitionState(false) /** * Transition the presentable state to [Presentable.State.VISIBLE] and set the visibility state to true. * This is to be called to trigger the presentable to show itself. */ fun onShown() { _presentableState.value = Presentable.State.VISIBLE visibilityState.targetState = true } /** * Transition the presentable state to [Presentable.State.HIDDEN] and set the visibility state to false. * This is to be called to trigger the presentable to hide itself. */ fun onHidden() { _presentableState.value = Presentable.State.HIDDEN visibilityState.targetState = false } /** * Transition the presentable state to [Presentable.State.DETACHED] and set the visibility state to false. * This is to be called to trigger the presentable to detach itself. */ fun onDetached() { _presentableState.value = Presentable.State.DETACHED visibilityState.targetState = false } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/common/AppLifecycleProvider.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.common import android.app.Activity import android.app.Application import android.os.Bundle import androidx.annotation.VisibleForTesting import com.adobe.marketing.mobile.services.ui.Presentable /** * A singleton class that provides [Presentable]s a way to register for app lifecycle events. * This is primarily used [Presentable]s to know when to show or hide themselves in response to * configuration changes. */ internal class AppLifecycleProvider private constructor() { internal interface AppLifecycleListener { fun onActivityResumed(activity: Activity) fun onActivityDestroyed(activity: Activity) } companion object { val INSTANCE by lazy { AppLifecycleProvider() } } private val listeners: MutableSet<AppLifecycleListener> = mutableSetOf() private var started = false /** * Starts the [AppLifecycleProvider] by registering an [InternalAppLifecycleListener] with the * [app] to receive app lifecycle events. * @param app the [Application] to register the [InternalAppLifecycleListener] with */ @Synchronized internal fun start(app: Application) { if (started) { return } started = true app.registerActivityLifecycleCallbacks(InternalAppLifecycleListener(this)) } /** * Registers a [listener] to receive app lifecycle events. * @param listener the [AppLifecycleListener] to register */ @Synchronized internal fun registerListener(listener: AppLifecycleListener) { listeners.add(listener) } /** * Unregisters a [listener] from receiving app lifecycle events. * @param listener the [AppLifecycleListener] to unregister */ @Synchronized internal fun unregisterListener(listener: AppLifecycleListener) { listeners.remove(listener) } /** TESTS ONLY **/ @VisibleForTesting internal fun stop(app: Application) { if (!started) { return } started = false app.unregisterActivityLifecycleCallbacks(InternalAppLifecycleListener(this)) } /** * Internal implementation of [Application.ActivityLifecycleCallbacks] that forwards * lifecycle events to [AppLifecycleProvider.AppLifecycleListener]. Allows registering a single Application.ActivityLifecycleCallback * with the Application instead of one per [Presentable]. */ private class InternalAppLifecycleListener(private val appLifecycleProvider: AppLifecycleProvider) : Application.ActivityLifecycleCallbacks { override fun onActivityResumed(activity: Activity) { appLifecycleProvider.listeners.forEach { listener -> listener.onActivityResumed(activity) } } override fun onActivityDestroyed(activity: Activity) { appLifecycleProvider.listeners.forEach { listener -> listener.onActivityDestroyed( activity ) } } // No op methods override fun onActivityStarted(activity: Activity) {} override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {} override fun onActivityPaused(activity: Activity) {} override fun onActivityStopped(activity: Activity) {} override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {} } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/ui/common/AEPPresentable.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.common import android.app.Activity import android.content.Context import android.view.View import android.view.ViewGroup import androidx.annotation.MainThread import androidx.annotation.VisibleForTesting import androidx.compose.ui.platform.ComposeView import com.adobe.marketing.mobile.internal.util.ActivityCompatOwnerUtils import com.adobe.marketing.mobile.services.Log import com.adobe.marketing.mobile.services.ServiceConstants import com.adobe.marketing.mobile.services.ui.AlreadyDismissed import com.adobe.marketing.mobile.services.ui.AlreadyHidden import com.adobe.marketing.mobile.services.ui.AlreadyShown import com.adobe.marketing.mobile.services.ui.ConflictingPresentation import com.adobe.marketing.mobile.services.ui.NoActivityToDetachFrom import com.adobe.marketing.mobile.services.ui.NoAttachableActivity import com.adobe.marketing.mobile.services.ui.Presentable import com.adobe.marketing.mobile.services.ui.Presentation import com.adobe.marketing.mobile.services.ui.PresentationDelegate import com.adobe.marketing.mobile.services.ui.PresentationUtilityProvider import com.adobe.marketing.mobile.services.ui.SuppressedByAppDeveloper import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import java.lang.ref.WeakReference import java.util.Random /** * Base implementation of [Presentable] interface. Abstracts the common functionality needed by all presentables * for their lifecycle and listener management. */ internal abstract class AEPPresentable<T : Presentation<T>> : Presentable<T>, AppLifecycleProvider.AppLifecycleListener { companion object { private const val LOG_SOURCE = "AEPPresentable" } private val presentation: Presentation<T> private val presentationUtilityProvider: PresentationUtilityProvider private val presentationDelegate: PresentationDelegate? private val appLifecycleProvider: AppLifecycleProvider private val presentationObserver: PresentationObserver private val activityCompatOwnerUtils: ActivityCompatOwnerUtils private val mainScope: CoroutineScope protected val presentationStateManager: PresentationStateManager @VisibleForTesting internal val contentIdentifier: Int = Random().nextInt() /** * Represents the activity to which the presentable is currently attached. * This SHOULD always be updated whenever the presentable is attached or detached from an * activity. For the sake of maintainability, modify this only in [attach] and [detach] and * limit queries to this field in activity lifecycle methods. */ private var attachmentHandle: WeakReference<Activity?> = WeakReference(null) /** * @param presentation the [Presentation] to be used by this [Presentable] * @param presentationUtilityProvider the [PresentationUtilityProvider] to be used to fetch components needed by this [Presentable] * @param presentationDelegate the [PresentationDelegate] for notifying the application of [Presentation] lifecycle events * @param appLifecycleProvider the [AppLifecycleProvider] to be used to register for app lifecycle events */ constructor( presentation: Presentation<T>, presentationUtilityProvider: PresentationUtilityProvider, presentationDelegate: PresentationDelegate?, appLifecycleProvider: AppLifecycleProvider, mainScope: CoroutineScope ) : this( presentation, presentationUtilityProvider, presentationDelegate, appLifecycleProvider, PresentationStateManager(), ActivityCompatOwnerUtils(), mainScope, PresentationObserver.INSTANCE ) /** * @param presentation the [Presentation] to be used by this [Presentable] * @param presentationUtilityProvider the [PresentationUtilityProvider] to be used to fetch components needed by this [Presentable] * @param presentationDelegate the [PresentationDelegate] for notifying the application of [Presentation] lifecycle events * @param appLifecycleProvider the [AppLifecycleProvider] to be used to register for app lifecycle events * @param presentationStateManager the [PresentationStateManager] to be used to manage the state of this [Presentable] * @param mainScope the [CoroutineScope] to be used to launch coroutines on the main thread */ @VisibleForTesting internal constructor( presentation: Presentation<T>, presentationUtilityProvider: PresentationUtilityProvider, presentationDelegate: PresentationDelegate?, appLifecycleProvider: AppLifecycleProvider, presentationStateManager: PresentationStateManager, activityCompatOwnerUtils: ActivityCompatOwnerUtils, mainScope: CoroutineScope, presentationObserver: PresentationObserver ) { this.presentation = presentation this.presentationUtilityProvider = presentationUtilityProvider this.presentationDelegate = presentationDelegate this.appLifecycleProvider = appLifecycleProvider this.presentationStateManager = presentationStateManager this.activityCompatOwnerUtils = activityCompatOwnerUtils this.mainScope = mainScope this.presentationObserver = presentationObserver } override fun show() { mainScope.launch { val currentState = getState() if (currentState == Presentable.State.VISIBLE) { Log.debug( ServiceConstants.LOG_TAG, LOG_SOURCE, "Presentable is already shown. Ignoring show request." ) presentation.listener.onError(this@AEPPresentable, AlreadyShown) return@launch } val currentActivity: Activity? = presentationUtilityProvider.getCurrentActivity() if (currentActivity == null) { Log.debug( ServiceConstants.LOG_TAG, LOG_SOURCE, "Current activity is null. Cannot show presentable." ) presentation.listener.onError(this@AEPPresentable, NoAttachableActivity) return@launch } val hasConflicts = hasConflicts(presentationObserver.getVisiblePresentations()) if (hasConflicts) { Log.debug( ServiceConstants.LOG_TAG, LOG_SOURCE, "Presentable has conflicts with other visible presentations. Ignoring show request." ) presentation.listener.onError(this@AEPPresentable, ConflictingPresentation) return@launch } // If all basic conditions are met, check with the delegate if the presentable can be shown if (gateDisplay()) { val canShow = (presentationDelegate?.canShow(this@AEPPresentable) ?: true) if (!canShow) { Log.debug(ServiceConstants.LOG_TAG, LOG_SOURCE, "Presentable couldn't be displayed, PresentationDelegate#canShow states the presentable should not be displayed.") presentation.listener.onError(this@AEPPresentable, SuppressedByAppDeveloper) return@launch } } // Show the presentable on the current activity show(currentActivity) // Register for app lifecycle events. AppLifecycleProvider maintains a set of listeners, so // registering multiple times is safe appLifecycleProvider.registerListener(this@AEPPresentable) // At this point show(currentActivity) would have attached the view if one existed, or just bailed out // if the view already a part of the view hierarchy. In either case, notify the listeners and // delegate about the presentable being shown presentation.listener.onShow(this@AEPPresentable) presentationDelegate?.onShow(this@AEPPresentable) presentationObserver.onPresentationVisible(getPresentation()) } } override fun dismiss() { mainScope.launch { // unregister for app lifecycle events appLifecycleProvider.unregisterListener(this@AEPPresentable) if (getState() == Presentable.State.DETACHED) { Log.debug( ServiceConstants.LOG_TAG, LOG_SOURCE, "Presentable is already detached. Ignoring dismiss request." ) presentation.listener.onError(this@AEPPresentable, AlreadyDismissed) return@launch } val currentActivity: Activity? = presentationUtilityProvider.getCurrentActivity() if (currentActivity == null) { Log.debug( ServiceConstants.LOG_TAG, LOG_SOURCE, "Current activity is null. Cannot dismiss presentable." ) presentation.listener.onError(this@AEPPresentable, NoActivityToDetachFrom) return@launch } // Remove the presentable from the current activity. dismiss(currentActivity) // At this point dismiss(currentActivity) would have detached the view if one existed, or just bailed out // if the view was never a part of the view hierarchy. In either case, notify the listeners and // delegate about the presentable being dismissed presentation.listener.onDismiss(this@AEPPresentable) presentationDelegate?.onDismiss(this@AEPPresentable) presentationObserver.onPresentationInvisible(getPresentation()) } } override fun hide() { mainScope.launch { if (getState() != Presentable.State.VISIBLE) { Log.debug( ServiceConstants.LOG_TAG, LOG_SOURCE, "Presentable is already hidden. Ignoring hide request." ) presentation.listener.onError(this@AEPPresentable, AlreadyHidden) return@launch } // Hide the presentable from the current activity. Note that unlike show() and dismiss() // which perform actions on the view itself, hide() only modifies the presentable state // resulting in composable to be hidden. presentationStateManager.onHidden() // Notify listeners presentation.listener.onHide(this@AEPPresentable) presentationDelegate?.onHide(this@AEPPresentable) presentationObserver.onPresentationInvisible(getPresentation()) } } override fun onActivityResumed(activity: Activity) { // When an activity associated with the host application is resumed, attach the ComposeView to it. // Do not change the state of the presentable it because this is an implicit attachment. mainScope.launch { // When an activity is resumed, attach the presentable only if it is already shown. if (getState() != Presentable.State.VISIBLE) { return@launch } // If the activity that has currently resumed is not the same as the one the presentable // is attached to, then it means that another activity has launched on top of/beside // current activity. Detach the presentable from the current activity before attaching // it to the newly resumed activity. val currentAttachmentHandle = attachmentHandle.get() if (currentAttachmentHandle != null && currentAttachmentHandle != activity) { Log.trace( ServiceConstants.LOG_TAG, LOG_SOURCE, "Detaching from $currentAttachmentHandle before attaching to $activity." ) detach(currentAttachmentHandle) } attach(activity) } } override fun onActivityDestroyed(activity: Activity) { // When an activity associated with the host application is destroyed, detach the ComposeView from it. // Do not change the state of the presentable it because this is an implicit detachment. mainScope.launch { detach(activity) } } override fun getState(): Presentable.State { return presentationStateManager.presentableState.value } /** * Waits for the exit animation to complete before performing any cleanup. * Subclasses can override this method to wait for the exit animation to complete before invoking * [onAnimationComplete]. Default implementation is to not wait for any exit animation to complete. * @param onAnimationComplete the callback to be invoked after the exit animation is complete. */ protected open fun awaitExitAnimation(onAnimationComplete: () -> Unit) { // Default implementation is to not wait for any exit animation to complete. onAnimationComplete() } /** * Fetches the [ComposeView] associated with the presentable. This ComposeView is used to * render the UI of the presentable by attaching it to the content view of the activity. * @param activityContext The context associated with the activity. */ abstract fun getContent(activityContext: Context): ComposeView /** * Determines whether the [Presentable] should be shown or not after consulting the [PresentationDelegate]. * @return true if the presentable should be shown, false otherwise. */ abstract fun gateDisplay(): Boolean /** * Determines whether the presentable has any conflicts with the given list of visible presentations * on the screen. * @param visiblePresentations list of visible presentations on the screen. */ abstract fun hasConflicts(visiblePresentations: List<Presentation<*>>): Boolean /** * Makes the presentable visible on the given activity by attaching it to the activity's content view. * Also changes the state of the presentable. * @param activity The activity to attach the presentable to. */ @MainThread private fun show(activity: Activity) { attach(activity) // Change the state after the view is attached to the activity. // This will trigger the recomposition of the view and result in any animations to be seen after attaching. presentationStateManager.onShown() } /** * Attaches the presentable content with identifier [contentIdentifier] to the given activity. * The caller of this method is responsible for changing the state of the presentable before or after calling this method. * This method will always result in the presentable being attached to the activity's content view (absent exceptions), * either by virtue of the view already being a part of the view hierarchy or by creating a new view and * attaching it to the activity's content view. * @param activityToAttach The activity to attach the presentable to. */ @MainThread private fun attach(activityToAttach: Activity) { val existingComposeView: View? = activityToAttach.findViewById(contentIdentifier) if (existingComposeView != null) { Log.debug( ServiceConstants.LOG_TAG, LOG_SOURCE, "Compose view already exists with id: $contentIdentifier. Showing it instead of creating a new one." ) return } activityCompatOwnerUtils.attachActivityCompatOwner(activityToAttach) // Fetch a new content view from the presentable val composeView: ComposeView = getContent(activityToAttach) composeView.id = contentIdentifier val rootViewGroup = activityToAttach.findViewById<ViewGroup>(android.R.id.content) rootViewGroup.addView(composeView) // Update the attachment handle to the currently attached activity. attachmentHandle = WeakReference(activityToAttach) Log.trace( ServiceConstants.LOG_TAG, LOG_SOURCE, "Attached $contentIdentifier to $activityToAttach." ) } /** * Removes the presentable content from the given activity and changes the state of the presentable. * @param activity The activity to detach the presentable from. */ @MainThread private fun dismiss(activity: Activity) { // Change the state before the view is detached from the activity. // This will trigger the recomposition of the view and result in any animations. presentationStateManager.onDetached() // If the presentable has an exit animation, wait for it to complete before detaching the ComposeView. // This is done to ensure that the ComposeView is not detached before the exit animation completes. // This is important because the exit animation may be a part of the ComposeView itself and detaching // the ComposeView before the animation completes will result in the animation being cancelled. awaitExitAnimation { detach(activity) } } /** * Detaches the presentable content (previously fetched via [getContent]) with identifier [contentIdentifier] from the given activity. * The caller of this method is responsible for changing the state of the presentable before or after * calling this method. * This method will always result in the presentable being detached from the activity's content view (absent exceptions), * either by virtue of the view already being absent from the view hierarchy or by removing the existing view. * @param activityToDetach The activity to detach the presentable from. */ @MainThread private fun detach(activityToDetach: Activity) { val rootViewGroup: ViewGroup = activityToDetach.findViewById(android.R.id.content) val existingComposeView: ComposeView? = activityToDetach.findViewById(contentIdentifier) if (existingComposeView == null) { Log.debug( ServiceConstants.LOG_TAG, LOG_SOURCE, "Compose view does not exist. Nothing to detach." ) return } existingComposeView.removeAllViews() rootViewGroup.removeView(existingComposeView) // Clear the attachment handle if the current attachment handle is the same as the activity // to detach. If not, the handle would have already been cleared when the presentable // was attached due to another activity being resumed on top of the presentable. val currentAttachmentHandle = attachmentHandle.get() if (currentAttachmentHandle == activityToDetach) { Log.trace( ServiceConstants.LOG_TAG, LOG_SOURCE, "Clearing attachment handle ($activityToDetach)." ) attachmentHandle.clear() } activityCompatOwnerUtils.detachActivityCompatOwner(activityToDetach) Log.trace(ServiceConstants.LOG_TAG, LOG_SOURCE, "Detached ${contentIdentifier}from $activityToDetach.") } } /** * Responsible for tracking the currently visible presentations. Methods of this class should be invoked * from the same thread across presentables to ensure serialization of the operations. Since this is managed * from [AEPPresentable], this guarantee is already provided (due to calls from main thread). This class should * be moved to the API layer and appropriate serialization mechanisms should be added in case we want to add the * ability to have custom implementation of [Presentable]s. */ @VisibleForTesting internal class PresentationObserver private constructor() { companion object { internal val INSTANCE by lazy { PresentationObserver() } } /** * A map of presentation IDs to weak references of the presentation. * This map is used to keep track of the currently visible presentations. */ private val visiblePresentations: MutableMap<String, WeakReference<Presentation<*>>> = mutableMapOf() /** * Called when a presentation becomes visible. * @param presentation The presentation that became visible. */ @VisibleForTesting @MainThread internal fun onPresentationVisible(presentation: Presentation<*>) { visiblePresentations[presentation.id] = WeakReference(presentation) } /** * Called when a presentation becomes invisible from the screen either due to being hidden or dismissed. * @param presentation The presentation that became invisible from the screen. */ @VisibleForTesting @MainThread internal fun onPresentationInvisible(presentation: Presentation<*>) { visiblePresentations.remove(presentation.id) } /** * Returns the list of currently visible presentations. * @return The list of currently visible presentations. */ @VisibleForTesting @MainThread internal fun getVisiblePresentations(): List<Presentation<*>> { // Use this opportunity to clean up the map of any lost references val lostRefs = visiblePresentations.filterValues { it.get() == null }.keys lostRefs.forEach { visiblePresentations.remove(it) } // Return the list of visible presentations return visiblePresentations.values.mapNotNull { it.get() } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/internal/context/AppStateListener.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.internal.context /** * Listener for app state transition events. */ internal interface AppStateListener { /** * Invoked when the application transitions into the AppState.FOREGROUND state. */ fun onForeground() /** * Invoked when the application transitions into the AppState.BACKGROUND state. */ fun onBackground() }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/internal/context/App.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.internal.context import android.app.Activity import android.app.Application import android.content.ComponentCallbacks2 import android.content.ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN import android.content.Context import android.content.res.Configuration import android.net.ConnectivityManager import android.os.Bundle import androidx.annotation.VisibleForTesting import com.adobe.marketing.mobile.services.AppContextService import com.adobe.marketing.mobile.services.AppState import java.lang.ref.WeakReference import java.util.concurrent.ConcurrentLinkedQueue /** * The [App] holds some variables related to the current application, including app [Context], * the current [Activity]. Also provides the method to get the orientation of the device, and the * methods to get and set icons for notifications. */ internal object App : AppContextService, Application.ActivityLifecycleCallbacks, ComponentCallbacks2 { @Volatile private var application: WeakReference<Application>? = null @Volatile private var applicationContext: WeakReference<Context>? = null @Volatile private var currentActivity: WeakReference<Activity>? = null @Volatile private var appState = AppState.UNKNOWN private var onActivityResumed: SimpleCallback<Activity>? = null private var appStateListeners: ConcurrentLinkedQueue<AppStateListener> = ConcurrentLinkedQueue() private var connectivityManager: ConnectivityManager? = null // AppContextService overrides override fun setApplication(application: Application) { if (this.application?.get() != null) { return } this.application = WeakReference(application) setAppContext(application) registerActivityLifecycleCallbacks(application) this.connectivityManager = application.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager } override fun getApplication(): Application? { return application?.get() } override fun getApplicationContext(): Context? { return applicationContext?.get() } override fun getCurrentActivity(): Activity? { return this.currentActivity?.get() } override fun getAppState(): AppState { return appState } override fun getConnectivityManager(): ConnectivityManager? { return connectivityManager } // Android Lifecycle overrides override fun onActivityResumed(activity: Activity) { setAppState(AppState.FOREGROUND) onActivityResumed?.call(activity) setCurrentActivity(activity) } override fun onActivityPaused(activity: Activity) { // do nothing } override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { // do nothing } override fun onActivityStarted(activity: Activity) { // do nothing } override fun onActivityStopped(activity: Activity) { // do nothing } override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) { // do nothing } override fun onActivityDestroyed(activity: Activity) { // do nothing } override fun onConfigurationChanged(paramConfiguration: Configuration) { // do nothing } override fun onLowMemory() { // do nothing } override fun onTrimMemory(level: Int) { // https://developer.android.com/reference/android/content/ComponentCallbacks2.html#TRIM_MEMORY_UI_HIDDEN if (level >= TRIM_MEMORY_UI_HIDDEN) { setAppState(AppState.BACKGROUND) } } // Internal methods called current from Core. @JvmName("setAppContext") internal fun setAppContext(appContext: Context?) { val context = appContext?.applicationContext if (context != null) { this.applicationContext = WeakReference(context) } } @JvmName("setCurrentActivity") internal fun setCurrentActivity(activity: Activity?) { this.currentActivity = if (activity != null) { WeakReference(activity) } else { null } } @JvmName("registerActivityResumedListener") internal fun registerActivityResumedListener(resumedListener: SimpleCallback<Activity>) { onActivityResumed = resumedListener } /** * Registers a `AppStateListener` which will gets called when the app state changes. * * @param listener the [AppStateListener] to receive app state change events */ fun registerListener(listener: AppStateListener) { appStateListeners.add(listener) } /** * Unregisters a `AppStateListener`. * * @param listener the [AppStateListener] to unregister */ fun unregisterListener(listener: AppStateListener) { appStateListeners.remove(listener) } // This method is used only for testing @VisibleForTesting @JvmName("resetInstance") internal fun resetInstance() { application?.get()?.let { unregisterActivityLifecycleCallbacks(it) } applicationContext = null currentActivity = null application = null appStateListeners = ConcurrentLinkedQueue() appState = AppState.UNKNOWN } private fun setAppState(state: AppState) { if (appState == state) { return } appState = state notifyAppStateListeners() } private fun notifyAppStateListeners() { for (listener in appStateListeners) { if (appState == AppState.FOREGROUND) { listener.onForeground() } else if (appState == AppState.BACKGROUND) { listener.onBackground() } } } /** * Registers `this` as the activity lifecycle callback for the `Application`. * * @param application the [Application] of the app */ private fun registerActivityLifecycleCallbacks( application: Application ) { application.registerActivityLifecycleCallbacks(this) application.registerComponentCallbacks(this) } /** * Unregisters `this` as the activity lifecycle callback for the `Application`. * * @param application the [Application] of the app */ private fun unregisterActivityLifecycleCallbacks( application: Application ) { application.unregisterActivityLifecycleCallbacks(this) application.unregisterComponentCallbacks(this) } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/internal/context/SimpleCallback.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.internal.context fun interface SimpleCallback<T> { fun call(t: T) }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/services/internal/caching/CacheFileManager.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.internal.caching; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import com.adobe.marketing.mobile.internal.util.FileUtils; import com.adobe.marketing.mobile.internal.util.StringEncoder; import com.adobe.marketing.mobile.services.Log; import com.adobe.marketing.mobile.services.ServiceConstants; import com.adobe.marketing.mobile.services.ServiceProvider; import com.adobe.marketing.mobile.services.caching.CacheEntry; import com.adobe.marketing.mobile.util.StringUtils; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; /** Helper class for {@code FileCacheService} used for managing cache files and their metadata. */ class CacheFileManager { private static final String TAG = "CacheFileManager"; @VisibleForTesting static final String CACHE_METADATA_FILE_EXT = "_metadata.txt"; private final String rootCacheDirName; CacheFileManager(@NonNull final String rootCacheDirName) { this.rootCacheDirName = rootCacheDirName; } /** * Creates a directory with name {@code cacheName} inside the {@code cacheRoot} folder of {@code * deviceInfoService.getApplicationCacheDir()} * * @param cacheName the name of the folder to act as a cache bucket. * @return a {@code File} handle for the newly created/existing bucket; null if the directory * creation fails. */ File createCache(@NonNull final String cacheName) { if (StringUtils.isNullOrEmpty(cacheName)) return null; final File appCacheDir = ServiceProvider.getInstance().getDeviceInfoService().getApplicationCacheDir(); if (!FileUtils.isWritableDirectory(appCacheDir)) { Log.debug(ServiceConstants.LOG_TAG, TAG, "App cache directory is not writable."); return null; } final File cacheBucket = new File(appCacheDir, rootCacheDirName + File.separator + cacheName); if (!cacheBucket.exists() && !cacheBucket.mkdirs()) { Log.debug(ServiceConstants.LOG_TAG, TAG, "Cannot create cache bucket."); return null; } return cacheBucket; } /** * Retrieves a cache file for {@code key} from {@code cacheName} directory. * * @param cacheName the cache sub-folder within {@code cacheRoot} where cache file stored for * key should be fetched from * @param key the key for which the cache file should be retrieved * @return the cache file for {@code key} if present; null otherwise. */ File getCacheFile(@NonNull final String cacheName, @NonNull final String key) { final String entryLocation = getCacheLocation(cacheName, key); if (entryLocation == null) return null; final File entryHandle = new File(entryLocation); if (entryHandle.exists()) { return entryHandle; } else { return null; } } /** * Retrieves a cache metadata file for {@code key} from {@code cacheName} directory. * * @param cacheName the cache sub-folder within {@code cacheRoot} where the metadata for cache * file stored for key should be fetched from * @param key the key for which the cache file metadata should be retrieved * @return the cache metadata for cache file stored for {@code key} if present; null otherwise. */ Map<String, String> getCacheMetadata( @NonNull final String cacheName, @NonNull final String key) { if (!canProcess(cacheName, key)) { return null; } final String metaDataLocation = getMetadataLocation(cacheName, key); if (metaDataLocation == null) { Log.debug( ServiceConstants.LOG_TAG, TAG, "Metadata location for" + "cache name: [%s], cache key [%s] is null.", cacheName, key); return null; } final String metadataJson = FileUtils.readAsString(new File(metaDataLocation)); if (metadataJson == null) { Log.debug( ServiceConstants.LOG_TAG, TAG, "Metadata stored for" + "cache name: [%s], cache key [%s] is null.", cacheName, key); return null; } try { final Map<String, String> metadata = new HashMap<>(); final JSONObject contentJson = new JSONObject(new JSONTokener(metadataJson)); Iterator<String> jsonKeys = contentJson.keys(); while (jsonKeys.hasNext()) { final String jsonKey = jsonKeys.next(); final String jsonValue = contentJson.optString(jsonKey); metadata.put(jsonKey, jsonValue); } return metadata; } catch (final JSONException e) { Log.debug( ServiceConstants.LOG_TAG, TAG, "Cannot create cache metadata for" + "cache name: [%s], cache key: [%s] due to %s", cacheName, key, e.getMessage()); return null; } } /** * Creates a cache file and a cache metadata file based on {@code cacheEntry} to be retrievable * via {@code key}. These files are stored inside {@code cacheRoot/cacheName} dir. * * @param cacheName the cache sub-folder within {@code cacheRoot} where the cache file and * metadata are stored * @param key the key for which the cacheEntry should be linked to. * @param cacheEntry the cache entry based on which the cache file should be created * @return true if the cache file and metadata file are created successfully; false otherwise. */ boolean createCacheFile( @NonNull final String cacheName, @NonNull final String key, @NonNull final CacheEntry cacheEntry) { if (!canProcess(cacheName, key)) { return false; } // Attempt to save the cache file. final String entryLocation = getCacheLocation(cacheName, key); if (entryLocation == null) { Log.debug( ServiceConstants.LOG_TAG, TAG, "Entry location for " + "cache name: [%s], cache key [%s] is null.", cacheName, key); return false; } final boolean saved = FileUtils.readInputStreamIntoFile( new File(entryLocation), cacheEntry.getData(), false); if (!saved) { Log.debug( ServiceConstants.LOG_TAG, TAG, "Failed to save cache file for " + "cache name: [%s], cache key [%s].", cacheName, key); return false; } // Attempt to save metadata final String metaDataLocation = getMetadataLocation(cacheName, key); final boolean metadataSaved = createCacheMetadataFile(cacheEntry, entryLocation, metaDataLocation); if (!metadataSaved) { Log.debug( ServiceConstants.LOG_TAG, TAG, "Failed to save metadata for" + "cache name: [%s], cache key [%s].", cacheName, key); // Metadata save failed. Delete the cache file previously saved. final File savedCacheFile = new File(entryLocation); FileUtils.deleteFile(savedCacheFile, true); return false; } return true; } /** * Creates a metadata file based on {@code cacheEntry} to be retrievable via {@code key}. * * @param cacheEntry the cache entry based on which the metadata file should be created * @param metadataFilePath the location where the metadata file should be placed * @return true if the cache file and metadata file are created successfully; false otherwise. */ private boolean createCacheMetadataFile( final CacheEntry cacheEntry, final String entryLocation, final String metadataFilePath) { if (cacheEntry == null || StringUtils.isNullOrEmpty(metadataFilePath)) { return false; } final Map<String, String> metadata = new HashMap<>(); metadata.put(FileCacheResult.METADATA_KEY_PATH_TO_FILE, entryLocation); final Date expiry = cacheEntry.getExpiry().getExpiration(); if (expiry != null) { metadata.put( FileCacheResult.METADATA_KEY_EXPIRY_IN_MILLIS, String.valueOf(expiry.getTime())); } if (cacheEntry.getMetadata() != null) { metadata.putAll(cacheEntry.getMetadata()); } try { final JSONObject metadataJson = new JSONObject(metadata); final InputStream metadataStream = new ByteArrayInputStream( metadataJson.toString().getBytes(StandardCharsets.UTF_8)); return FileUtils.readInputStreamIntoFile( new File(metadataFilePath), metadataStream, false); } catch (final Exception exception) { Log.debug(ServiceConstants.LOG_TAG, TAG, "Cannot create cache metadata %s", exception); return false; } } /** * Deletes the cache file and a cache metadata file associated with {@code key}. * * @param cacheName the cache sub-folder from which files associated with the key need to be * deleted * @param key the key for which the cache file and cache metadata file should be deleted * @return true if the cache file and metadata file were deleted successfully; false otherwise. */ boolean deleteCacheFile(final String cacheName, final String key) { if (!canProcess(cacheName, key)) { return false; } final File cacheFileToDelete = getCacheFile(cacheName, key); if (cacheFileToDelete == null) { Log.debug( ServiceConstants.LOG_TAG, TAG, "Cannot delete cache file. No file to delete."); return true; } if (!FileUtils.deleteFile(cacheFileToDelete, true)) { Log.debug( ServiceConstants.LOG_TAG, TAG, "Failed to delete cache file for " + "cache name [%s], key: [%s]", cacheName, key); return false; } final String cacheFileMetadataPath = getMetadataLocation(cacheName, key); if (cacheFileMetadataPath != null) { Log.debug( ServiceConstants.LOG_TAG, TAG, "Failed to delete cache metadata file for " + "cache name [%s], key: [%s]", cacheName, key); FileUtils.deleteFile(new File(cacheFileMetadataPath), true); } return true; } @VisibleForTesting String getCacheLocation(final String cacheName, final String key) { if (!canProcess(cacheName, key)) { return null; } final String hash = StringEncoder.sha2hash(key); return (ServiceProvider.getInstance() .getDeviceInfoService() .getApplicationCacheDir() .getPath() + File.separator + rootCacheDirName + File.separator + cacheName + File.separator + hash); } @VisibleForTesting String getMetadataLocation(final String cacheName, final String key) { if (!canProcess(cacheName, key)) { return null; } return getCacheLocation(cacheName, key) + CACHE_METADATA_FILE_EXT; } private boolean canProcess(final String cacheName, final String key) { return !StringUtils.isNullOrEmpty(cacheName) && !StringUtils.isNullOrEmpty(key); } }
0