From 87b39d34f290c48e913a0c166dd7aa7ab685eb30 Mon Sep 17 00:00:00 2001 From: Romman Sabbir Date: Mon, 10 May 2021 19:39:36 +0600 Subject: [PATCH] Initial Release: 1.0.0 --- .gitignore | 15 ++ README.md | 171 ++++++++++++++++ StoreX/.gitignore | 1 + StoreX/build.gradle | 51 +++++ StoreX/consumer-rules.pro | 0 StoreX/proguard-rules.pro | 21 ++ StoreX/src/main/AndroidManifest.xml | 5 + .../com/rommansabbir/storex/EncryptionTool.kt | 101 ++++++++++ .../java/com/rommansabbir/storex/Extension.kt | 7 + .../rommansabbir/storex/StoreAbleObject.kt | 13 ++ .../java/com/rommansabbir/storex/StoreX.kt | 30 +++ .../com/rommansabbir/storex/StoreXCore.kt | 55 ++++++ .../com/rommansabbir/storex/StoreXInstance.kt | 186 ++++++++++++++++++ .../com/rommansabbir/storex/StoreXStorage.kt | 42 ++++ .../com/rommansabbir/storex/Subscriber.kt | 10 + .../storex/callbacks/EventCallback.kt | 11 ++ .../storex/callbacks/GetCallback.kt | 7 + .../storex/callbacks/SaveCallback.kt | 7 + .../execptions/DuplicateKeyFoundException.kt | 4 + .../InvalidEncryptionKeyException.kt | 4 + .../execptions/NoStoreAbleObjectFound.kt | 4 + .../execptions/NotInitializedException.kt | 4 + app/.gitignore | 1 + app/build.gradle | 47 +++++ app/proguard-rules.pro | 21 ++ app/src/main/AndroidManifest.xml | 22 +++ .../rommansabbir/storexdemo/MainActivity.kt | 121 ++++++++++++ .../java/com/rommansabbir/storexdemo/MyApp.kt | 11 ++ .../com/rommansabbir/storexdemo/UserData.kt | 7 + .../drawable-v24/ic_launcher_foreground.xml | 30 +++ .../res/drawable/ic_launcher_background.xml | 170 ++++++++++++++++ app/src/main/res/layout/activity_main.xml | 180 +++++++++++++++++ .../res/mipmap-anydpi-v26/ic_launcher.xml | 5 + .../mipmap-anydpi-v26/ic_launcher_round.xml | 5 + app/src/main/res/mipmap-hdpi/ic_launcher.png | Bin 0 -> 3593 bytes .../res/mipmap-hdpi/ic_launcher_round.png | Bin 0 -> 5339 bytes app/src/main/res/mipmap-mdpi/ic_launcher.png | Bin 0 -> 2636 bytes .../res/mipmap-mdpi/ic_launcher_round.png | Bin 0 -> 3388 bytes app/src/main/res/mipmap-xhdpi/ic_launcher.png | Bin 0 -> 4926 bytes .../res/mipmap-xhdpi/ic_launcher_round.png | Bin 0 -> 7472 bytes .../main/res/mipmap-xxhdpi/ic_launcher.png | Bin 0 -> 7909 bytes .../res/mipmap-xxhdpi/ic_launcher_round.png | Bin 0 -> 11873 bytes .../main/res/mipmap-xxxhdpi/ic_launcher.png | Bin 0 -> 10652 bytes .../res/mipmap-xxxhdpi/ic_launcher_round.png | Bin 0 -> 16570 bytes app/src/main/res/values-night/themes.xml | 16 ++ app/src/main/res/values/colors.xml | 10 + app/src/main/res/values/strings.xml | 3 + app/src/main/res/values/themes.xml | 16 ++ art/how-storex-works.png | Bin 0 -> 96145 bytes build.gradle | 27 +++ gradle.properties | 21 ++ gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 54329 bytes gradle/wrapper/gradle-wrapper.properties | 6 + gradlew | 172 ++++++++++++++++ gradlew.bat | 84 ++++++++ settings.gradle | 3 + 56 files changed, 1727 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 StoreX/.gitignore create mode 100644 StoreX/build.gradle create mode 100644 StoreX/consumer-rules.pro create mode 100644 StoreX/proguard-rules.pro create mode 100644 StoreX/src/main/AndroidManifest.xml create mode 100644 StoreX/src/main/java/com/rommansabbir/storex/EncryptionTool.kt create mode 100644 StoreX/src/main/java/com/rommansabbir/storex/Extension.kt create mode 100644 StoreX/src/main/java/com/rommansabbir/storex/StoreAbleObject.kt create mode 100644 StoreX/src/main/java/com/rommansabbir/storex/StoreX.kt create mode 100644 StoreX/src/main/java/com/rommansabbir/storex/StoreXCore.kt create mode 100644 StoreX/src/main/java/com/rommansabbir/storex/StoreXInstance.kt create mode 100644 StoreX/src/main/java/com/rommansabbir/storex/StoreXStorage.kt create mode 100644 StoreX/src/main/java/com/rommansabbir/storex/Subscriber.kt create mode 100644 StoreX/src/main/java/com/rommansabbir/storex/callbacks/EventCallback.kt create mode 100644 StoreX/src/main/java/com/rommansabbir/storex/callbacks/GetCallback.kt create mode 100644 StoreX/src/main/java/com/rommansabbir/storex/callbacks/SaveCallback.kt create mode 100644 StoreX/src/main/java/com/rommansabbir/storex/execptions/DuplicateKeyFoundException.kt create mode 100644 StoreX/src/main/java/com/rommansabbir/storex/execptions/InvalidEncryptionKeyException.kt create mode 100644 StoreX/src/main/java/com/rommansabbir/storex/execptions/NoStoreAbleObjectFound.kt create mode 100644 StoreX/src/main/java/com/rommansabbir/storex/execptions/NotInitializedException.kt create mode 100644 app/.gitignore create mode 100644 app/build.gradle create mode 100644 app/proguard-rules.pro create mode 100644 app/src/main/AndroidManifest.xml create mode 100644 app/src/main/java/com/rommansabbir/storexdemo/MainActivity.kt create mode 100644 app/src/main/java/com/rommansabbir/storexdemo/MyApp.kt create mode 100644 app/src/main/java/com/rommansabbir/storexdemo/UserData.kt create mode 100644 app/src/main/res/drawable-v24/ic_launcher_foreground.xml create mode 100644 app/src/main/res/drawable/ic_launcher_background.xml create mode 100644 app/src/main/res/layout/activity_main.xml create mode 100644 app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml create mode 100644 app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml create mode 100644 app/src/main/res/mipmap-hdpi/ic_launcher.png create mode 100644 app/src/main/res/mipmap-hdpi/ic_launcher_round.png create mode 100644 app/src/main/res/mipmap-mdpi/ic_launcher.png create mode 100644 app/src/main/res/mipmap-mdpi/ic_launcher_round.png create mode 100644 app/src/main/res/mipmap-xhdpi/ic_launcher.png create mode 100644 app/src/main/res/mipmap-xhdpi/ic_launcher_round.png create mode 100644 app/src/main/res/mipmap-xxhdpi/ic_launcher.png create mode 100644 app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png create mode 100644 app/src/main/res/mipmap-xxxhdpi/ic_launcher.png create mode 100644 app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png create mode 100644 app/src/main/res/values-night/themes.xml create mode 100644 app/src/main/res/values/colors.xml create mode 100644 app/src/main/res/values/strings.xml create mode 100644 app/src/main/res/values/themes.xml create mode 100644 art/how-storex-works.png create mode 100644 build.gradle create mode 100644 gradle.properties create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100644 gradlew create mode 100644 gradlew.bat create mode 100644 settings.gradle diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..aa724b7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties diff --git a/README.md b/README.md new file mode 100644 index 0000000..35ac965 --- /dev/null +++ b/README.md @@ -0,0 +1,171 @@ +[![Release](https://jitpack.io/v/jitpack/android-example.svg)](https://jitpack.io/#rommansabbir/StoreX) +# StoreX +✔️ Simplify Caching in Android + +## Features +* Notify on Data Changes based on Subscription +* Lightweight +* AES Encryption +* Thread Safe + +## How does it work? +Caching is just a simple key-value pair data saving procedure. StoreX follows the same approach. StoreX uses SharedPreference as storage for caching data. Since we really can't just save the original data because of security issues. StoreX uses AES encryption & decryption behind the scene when you are caching data or fetching data from the cache. Also, you can observer cached data in real-time. + +## Documentation + +### Installation + +--- +Step 1. Add the JitPack repository to your build file + +```gradle +allprojects { + repositories { + maven { url 'https://jitpack.io' } + } +} +``` + +Step 2. Add the dependency + +```gradle +dependencies { + implementation 'com.github.rommansabbir:StoreX:Tag' +} +``` + +--- + +### Version available + +| Latest Releases +| ------------- | +| 1.0.0 | + +--- + +## Initialize +```` +StoreXCore.init(application: Application, prefName: String) +```` + +## How To Access +```` +StoreXCore.instance() +```` +or else, use the extension function +```` +storeXInstance() +```` +which return an instance of `StoreX` [Note: You must initalize `StoreX` properly before accessing or else it will throw `NotInitializedException`] + +Also, you can set encryption key for your data accross the application by calling this method `StoreXCore.setEncryptionKey(key:String)` which throw `InvalidEncryptionKeyException` if you passed empty `String` + +---- + +# Usages + +## How to save an object to StoreX? + +Create any data class that extends `StoreAbleObject` +Example: +````` +class MyClass:StoreAbleObject() +````` +How to save the object (Main Thread) +```` +StoreX.put(key: String, value: StoreAbleObject) +```` +or use Async +```` +StoreX.put(key: String, value: StoreAbleObject, callback: SaveCallback) +```` + + +## How to get an object from StoreX? +Get an saved object (Main Thread) which may throw `RuntimeException` +```` +StoreX.get(key: String, objectType: Class): T +```` +or use Async +```` +StoreX.get(key: String, objectType: Class, callback: GetCallback) +```` + +## How to get notified on data changes? +Simple, to get notified on any data changes according to a given key you first need to subscribe to StoreX by calling this method `StoreX.addSubscriber(subscriber: Subscriber)` else if you want to add a list subscriber use `StoreX.addSubscriber(subscribers: ArrayList)` + +Example: +First setup an callback for the data changes +```` + private val callback1 = object : EventCallback{ + override fun onDataChanges(subscriber: Subscriber, instance: StoreX) { + // Callback return an instance of StoreX and the specific subscriber + } + } +```` +Create a new sunscriber. + +Create a new subscriber by providing the `Key`, `Observer ID (Must be unique)` and the `Callback` + +```` + private var subscriber1 = Subscriber(key, OBSERVER_ID_1, callback1) +```` + +Now register the subscriber to the `StoreX` by calling this method +```` +StoreX.addSubscriber(subscriber1) +```` + +Also, you can remove your subscription any time by calling this method +`StoreX.removeSubscriber(subscriber: Subscriber)` or list of subscriber `StoreX.removeSubscriber(subscribers: ArrayList)` +```` +storeXInstance().removeSubscriber(subscriber1) +```` + +## How to remove any saved data? +```` +StoreX.remove(key: String) +```` + +## How to remove all data when you are crazy +```` +StoreX.removeAll() +```` + +##### Need more information regarding the solid implementation? - Check out the sample application. + +--- + + +### How does StoreX work? + + + +---- + +### Contact me +[Portfolio](https://www.rommansabbir.com/) | [LinkedIn](https://www.linkedin.com/in/rommansabbir/) | [Twitter](https://www.twitter.com/itzrommansabbir/) | [Facebook](https://www.facebook.com/itzrommansabbir/) + +### License + +--- +[Apache Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html) + +```` +Copyright (C) 2021 Romman Sabbir + +Licensed 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 CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +```` + + diff --git a/StoreX/.gitignore b/StoreX/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/StoreX/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/StoreX/build.gradle b/StoreX/build.gradle new file mode 100644 index 0000000..f7ecab6 --- /dev/null +++ b/StoreX/build.gradle @@ -0,0 +1,51 @@ +apply plugin: 'com.android.library' +apply plugin: 'kotlin-android' +apply plugin: 'kotlin-android-extensions' +apply plugin: 'com.github.dcendents.android-maven' +group = 'rommansabbir' +version '1.0' + +android { + compileSdkVersion 30 + buildToolsVersion "30.0.3" + + defaultConfig { + minSdkVersion 16 + targetSdkVersion 30 + versionCode 1 + versionName "1.0" + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + consumerProguardFiles "consumer-rules.pro" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + kotlinOptions { + jvmTarget = '1.8' + } +} + +dependencies { + + implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + implementation 'androidx.core:core-ktx:1.3.2' + implementation 'androidx.appcompat:appcompat:1.2.0' + implementation 'com.google.android.material:material:1.3.0' + testImplementation 'junit:junit:4.+' + androidTestImplementation 'androidx.test.ext:junit:1.1.2' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' + implementation "com.google.code.gson:gson:2.8.6" + + + implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.2' + implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9' +} \ No newline at end of file diff --git a/StoreX/consumer-rules.pro b/StoreX/consumer-rules.pro new file mode 100644 index 0000000..e69de29 diff --git a/StoreX/proguard-rules.pro b/StoreX/proguard-rules.pro new file mode 100644 index 0000000..481bb43 --- /dev/null +++ b/StoreX/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/StoreX/src/main/AndroidManifest.xml b/StoreX/src/main/AndroidManifest.xml new file mode 100644 index 0000000..45622f0 --- /dev/null +++ b/StoreX/src/main/AndroidManifest.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/StoreX/src/main/java/com/rommansabbir/storex/EncryptionTool.kt b/StoreX/src/main/java/com/rommansabbir/storex/EncryptionTool.kt new file mode 100644 index 0000000..3014b41 --- /dev/null +++ b/StoreX/src/main/java/com/rommansabbir/storex/EncryptionTool.kt @@ -0,0 +1,101 @@ +package com.rommansabbir.storex + +import android.util.Base64 +import java.security.GeneralSecurityException +import java.security.SecureRandom +import javax.crypto.Cipher +import javax.crypto.SecretKey +import javax.crypto.SecretKeyFactory +import javax.crypto.spec.IvParameterSpec +import javax.crypto.spec.PBEKeySpec +import javax.crypto.spec.SecretKeySpec + + +internal object EncryptionTool { + private const val ITERATION_COUNT = 1000 + private const val KEY_LENGTH = 256 + private const val PBKDF2_DERIVATION_ALGORITHM = "PBKDF2WithHmacSHA1" + private const val CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding" + private const val PKCS5_SALT_LENGTH = 32 + private const val DELIMITER = "]" + private val random = SecureRandom() + + /** + * Encrypt the given data. + * + * @param dataToEncrypt Data that need to be encrypted + * + * @return [String] Encrypted Data + */ + fun encrypt(dataToEncrypt: String): String { + val salt = generateSalt() + val key = deriveKey(StoreXCore.encryptionKey, salt) + val cipher = Cipher.getInstance(CIPHER_ALGORITHM) + val iv = generateIv(cipher.blockSize) + val ivParams = IvParameterSpec(iv) + cipher.init(Cipher.ENCRYPT_MODE, key, ivParams) + val cipherText = cipher.doFinal(dataToEncrypt.toByteArray(Charsets.UTF_8)) + return String.format( + "%s%s%s%s%s", + toBase64(salt), + DELIMITER, + toBase64(iv), + DELIMITER, + toBase64(cipherText) + ) + } + + /** + * Decrypt the given data. + * + * @param dataToDecrypt Data that need to be encrypted + * + * @return [String] Decrypted Data + */ + fun decrypt(dataToDecrypt: String): String { + val fields = + dataToDecrypt.split(DELIMITER.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() + require(fields.size == 3) { "Invalid encrypted text format" } + val salt = fromBase64(fields[0]) + val iv = fromBase64(fields[1]) + val cipherBytes = fromBase64(fields[2]) + val key = deriveKey(StoreXCore.encryptionKey, salt) + val cipher = Cipher.getInstance(CIPHER_ALGORITHM) + val ivParams = IvParameterSpec(iv) + cipher.init(Cipher.DECRYPT_MODE, key, ivParams) + val plaintext = cipher.doFinal(cipherBytes) + return String(plaintext, Charsets.UTF_8) + } + + private fun generateSalt(): ByteArray { + val b = ByteArray(PKCS5_SALT_LENGTH) + random.nextBytes(b) + return b + } + + private fun generateIv(length: Int): ByteArray { + val b = ByteArray(length) + random.nextBytes(b) + return b + } + + private fun deriveKey(password: String, salt: ByteArray?): SecretKey { + try { + val keySpec = PBEKeySpec(password.toCharArray(), salt!!, ITERATION_COUNT, KEY_LENGTH) + val keyFactory = SecretKeyFactory.getInstance(PBKDF2_DERIVATION_ALGORITHM) + val keyBytes = keyFactory.generateSecret(keySpec).encoded + return SecretKeySpec(keyBytes, "AES") + } catch (e: GeneralSecurityException) { + throw RuntimeException(e) + } + } + + private fun toBase64(bytes: ByteArray): String { + return Base64.encodeToString(bytes, Base64.NO_WRAP) + } + + private fun fromBase64(base64: String): ByteArray { + return Base64.decode(base64, Base64.NO_WRAP) + } + +} \ No newline at end of file diff --git a/StoreX/src/main/java/com/rommansabbir/storex/Extension.kt b/StoreX/src/main/java/com/rommansabbir/storex/Extension.kt new file mode 100644 index 0000000..64aca71 --- /dev/null +++ b/StoreX/src/main/java/com/rommansabbir/storex/Extension.kt @@ -0,0 +1,7 @@ +package com.rommansabbir.storex + +fun storeXInstance(): StoreX = StoreXCore.instance() + +internal fun Subscriber.getKey(): String { + return "${this.key}_${this.subscriberID}" +} \ No newline at end of file diff --git a/StoreX/src/main/java/com/rommansabbir/storex/StoreAbleObject.kt b/StoreX/src/main/java/com/rommansabbir/storex/StoreAbleObject.kt new file mode 100644 index 0000000..8a184bf --- /dev/null +++ b/StoreX/src/main/java/com/rommansabbir/storex/StoreAbleObject.kt @@ -0,0 +1,13 @@ +package com.rommansabbir.storex + +import java.io.Serializable +import java.util.* + +open class StoreAbleObject : Serializable { + private val _objectId: String = UUID.randomUUID().toString() + val objectId: String + get() = _objectId + + fun isSameObject(storeAbleObject: StoreAbleObject): Boolean = + storeAbleObject._objectId == _objectId +} diff --git a/StoreX/src/main/java/com/rommansabbir/storex/StoreX.kt b/StoreX/src/main/java/com/rommansabbir/storex/StoreX.kt new file mode 100644 index 0000000..5f5ede7 --- /dev/null +++ b/StoreX/src/main/java/com/rommansabbir/storex/StoreX.kt @@ -0,0 +1,30 @@ +package com.rommansabbir.storex + +import com.rommansabbir.storex.callbacks.GetCallback +import com.rommansabbir.storex.callbacks.SaveCallback + +interface StoreX { + @Throws(RuntimeException::class) + fun put(key: String, value: StoreAbleObject): Boolean + + fun put(key: String, value: StoreAbleObject, callback: SaveCallback) + + @Throws(RuntimeException::class) + fun get(key: String, objectType: Class): T + + fun get(key: String, objectType: Class, callback: GetCallback) + + @Throws(RuntimeException::class) + fun addSubscriber(subscriber: Subscriber) + + @Throws(RuntimeException::class) + fun addSubscriber(subscribers: ArrayList) + + fun removeSubscriber(subscriber: Subscriber) + + fun removeSubscriber(subscribers: ArrayList) + + fun remove(key: String) + + fun removeAll() +} \ No newline at end of file diff --git a/StoreX/src/main/java/com/rommansabbir/storex/StoreXCore.kt b/StoreX/src/main/java/com/rommansabbir/storex/StoreXCore.kt new file mode 100644 index 0000000..02918e9 --- /dev/null +++ b/StoreX/src/main/java/com/rommansabbir/storex/StoreXCore.kt @@ -0,0 +1,55 @@ +package com.rommansabbir.storex + +import android.app.Application +import com.google.gson.Gson +import com.rommansabbir.storex.execptions.InvalidEncryptionKeyException +import com.rommansabbir.storex.execptions.NotInitializedException + +object StoreXCore { + private var isInitialized: Boolean = false + private var instance: StoreXInstance? = null + + @Throws(RuntimeException::class) + fun instance(): StoreX { + if (isInitialized) { + return instance!! + } else { + throw NotInitializedException() + } + } + + fun init(application: Application, prefName: String): StoreXCore { + this.instance = StoreXInstance(application, prefName, Gson()) + this.instance!!.registerListener(this.instance!!.listener) + this.isInitialized = true + return this + } + + @Throws(RuntimeException::class) + fun setEncryptionKey(key: String) { + if (key.isEmpty()) { + throw InvalidEncryptionKeyException() + } + this.encryptionKey = key + } + + internal const val NO_ENCRYPTION = "NoEncryption" + internal var encryptionKey: String = NO_ENCRYPTION + + // + private var subscriberListMain: HashMap = HashMap() + internal fun subscriberList(): HashMap { + return subscriberListMain + } + + internal fun addSubscriber(subscriber: Subscriber) { + subscriberListMain[subscriber.getKey()] = subscriber + } + + internal fun removeSubscriber(subscriber: Subscriber) { + val key = subscriber.getKey() + if (subscriberListMain.containsKey(key)) { + subscriberListMain.remove(key) + } + } +} \ No newline at end of file diff --git a/StoreX/src/main/java/com/rommansabbir/storex/StoreXInstance.kt b/StoreX/src/main/java/com/rommansabbir/storex/StoreXInstance.kt new file mode 100644 index 0000000..a5eab4f --- /dev/null +++ b/StoreX/src/main/java/com/rommansabbir/storex/StoreXInstance.kt @@ -0,0 +1,186 @@ +@file:Suppress("UNCHECKED_CAST") + +package com.rommansabbir.storex + +import android.app.Application +import android.content.Context +import android.content.SharedPreferences +import com.google.gson.Gson +import com.rommansabbir.storex.callbacks.GetCallback +import com.rommansabbir.storex.callbacks.SaveCallback +import com.rommansabbir.storex.execptions.DuplicateKeyFoundException +import com.rommansabbir.storex.execptions.NoStoreAbleObjectFound +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch + + +internal class StoreXInstance( + private val application: Application, + private val prefRef: String, + private val serializer: Gson +) : StoreX, StoreXStorage { + internal var listener: SharedPreferences.OnSharedPreferenceChangeListener = + SharedPreferences.OnSharedPreferenceChangeListener { _, key -> + StoreXCore.subscriberList().keys.forEach { cacheKey -> + StoreXCore.subscriberList()[cacheKey]?.let { + if (cacheKey.contains(key) && it.getKey() == cacheKey) { + it.callback.onDataChanges(it, this@StoreXInstance) + } + } + } + } + + override fun put(key: String, value: StoreAbleObject): Boolean { + return try { + val serializedValue: String = serializer.toJson(value) + if (StoreXCore.encryptionKey == StoreXCore.NO_ENCRYPTION) { + doCache(key, serializedValue) + true + } else { + val encryptedValue = EncryptionTool.encrypt(serializedValue) + doCache(key, encryptedValue) + true + } + } catch (e: Exception) { + throw e + } + } + + override fun put( + key: String, + value: StoreAbleObject, + callback: SaveCallback + ) { + CoroutineScope(Dispatchers.Main).launch { + try { + val serializedValue: String = serializer.toJson(value) + if (StoreXCore.encryptionKey == StoreXCore.NO_ENCRYPTION) { + doCache(key, serializedValue) + callback.onDone(value as T, null) + } else { + val encryptedValue = EncryptionTool.encrypt(serializedValue) + doCache(key, encryptedValue) + callback.onDone(value as T, null) + } + } catch (e: Exception) { + callback.onDone(value as T, e) + } + } + } + + + override fun get(key: String, objectType: Class): T { + try { + when (val value = getCache(key)) { + null -> { + throw NoStoreAbleObjectFound() + } + else -> { + return when (StoreXCore.encryptionKey == StoreXCore.NO_ENCRYPTION) { + true -> { + serializer.fromJson(value, objectType) + } + else -> { + val decryptedValue = EncryptionTool.decrypt(value) + serializer.fromJson(decryptedValue, objectType) + } + } + } + } + } catch (e: Exception) { + throw e + } + } + + + override fun get( + key: String, + objectType: Class, + callback: GetCallback + ) { + CoroutineScope(Dispatchers.Main).launch { + try { + when (val value = getCache(key)) { + null -> { + callback.onSuccess(null, NoStoreAbleObjectFound()) + } + else -> { + when (StoreXCore.encryptionKey == StoreXCore.NO_ENCRYPTION) { + true -> { + callback.onSuccess(serializer.fromJson(value, objectType)) + } + else -> { + val decryptedValue = EncryptionTool.decrypt(value) + callback.onSuccess(serializer.fromJson(decryptedValue, objectType)) + } + } + } + } + } catch (e: Exception) { + callback.onSuccess(null, e) + } + } + } + + override fun addSubscriber(subscriber: Subscriber) { + if (StoreXCore.subscriberList().containsKey(subscriber.getKey())) { + throw DuplicateKeyFoundException() + } + StoreXCore.addSubscriber(subscriber) + } + + override fun addSubscriber(subscribers: ArrayList) { + subscribers.forEach { + addSubscriber(it) + } + } + + override fun removeSubscriber(subscriber: Subscriber) { + StoreXCore.removeSubscriber(subscriber) + } + + override fun removeSubscriber(subscribers: ArrayList) { + subscribers.forEach { + removeSubscriber(it) + } + } + + override fun remove(key: String) { + clearCacheByKey(key) + } + + override fun removeAll() { + clearAllCache() + } + + + // Storage + private var mSharedPreferences: SharedPreferences = + application.getSharedPreferences(prefRef, Context.MODE_PRIVATE) + + override fun doCache(key: String, value: String): Boolean { + getSharedPref().edit().putString(key, value).apply() + return true + } + + override fun getCache(key: String): String? { + return getSharedPref().getString(key, null) + } + + override fun registerListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) { + this.mSharedPreferences.registerOnSharedPreferenceChangeListener(listener) + } + + override fun clearCacheByKey(key: String) { + mSharedPreferences.edit().remove(key).apply() + } + + override fun clearAllCache() { + mSharedPreferences.edit().clear().apply() + } + + private fun getSharedPref(): SharedPreferences { + return mSharedPreferences + } +} \ No newline at end of file diff --git a/StoreX/src/main/java/com/rommansabbir/storex/StoreXStorage.kt b/StoreX/src/main/java/com/rommansabbir/storex/StoreXStorage.kt new file mode 100644 index 0000000..eff4089 --- /dev/null +++ b/StoreX/src/main/java/com/rommansabbir/storex/StoreXStorage.kt @@ -0,0 +1,42 @@ +package com.rommansabbir.storex + +import android.content.SharedPreferences + +internal interface StoreXStorage { + /** + * Cache single data. + * + * @param data The data which will be stored + * @param key The key to store the data + */ + fun doCache(key: String, value: String): Boolean + + /** + * Get single stored data. + * + * @param key The which was used to store the data + * + * @return [String], Data can be null + */ + fun getCache(key: String): String? + + /** + * Register listener to get notified on data changes. + * + * @param listener Listener to listen to the changes + */ + fun registerListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) + + /** + * Clear stored data by following the respective key. + * + * @param key The which was used to store the data + */ + fun clearCacheByKey(key: String) + + /** + * Clear all stored data. + * + */ + fun clearAllCache() +} \ No newline at end of file diff --git a/StoreX/src/main/java/com/rommansabbir/storex/Subscriber.kt b/StoreX/src/main/java/com/rommansabbir/storex/Subscriber.kt new file mode 100644 index 0000000..02ff415 --- /dev/null +++ b/StoreX/src/main/java/com/rommansabbir/storex/Subscriber.kt @@ -0,0 +1,10 @@ +package com.rommansabbir.storex + +import com.rommansabbir.storex.callbacks.EventCallback + +data class Subscriber( + val key: String, + val subscriberID: Int, + val callback: EventCallback +) + diff --git a/StoreX/src/main/java/com/rommansabbir/storex/callbacks/EventCallback.kt b/StoreX/src/main/java/com/rommansabbir/storex/callbacks/EventCallback.kt new file mode 100644 index 0000000..f686290 --- /dev/null +++ b/StoreX/src/main/java/com/rommansabbir/storex/callbacks/EventCallback.kt @@ -0,0 +1,11 @@ +package com.rommansabbir.storex.callbacks + +import com.rommansabbir.storex.StoreX +import com.rommansabbir.storex.Subscriber + +interface EventCallback { + fun onDataChanges( + subscriber: Subscriber, + instance: StoreX + ) +} \ No newline at end of file diff --git a/StoreX/src/main/java/com/rommansabbir/storex/callbacks/GetCallback.kt b/StoreX/src/main/java/com/rommansabbir/storex/callbacks/GetCallback.kt new file mode 100644 index 0000000..c88e186 --- /dev/null +++ b/StoreX/src/main/java/com/rommansabbir/storex/callbacks/GetCallback.kt @@ -0,0 +1,7 @@ +package com.rommansabbir.storex.callbacks + +import com.rommansabbir.storex.StoreAbleObject + +interface GetCallback { + fun onSuccess(value: T? = null, exception: Exception? = null) +} \ No newline at end of file diff --git a/StoreX/src/main/java/com/rommansabbir/storex/callbacks/SaveCallback.kt b/StoreX/src/main/java/com/rommansabbir/storex/callbacks/SaveCallback.kt new file mode 100644 index 0000000..af07a8d --- /dev/null +++ b/StoreX/src/main/java/com/rommansabbir/storex/callbacks/SaveCallback.kt @@ -0,0 +1,7 @@ +package com.rommansabbir.storex.callbacks + +import com.rommansabbir.storex.StoreAbleObject + +interface SaveCallback { + fun onDone(value : T, exception: Exception? = null) +} \ No newline at end of file diff --git a/StoreX/src/main/java/com/rommansabbir/storex/execptions/DuplicateKeyFoundException.kt b/StoreX/src/main/java/com/rommansabbir/storex/execptions/DuplicateKeyFoundException.kt new file mode 100644 index 0000000..37eca46 --- /dev/null +++ b/StoreX/src/main/java/com/rommansabbir/storex/execptions/DuplicateKeyFoundException.kt @@ -0,0 +1,4 @@ +package com.rommansabbir.storex.execptions + +class DuplicateKeyFoundException(@JvmField override val message: String = "This subscriber is already present in the StoreX subscribers list. Make sure your SUBSCRIBER_ID is unique or else remove the current subscriber and add new one") : + RuntimeException(message) \ No newline at end of file diff --git a/StoreX/src/main/java/com/rommansabbir/storex/execptions/InvalidEncryptionKeyException.kt b/StoreX/src/main/java/com/rommansabbir/storex/execptions/InvalidEncryptionKeyException.kt new file mode 100644 index 0000000..fb4dd40 --- /dev/null +++ b/StoreX/src/main/java/com/rommansabbir/storex/execptions/InvalidEncryptionKeyException.kt @@ -0,0 +1,4 @@ +package com.rommansabbir.storex.execptions + +class InvalidEncryptionKeyException(@JvmField override val message: String = "Invalid encryption key") : + RuntimeException(message) \ No newline at end of file diff --git a/StoreX/src/main/java/com/rommansabbir/storex/execptions/NoStoreAbleObjectFound.kt b/StoreX/src/main/java/com/rommansabbir/storex/execptions/NoStoreAbleObjectFound.kt new file mode 100644 index 0000000..284869f --- /dev/null +++ b/StoreX/src/main/java/com/rommansabbir/storex/execptions/NoStoreAbleObjectFound.kt @@ -0,0 +1,4 @@ +package com.rommansabbir.storex.execptions + +class NoStoreAbleObjectFound(@JvmField override val message: String = "No StoreAbleObject found associated with this key") : + RuntimeException(message) \ No newline at end of file diff --git a/StoreX/src/main/java/com/rommansabbir/storex/execptions/NotInitializedException.kt b/StoreX/src/main/java/com/rommansabbir/storex/execptions/NotInitializedException.kt new file mode 100644 index 0000000..1f22c76 --- /dev/null +++ b/StoreX/src/main/java/com/rommansabbir/storex/execptions/NotInitializedException.kt @@ -0,0 +1,4 @@ +package com.rommansabbir.storex.execptions + +class NotInitializedException(@JvmField override val message: String = "StoreX is not initialized properly") : + RuntimeException(message) \ No newline at end of file diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..602b4c9 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,47 @@ +plugins { + id 'com.android.application' + id 'kotlin-android' +} + +android { + compileSdkVersion 30 + buildToolsVersion "30.0.3" + + defaultConfig { + applicationId "com.rommansabbir.storexdemo" + minSdkVersion 16 + targetSdkVersion 30 + versionCode 1 + versionName "1.0" + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + kotlinOptions { + jvmTarget = '1.8' + } +} + +dependencies { + + implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + implementation 'androidx.core:core-ktx:1.3.2' + implementation 'androidx.appcompat:appcompat:1.2.0' + implementation 'com.google.android.material:material:1.3.0' + implementation 'androidx.constraintlayout:constraintlayout:2.0.4' + implementation project(path: ':StoreX') + testImplementation 'junit:junit:4.+' + androidTestImplementation 'androidx.test.ext:junit:1.1.2' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' + +} \ No newline at end of file diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..481bb43 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..e35092c --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/java/com/rommansabbir/storexdemo/MainActivity.kt b/app/src/main/java/com/rommansabbir/storexdemo/MainActivity.kt new file mode 100644 index 0000000..c7e0299 --- /dev/null +++ b/app/src/main/java/com/rommansabbir/storexdemo/MainActivity.kt @@ -0,0 +1,121 @@ +package com.rommansabbir.storexdemo + +import android.annotation.SuppressLint +import android.os.Bundle +import android.widget.Button +import android.widget.TextView +import androidx.appcompat.app.AppCompatActivity +import com.rommansabbir.storex.* +import com.rommansabbir.storex.callbacks.EventCallback +import com.rommansabbir.storex.callbacks.GetCallback +import com.rommansabbir.storex.callbacks.SaveCallback + +class MainActivity : AppCompatActivity(), EventCallback { + + private var OBSERVER_ID_1 = 1 + private var OBSERVER_ID_2 = 2 + private var OBSERVER_ID_3 = 3 + private var OBSERVER_ID_4 = 4 + + private var key = "key" + + @SuppressLint("SetTextI18n") + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + + // + findViewById