diff --git a/CHANGELOG.md b/CHANGELOG.md index 992967b9..e6b37207 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # CHANGELOG +## Version 3.12.0 + +### Date: 02-May-2023 + +- Added support for include metadata in asset, entry and query class +- Added support of Region for Azure-EU +- General code and API document improvements +- Breaking changes : PublishType Enums are updated to all CAPS +- Kotlin support removed due to build issue +- EntryModel publish_details parsing issue fixed #30 + +--- + ## Version 3.11.0 ### Date: 08-Feb-2023 @@ -131,15 +144,8 @@ Below two support from the Config class has been removed permanently Change: - Removed support for unsafe (HTTP) request. -- Below two breaking changes from Config class has been deprecated - -```java -@Deprecated -public void setSSL(boolean isSSL)setSSL() - -@Deprecated -public boolean isSSL() -``` +- Deprecated setSSL(boolean isSSL)setSSL() from config class +- Deprecated isSSL() from config class --- @@ -172,11 +178,11 @@ Added below function support for sync in Stack class New Features: - Entry - - added method ‘addParam’ + - added method ‘addParam’ - Query - - added method 'addParam' + - added method 'addParam' - Asset - - added method ‘addParam' + - added method ‘addParam' --- @@ -187,21 +193,21 @@ New Features: New Features: - Stack - - added method 'ImageTransform' + - added method 'ImageTransform' - Query - - added method 'includeContentType' + - added method 'includeContentType' - QueryResult - - added method 'content_type' + - added method 'content_type' - API Modifications: - - None + - None API deprecation: - Query - - Deprecated method 'includeSchema' + - Deprecated method 'includeSchema' - Bug Fixes: - - None + - None --- @@ -210,18 +216,18 @@ API deprecation: ### Date: 28-July-2017 - New Features: - - None + - None - API Modifications: - - None + - None API deprecation: None - Bug Fixes: - - Cache Policy bug fixed. - - Cache Policy timeout increased. + - Cache Policy bug fixed. + - Cache Policy timeout increased. --- @@ -234,15 +240,18 @@ New Features: - None API Modifications: - - None + +- None API deprecation: - - Asset + +- Asset 1] Removed getPublishDetails() method. Entry 1] Removed getPublishDetails() method. Bug Fixes: - - None. + +- None. --- @@ -251,10 +260,12 @@ Bug Fixes: ### Date: 17-May-2017 New Features: - - None + +- None API Modifications: - - None + +- None API deprecation: @@ -275,16 +286,16 @@ New Features: Added new class Group Entry - 1] Added getAllEntries(String refKey, String refContentType) method. - 2] Added getGroups(String key) method. - 3] Added getGroup(String key) method. +1] Added getAllEntries(String refKey, String refContentType) method. +2] Added getGroups(String key) method. +3] Added getGroup(String key) method. Asset - 1] Added setCachePolicy(CachePolicy policy) method. - 2] Added getTags() method. +1] Added setCachePolicy(CachePolicy policy) method. +2] Added getTags() method. AssetLibrary - 1] Added setCachePolicy(CachePolicy policy) method. +1] Added setCachePolicy(CachePolicy policy) method. API Modifications: @@ -320,7 +331,7 @@ environment, Config config) method. Stack 1] Added asset() method. 2] Added assetLibrary() method. Entry - 1] Added getPublishDetails() method. +1] Added getPublishDetails() method. API Modifications: @@ -332,20 +343,20 @@ Conetntstack 1] Removed stack(Context context, String stackApiKey, String access environment, boolean isEnvironmentUid) method. Stack - 1] Removed setVersion(String version) method. - 2] Removed setURL(String hostName, boolean isSSL) method. - 3] Removed setEnvironment(String environment, boolean isEnvironmentUid) method. - 4] Removed isEnvironmentUid() method. - 5] Removed getEnvironment() method. - 6] Removed getVersion() method. - 7] Removed getURL() method +1] Removed setVersion(String version) method. +2] Removed setURL(String hostName, boolean isSSL) method. +3] Removed setEnvironment(String environment, boolean isEnvironmentUid) method. +4] Removed isEnvironmentUid() method. +5] Removed getEnvironment() method. +6] Removed getVersion() method. +7] Removed getURL() method Entry - 1] Removed getMetadata() method. +1] Removed getMetadata() method. Query - 1] Removed afterUid() method. - 2] Removed beforeUid() method. +1] Removed afterUid() method. +2] Removed beforeUid() method. Bug Fixes: @@ -379,17 +390,20 @@ Fixed API calls issue for Android 7.0 Nougat. ### Date: 22-September-2016 New Features: - - None -API Modifications: - - None + +- None + API Modifications: +- None API deprecation: - - None + +- None Bug Fixes: - - Query 1] Fixed search method issue causing improper result. - - Entry 1] Fixed includeReference method issue causing improper result. 2] Fixed fetch method which -now return response as per environment. + +- Query 1] Fixed search method issue causing improper result. +- Entry 1] Fixed includeReference method issue causing improper result. 2] Fixed fetch method which + now return response as per environment. --- diff --git a/build.gradle b/build.gradle index 0e84797f..4fffe10f 100644 --- a/build.gradle +++ b/build.gradle @@ -1,7 +1,5 @@ buildscript { - - ext.jacocoVersion = '0.8.8' - + ext.jacoco_version = '0.8.8' repositories { maven { url "https://plugins.gradle.org/m2/" } google() @@ -9,16 +7,15 @@ buildscript { } dependencies { - classpath 'com.android.tools.build:gradle:7.0.4' //4.1.3 + classpath "com.android.tools.build:gradle:7.2.2" //7.0.4 classpath 'io.github.gradle-nexus:publish-plugin:1.1.0' - // NOTE: Do not place your application dependencies here - classpath "org.jacoco:org.jacoco.core:$jacocoVersion" + classpath "org.jacoco:org.jacoco.core:$jacoco_version" } } apply plugin: 'io.github.gradle-nexus.publish-plugin' apply from: "${rootDir}/scripts/publish-root.gradle" -task clean(type: Delete) { +tasks.register('clean', Delete) { delete rootProject.buildDir } \ No newline at end of file diff --git a/contentstack/build.gradle b/contentstack/build.gradle index 4077cbf1..c91cacea 100755 --- a/contentstack/build.gradle +++ b/contentstack/build.gradle @@ -1,61 +1,22 @@ apply plugin: 'com.android.library' apply plugin: 'jacoco' -ext { - PUBLISH_GROUP_ID = 'com.contentstack.sdk' - PUBLISH_ARTIFACT_ID = 'android' - PUBLISH_VERSION = '3.11.0' - PUBLISH_DESCRIPTION = 'The Content Delivery SDK is used to retrieve content from your Contentstack account and deliver it to your web or mobile properties.' - PUBLISH_URL = 'https://github.com/contentstack/contentstack-android' - PUBLISH_LICENSE_NAME = 'MIT License' - PUBLISH_LICENSE_URL = 'https://github.com/contentstack/contentstack-android/blob/master/LICENSE' - PUBLISH_DEVELOPER_ID = 'ishaileshmishra' - PUBLISH_DEVELOPER_NAME = 'Shailesh Mishra' - PUBLISH_DEVELOPER_EMAIL = 'shailesh.mishra@contentstack.com' - PUBLISH_SCM_CONNECTION = 'scm:git@github.com:contentstack/contentstack-android' - PUBLISH_SCM_DEVELOPER_CONNECTION = 'scm:git@github.com:contentstack/contentstack-android' - PUBLISH_SCM_URL = 'https://github.com/contentstack/contentstack-android/tree/master' -} - apply from: "${rootProject.projectDir}/scripts/publish-module.gradle" -def localProperties = new Properties() -localProperties.load(new FileInputStream(rootProject.file("local.properties"))) - android { - compileSdkVersion 33 compileSdk 33 - buildToolsVersion '30.0.2' - defaultConfig { - minSdkVersion 19 + minSdk 19 + targetSdk 33 versionCode 1 - versionName "1.0.0" + versionName "1.0" + multiDexEnabled true + vectorDrawables.useSupportLibrary = true testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { - debug { - debuggable true - testCoverageEnabled true - buildConfigField "String", "host", localProperties['host'] - buildConfigField "String", "APIKey", localProperties['APIKey'] - buildConfigField "String", "deliveryToken", localProperties['deliveryToken'] - buildConfigField "String", "environment", localProperties['env'] - buildConfigField "String", "contentTypeUID", localProperties['contentType'] - buildConfigField "String", "assetUID", localProperties['assetUid'] - } - - release { - minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' - buildConfigField "String", "host", localProperties['host'] - buildConfigField "String", "APIKey", localProperties['APIKey'] - buildConfigField "String", "deliveryToken", localProperties['deliveryToken'] - buildConfigField "String", "environment", localProperties['env'] - buildConfigField "String", "contentTypeUID", localProperties['contentType'] - buildConfigField "String", "assetUID", localProperties['assetUid'] - proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' - } + def localProperties = new Properties() + localProperties.load(new FileInputStream(rootProject.file("local.properties"))) } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 @@ -74,12 +35,14 @@ android { dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) - //testImplementation 'junit:junit:5.9.2' - // https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.2' implementation 'androidx.appcompat:appcompat:1.6.1' implementation 'com.android.volley:volley:1.2.1' - androidTestImplementation 'androidx.test:core:1.5.0' - androidTestImplementation "androidx.test:runner:1.5.2" - androidTestImplementation "androidx.test:rules:1.5.0" + implementation 'androidx.test:core:1.5.0' + testImplementation 'junit:junit:4.13.2' + androidTestImplementation 'androidx.test.ext:junit:1.1.5' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' +} +java { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 } \ No newline at end of file diff --git a/contentstack/src/androidTest/java/com/contentstack/sdk/AssetTestCase.java b/contentstack/src/androidTest/java/com/contentstack/sdk/AssetTestCase.java deleted file mode 100644 index fb82ca09..00000000 --- a/contentstack/src/androidTest/java/com/contentstack/sdk/AssetTestCase.java +++ /dev/null @@ -1,180 +0,0 @@ -package com.contentstack.sdk; - -import static junit.framework.Assert.assertTrue; -import static junit.framework.TestCase.assertEquals; - -import android.content.Context; -import android.util.Log; - -import androidx.test.core.app.ApplicationProvider; - -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; - -import java.util.List; - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class AssetTestCase { - - private final String TAG = AssetTestCase.class.getSimpleName(); - private static String assetUid = BuildConfig.assetUID; - private static Stack stack; - - @BeforeClass - public static void oneTimeSetUp() throws Exception { - Context context = ApplicationProvider.getApplicationContext(); - - Config config = new Config(); - String DEFAULT_API_KEY = BuildConfig.APIKey; - String DEFAULT_DELIVERY_TOKEN = BuildConfig.deliveryToken; - String DEFAULT_ENV = BuildConfig.environment; - String DEFAULT_HOST = BuildConfig.host; - config.setHost(DEFAULT_HOST); - stack = Contentstack.stack(context, DEFAULT_API_KEY, DEFAULT_DELIVERY_TOKEN, DEFAULT_ENV, config); - } - - - @Test() - public void test_A_getAllAssetsToSetAssetUID() { - final AssetLibrary assetLibrary = stack.assetLibrary(); - assetLibrary.fetchAll(new FetchAssetsCallback() { - @Override - public void onCompletion(ResponseType responseType, List assets, Error error) { - if (error == null) { - Log.d(TAG, "response: " + assets.get(0).getAssetUid()); - assetUid = assets.get(0).getAssetUid(); - Log.e(assetUid, assetUid); - } - } - }); - - } - - @Test - public void test_B_VerifyAssetUID() { - - final Asset asset = stack.asset(assetUid); - asset.fetch(new FetchResultCallback() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - // Success Block. - Log.d(TAG, "response: " + asset.getAssetUid()); - assertEquals(assetUid, asset.getAssetUid()); - } - } - }); - } - - @Test - public void test_C_Asset_fetch() { - final Asset asset = stack.asset(assetUid); - asset.fetch(new FetchResultCallback() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - assertEquals(BuildConfig.assetUID, asset.getAssetUid()); - assertEquals("image/jpeg", asset.getFileType()); - assertEquals("phoenix2.jpg", asset.getFileName()); - assertEquals("482141", asset.getFileSize()); - } else { - assertEquals(105, error.getErrorCode()); - } - } - }); - } - - @Test - public void test_D_AssetLibrary_fetch() { - final AssetLibrary assetLibrary = stack.assetLibrary(); - assetLibrary.fetchAll(new FetchAssetsCallback() { - @Override - public void onCompletion(ResponseType responseType, List assets, Error error) { - if (error == null) { - assets.forEach(asset -> { - Log.d(TAG, "----Test--Asset-D--Success----" + asset.toJSON()); - Log.d(TAG, "----Test--Asset-D--Success----" + asset.getFileType()); - Log.d(TAG, "----Test--Asset-D--Success----" + asset.getCreatedBy()); - Log.d(TAG, "----Test--Asset-D--Success----" + asset.getUpdatedBy()); - Log.d(TAG, "----Test--Asset-D--Success----" + asset.getFileName()); - Log.d(TAG, "----Test--Asset-D--Success----" + asset.getFileSize()); - Log.d(TAG, "----Test--Asset-D--Success----" + asset.getAssetUid()); - Log.d(TAG, "----Test--Asset-D--Success----" + asset.getUrl()); - }); - } - } - }); - } - - @Test - public void test_E_AssetLibrary_includeCount_fetch() { - final AssetLibrary assetLibrary = stack.assetLibrary(); - assetLibrary.includeCount(); - assetLibrary.fetchAll(new FetchAssetsCallback() { - @Override - public void onCompletion(ResponseType responseType, List assets, Error error) { - if (error == null) { - assertEquals(16, assetLibrary.getCount()); - } - } - }); - } - - @Test - public void test_F_AssetLibrary_includeRelativeUrl_fetch() { - final AssetLibrary assetLibrary = stack.assetLibrary(); - assetLibrary.includeRelativeUrl(); - assetLibrary.fetchAll(new FetchAssetsCallback() { - public void onCompletion(ResponseType responseType, List assets, Error error) { - if (error == null) { - assertTrue(assets.get(0).getUrl().contains("phoenix2.jpg")); - } - } - }); - } - - @Test - public void test_G_Include_Dimension() { - final Asset asset = stack.asset(assetUid); - asset.includeDimension().fetch(new FetchResultCallback() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - Log.d(TAG, asset.getAssetUid()); - assertEquals(assetUid, asset.getAssetUid()); - } - } - }); - } - - - @Test - public void test_H_include_fallback() { - final Asset asset = stack.asset(assetUid); - asset.includeFallback().fetch(new FetchResultCallback() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - Log.d(TAG, asset.getAssetUid()); - assertEquals(assetUid, asset.getAssetUid()); - } - } - }); - } - - @Test - public void test_AZURE_NA() throws Exception { - Config config = new Config(); - String DEFAULT_API_KEY = BuildConfig.APIKey; - String DEFAULT_DELIVERY_TOKEN = BuildConfig.deliveryToken; - String DEFAULT_ENV = BuildConfig.environment; - String DEFAULT_HOST = BuildConfig.host; - config.setHost(DEFAULT_HOST); - config.setRegion(Config.ContentstackRegion.AZURE_NA); - Context appContext = ApplicationProvider.getApplicationContext(); - stack = Contentstack.stack(appContext, DEFAULT_API_KEY, DEFAULT_DELIVERY_TOKEN, DEFAULT_ENV, config); - } - -} diff --git a/contentstack/src/androidTest/java/com/contentstack/sdk/EntryTestCase.java b/contentstack/src/androidTest/java/com/contentstack/sdk/EntryTestCase.java deleted file mode 100644 index dc1fb492..00000000 --- a/contentstack/src/androidTest/java/com/contentstack/sdk/EntryTestCase.java +++ /dev/null @@ -1,334 +0,0 @@ -package com.contentstack.sdk; - -import android.content.Context; -import android.util.Log; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.*; -import org.junit.runners.MethodSorters; - -import java.util.ArrayList; -import java.util.concurrent.CountDownLatch; - -import static junit.framework.TestCase.*; - -import androidx.test.core.app.ApplicationProvider; - - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class EntryTestCase { - - private final static String TAG = EntryTestCase.class.getSimpleName(); - private static String entryUID; - private static final String CONTENT_TYPE_UID = BuildConfig.contentTypeUID; - private static CountDownLatch latch; - private static Stack stack; - - - @BeforeClass - public static void oneTimeSetUp() throws Exception { - Context appContext = ApplicationProvider.getApplicationContext(); - Config config = new Config(); - String DEFAULT_HOST = BuildConfig.host; - config.setHost(DEFAULT_HOST); - stack = Contentstack.stack(appContext, BuildConfig.APIKey, BuildConfig.deliveryToken, BuildConfig.environment, config); - - latch = new CountDownLatch(1); - Log.d(TAG, "test started..."); - } - - @AfterClass - public static void oneTimeTearDown() { - // one-time cleanup code - Log.d(TAG, "When all the test cases of class finishes..."); - Log.d(TAG, "Total testcase: " + latch.getCount()); - } - - /** - * Sets up the test fixture. - * (Called before every test case method.) - */ - @Before - public void setUp() { - latch = new CountDownLatch(1); - } - - - /** - * Tears down the test fixture. - * (Called after every test case method.) - */ - @After - public void tearDown() { - Log.d(TAG, "Runs after every testcase completes."); - latch.countDown(); - } - - - @Test - public void testCustomHeader() { - final Query query = stack.contentType(CONTENT_TYPE_UID).query(); - query.setHeader("customHeaderKey", "customHeaderValue"); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - entryUID = queryresult.getResultObjects().get(15).getUid(); - } - } - }); - } - - @Test - public void test_01_findAllEntries() { - final Query query = stack.contentType(CONTENT_TYPE_UID).query(); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - entryUID = queryresult.getResultObjects().get(15).getUid(); - } - } - }); - } - - @Test - public void test_02_only_fetch() { - final Entry entry = stack.contentType(CONTENT_TYPE_UID).entry(entryUID); - entry.only(new String[]{"price"}); - entry.fetch(new EntryResultCallBack() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - assertEquals(786, entry.toJSON().opt("price")); - } - } - }); - } - - @Test - public void test_03_except_fetch() { - final Entry entry = stack.contentType(CONTENT_TYPE_UID).entry(entryUID); - entry.except(new String[]{"title"}); - entry.fetch(new EntryResultCallBack() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - Log.e(TAG, entry.toJSON().optString("title")); - } else { - Log.e(TAG, error.getErrorMessage()); - } - } - }); - } - - @Test - public void test_04_includeReference_fetch() { - final Entry entry = stack.contentType(CONTENT_TYPE_UID).entry(entryUID); - entry.includeReference("category"); - entry.fetch(new EntryResultCallBack() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - JSONArray categoryArray = entry.getJSONArray("category"); - - try { - for (int index = 0; index < categoryArray.length(); index++) { - JSONObject array = (JSONObject) categoryArray.get(index); - assertTrue(array.toString().contains("_content_type_uid")); - } - } catch (Exception e) { - Log.e(TAG, e.getLocalizedMessage()); - } - - } - } - }); - } - - @Test - public void test_05_includeReferenceOnly_fetch() { - final Entry entry = stack.contentType(CONTENT_TYPE_UID).entry(entryUID); - ArrayList strings = new ArrayList<>(); - strings.add("title"); - strings.add("orange"); - strings.add("mango"); - entry.onlyWithReferenceUid(strings, "category"); - entry.fetch(new EntryResultCallBack() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - assertEquals("laptop", entry.toJSON().optString("title")); - } - } - }); - - } - - - @Test - public void test_06_includeReferenceExcept_fetch() throws InterruptedException { - final Entry entry = stack.contentType(CONTENT_TYPE_UID).entry(entryUID); - ArrayList strings = new ArrayList<>(); - strings.add("color"); - strings.add("price_in_usd"); - entry.exceptWithReferenceUid(strings, "category"); - entry.fetch(new EntryResultCallBack() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - latch.countDown(); - } else { - latch.countDown(); - } - - } - }); - latch.await(); - - } - - - @Test - public void test_07_getMarkdown_fetch() throws InterruptedException { - - final Entry entry = stack.contentType("user").entry(entryUID); - entry.fetch(new EntryResultCallBack() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - latch.countDown(); - } else { - latch.countDown(); - } - } - }); - latch.await(); - } - - - @Test - public void test_08_get() throws InterruptedException { - final Entry entry = stack.contentType("user").entry(entryUID); - entry.fetch(new EntryResultCallBack() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - latch.countDown(); - } else { - latch.countDown(); - } - } - }); - latch.await(); - } - - - @Test - public void test_09_getParam() throws InterruptedException { - final Entry entry = stack.contentType("user").entry(entryUID); - entry.addParam("include_dimensions", "true"); - entry.fetch(new EntryResultCallBack() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - latch.countDown(); - } else { - latch.countDown(); - } - } - }); - latch.await(); - } - - - @Test - public void test_10_IncludeReferenceContentTypeUID() throws InterruptedException { - final Entry entry = stack.contentType("user").entry(entryUID); - entry.includeReferenceContentTypeUID(); - entry.fetch(new EntryResultCallBack() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - JSONObject jsonResult = entry.toJSON(); - try { - JSONArray cartList = (JSONArray) jsonResult.get("cart"); - Object whatTYPE = cartList.get(0); - if (whatTYPE instanceof JSONObject) { - assertTrue(true); - } - } catch (JSONException e) { - Log.e(TAG, e.getLocalizedMessage()); - } - latch.countDown(); - } else { - latch.countDown(); - } - } - }); - latch.await(); - - } - - - @Test - public void test_11_Locale() throws InterruptedException { - final Entry entry = stack.contentType("user").entry(entryUID); - entry.fetch(new EntryResultCallBack() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - String checkResp = entry.getLocale(); - Log.e(TAG, checkResp); - latch.countDown(); - } else { - latch.countDown(); - } - - } - }); - latch.await(); - } - - @Test - public void test_12_entry_except() throws InterruptedException { - final Entry entry = stack.contentType("user").entry(entryUID); - String[] allValues = {"color", "price_in_usd"}; - entry.except(allValues); - entry.fetch(new EntryResultCallBack() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - String checkResp = entry.getLocale(); - Log.d(TAG, checkResp); - latch.countDown(); - } else { - latch.countDown(); - } - } - }); - latch.await(); - } - - @Test - public void test_13_entry_include_embedded_items_unit_test() throws InterruptedException { - - final Entry entry = stack.contentType("user").entry(entryUID); - entry.includeEmbeddedItems().fetch(new EntryResultCallBack() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - String checkResp = entry.getLocale(); - Log.d(TAG, checkResp); - } - boolean hasEmbeddedItemKey = entry.otherPostJSON.has("include_embedded_items[]"); - Assert.assertTrue(hasEmbeddedItemKey); - latch.countDown(); - } - }); - latch.await(); - } - -} diff --git a/contentstack/src/androidTest/java/com/contentstack/sdk/ExampleInstrumentedTest.java b/contentstack/src/androidTest/java/com/contentstack/sdk/ExampleInstrumentedTest.java new file mode 100644 index 00000000..b6c7c4e9 --- /dev/null +++ b/contentstack/src/androidTest/java/com/contentstack/sdk/ExampleInstrumentedTest.java @@ -0,0 +1,75 @@ +package com.contentstack.sdk; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import android.content.Context; + +import androidx.test.core.app.ApplicationProvider; +import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.util.Date; + + +@RunWith(AndroidJUnit4ClassRunner.class) +public class ExampleInstrumentedTest { + + static final String apiKey = BuildConfig.APIKey; + static final String deliveryToken = BuildConfig.deliveryToken; + static final String environment = BuildConfig.environment; + static Stack stack = null; + + + @Test + public void useAppContext() throws Exception { + Context ctx = ApplicationProvider.getApplicationContext(); + stack = Contentstack.stack(ctx, apiKey, deliveryToken, environment); + assertEquals("com.contentstack.sdk.test", ctx.getPackageName().toLowerCase()); + } + + @Test + public void testAPINotNull() { + assertNotNull(apiKey); + } + + @Test + public void testDeliveryTokenNotNull() { + assertNotNull(deliveryToken); + } + + @Test + public void testEnvironmentNotNull() { + assertNotNull(environment); + } + + @Test + public void initSDK() { + stack.sync(null); + assertNotNull(stack.syncParams); + } + + @Test + public void syncLocale() { + stack.syncLocale("ar-eu", new SyncResultCallBack() { + @Override + public void onCompletion(SyncStack syncStack, Error error) { + + } + }); + assertNotNull(stack.syncParams); + } + + + @Test + public void syncSDKWIthAllParams() { + stack.sync("content_type", new Date(), "en-us", Stack.PublishType.ENTRY_PUBLISHED, new SyncResultCallBack() { + @Override + public void onCompletion(SyncStack syncStack, Error error) { + + } + }); + assertNotNull(stack.syncParams); + } +} \ No newline at end of file diff --git a/contentstack/src/androidTest/java/com/contentstack/sdk/QueryTestCase.java b/contentstack/src/androidTest/java/com/contentstack/sdk/QueryTestCase.java deleted file mode 100644 index d5217610..00000000 --- a/contentstack/src/androidTest/java/com/contentstack/sdk/QueryTestCase.java +++ /dev/null @@ -1,654 +0,0 @@ -package com.contentstack.sdk; - -import android.content.Context; -import android.util.Log; - -import org.json.JSONArray; -import org.json.JSONObject; -import org.junit.*; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import static junit.framework.TestCase.assertEquals; - -import androidx.test.core.app.ApplicationProvider; - - -public class QueryTestCase { - - private static final String TAG = AssetTestCase.class.getSimpleName(); - private static Stack stack; - private static Query query; - private static final String contentTypeUID = BuildConfig.contentTypeUID; - - @BeforeClass - public static void oneTimeSetUp() throws Exception { - Context appContext = ApplicationProvider.getApplicationContext(); - Config config = new Config(); - String DEFAULT_API_KEY = BuildConfig.APIKey; - String DEFAULT_DELIVERY_TOKEN = BuildConfig.deliveryToken; - String DEFAULT_ENV = BuildConfig.environment; - String DEFAULT_HOST = BuildConfig.host; - config.setHost(DEFAULT_HOST); - stack = Contentstack.stack(appContext, DEFAULT_API_KEY, DEFAULT_DELIVERY_TOKEN, DEFAULT_ENV, config); - query = stack.contentType(contentTypeUID).query(); - } - - - /** - * Sets up the test fixture. - * (Called before every test case method.) - */ - @Before - public void setUp() { - query = stack.contentType(contentTypeUID).query(); - } - - - @Test - public void test_01_fetchAllEntries() { - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List listOfEntries = queryresult.getResultObjects(); - } - } - }); - } - - @Test() - public void test_03_fetchSingleNonExistingEntry() { - Query query = stack.contentType("categories").query(); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List listOfEntries = queryresult.getResultObjects(); - } - } - }); - } - - @Test - public void test_04_fetchEntryWithIncludeReference() { - query.includeReference("category"); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List listOfEntries = queryresult.getResultObjects(); - } - } - }); - } - - - @Test - public void test_05_fetchEntryNotContainedInField() { - String[] containArray = new String[]{"Roti Maker", "kids dress"}; - query.notContainedIn("title", containArray); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - - if (error == null) { - List entries = queryresult.getResultObjects(); - int price = entries.get(0).toJSON().optInt("price"); - assertEquals(45, price); - } - } - }); - } - - - @Test - public void test_07_fetchEntryNotEqualToField() { - query.notEqualTo("title", "yellow t shirt"); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List entries = queryresult.getResultObjects(); - entries.forEach(entry -> Log.i(TAG, entry.getString("title"))); - } - } - }); - } - - - @Test - public void test_08_fetchEntryGreaterThanEqualToField() { - query.greaterThanOrEqualTo("price", 90); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List entries = queryresult.getResultObjects(); - entries.forEach(entry -> { - //og.i(TAG,entry.getString("price")); - }); - } - } - }); - } - - - @Test - public void test_09_fetchEntryGreaterThanField() { - query.greaterThan("price", 90); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List entries = queryresult.getResultObjects(); - entries.forEach(entry -> { - //Log.i(TAG,entry.getString("price"); - }); - } - } - }); - } - - - @Test - public void test_10_fetchEntryLessThanEqualField() { - query.lessThanOrEqualTo("price", 90); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List entries = queryresult.getResultObjects(); - int price = entries.get(0).toJSON().optInt("price"); - assertEquals(45, price); - } - } - }); - } - - - @Test - public void test_11_fetchEntryLessThanField() { - query.lessThan("price", "90"); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List resp = queryresult.getResultObjects(); - resp.forEach(entry -> { - Log.i(TAG, "Is price less than 90..? " + entry.get("price")); - }); - } - } - }); - } - - - @Test - public void test_12_fetchEntriesWithOr() { - - ContentType ct = stack.contentType(contentTypeUID); - Query orQuery = ct.query(); - - Query query = ct.query(); - query.lessThan("price", 90); - - Query subQuery = ct.query(); - subQuery.containedIn("discount", new Integer[]{20, 45}); - - ArrayList array = new ArrayList(); - array.add(query); - array.add(subQuery); - orQuery.or(array); - - orQuery.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List listOfEntries = queryresult.getResultObjects(); - } - } - }); - } - - - @Test - public void test_13_fetchEntriesWithAnd() { - - ContentType ct = stack.contentType(contentTypeUID); - Query orQuery = ct.query(); - - Query query = ct.query(); - query.lessThan("price", 90); - - Query subQuery = ct.query(); - subQuery.containedIn("discount", new Integer[]{20, 45}); - - ArrayList array = new ArrayList(); - array.add(query); - array.add(subQuery); - - orQuery.and(array); - orQuery.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List listOfEntries = queryresult.getResultObjects(); - } - } - }); - } - - - @Test - public void test_14_addQuery() { - query.addQuery("limit", "8"); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List listOfEntries = queryresult.getResultObjects(); - } - } - }); - } - - - @Test - public void test_15_removeQueryFromQuery() { - query.addQuery("limit", "8"); - query.removeQuery("limit"); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List listOfEntries = queryresult.getResultObjects(); - } - } - }); - } - - - @Test - public void test_16_includeSchema() { - query.includeContentType(); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - JSONObject contentTypeObj = queryresult.getContentType(); - } - } - }); - } - - - @Test - public void test_17_search() { - query.search("dress"); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List entries = queryresult.getResultObjects(); - for (Entry entry : entries) { - JSONObject jsonObject = entry.toJSON(); - Iterator iter = jsonObject.keys(); - while (iter.hasNext()) { - String key = iter.next(); - try { - Object value = jsonObject.opt(key); - if (value instanceof String && ((String) value).contains("dress")) - Log.i(TAG, value.toString()); - } catch (Exception e) { - Log.i(TAG, "----------------setQueryJson" + e.toString()); - } - } - } - } - } - }); - } - - - @Test - public void test_18_ascending() { - query.ascending("title"); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List entries = queryresult.getResultObjects(); - for (Entry entry : entries) { - Log.i(TAG, entry.getString("title")); - } - } - } - }); - } - - - @Test - public void test_19_descending() { - query.descending("title"); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List entries = queryresult.getResultObjects(); - for (Entry entry : entries) { - Log.i(TAG, entry.getString("title")); - } - } - } - }); - } - - - @Test - public void test_20_limit() { - query.limit(3); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List entries = queryresult.getResultObjects(); - for (Entry entry : entries) { - Log.i(TAG, " entry = [" + entry.getString("title") + "]"); - } - } - } - }); - } - - - @Test - public void test_21_skip() { - query.skip(3); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List entries = queryresult.getResultObjects(); - } - } - }); - } - - - @Test - public void test_22_only() { - query.only(new String[]{"price"}); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List entries = queryresult.getResultObjects(); - } - } - }); - } - - - @Test - public void test_23_except() { - query.locale("en-eu"); - query.except(new String[]{"price", "chutiya"}); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List entries = queryresult.getResultObjects(); - } - } - }); - } - - - @Test - public void test_24_count() { - query.count(); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - int count = queryresult.getCount(); - } - } - }); - } - - - @Test - public void test_25_regex() { - query.regex("title", "lap*", "i"); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List entries = queryresult.getResultObjects(); - } - } - }); - } - - - @Test - public void test_26_exist() { - query.exists("title"); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List entries = queryresult.getResultObjects(); - } - } - }); - } - - - @Test - public void test_27_notExist() { - query.notExists("price1"); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - int entryCount = queryresult.getCount(); - } - } - }); - - - } - - - @Test - public void test_28_tags() { - query.tags(new String[]{"pink"}); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List entries = queryresult.getResultObjects(); - } - } - }); - - - } - - - @Test - public void test_29_language() { - query.language(Language.ENGLISH_UNITED_KINGDOM); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List entries = queryresult.getResultObjects(); - } - } - }); - - - } - - - @Test - public void test_33_findOne() { - query.includeCount(); - query.where("in_stock", true); - query.findOne(new SingleQueryResultCallback() { - @Override - public void onCompletion(ResponseType responseType, Entry entry, Error error) { - if (error == null) { - System.out.println("entry: " + entry); - } - } - }); - } - - - @Test - public void test_34_complexFind() { - query.notEqualTo("title", "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.*************************************Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.*************************************Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.*************************************Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.*************************************Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.************************************Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.************************************Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.************************************Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.************************************Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.************************************Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.************************************Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.************************************Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.************************************Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.*******"); - query.includeCount(); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - List entries = queryresult.getResultObjects(); - } - } - }); - } - - - @Test - public void test_35_includeSchema() { - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - JSONArray result; - if (error == null) { - result = queryresult.getSchema(); - } - } - }); - } - - - @Test - public void test_36_includeContentType() { - query.includeContentType(); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - JSONObject entries = queryresult.getContentType(); - } - } - }); - } - - - @Test - public void test_38_include_content_type() { - query.includeContentType(); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - JSONObject result; - if (error == null) { - result = queryresult.getContentType(); - } - } - }); - } - - - @Test - public void test_39_include_content_type() { - query.includeContentType(); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - JSONObject entries = queryresult.getContentType(); - } - } - }); - } - - - @Test - public void test_40_WithoutIncludeFallback() { - Query fallbackQuery = stack.contentType("categories").query(); - fallbackQuery.locale("hi-in"); - fallbackQuery.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - assertEquals(0, queryresult.getResultObjects().size()); - fallbackQuery.includeFallback().locale("hi-in"); - fallbackQuery.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - assertEquals(0, queryresult.getResultObjects().size()); - } - }); - } - } - }); - } - - @Test - public void test_40_WithIncludeFallback() { - Query fallbackQuery = stack.contentType("categories").query(); - fallbackQuery.locale("hi-in"); - fallbackQuery.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - assertEquals(0, queryresult.getResultObjects().size()); - } - } - }); - } - - - @Test - public void test_41_entry_include_embedded_items_unit_test() { - - final Query query = stack.contentType("user").query(); - query.includeEmbeddedItems().find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - Entry checkResp = queryresult.getResultObjects().get(0); - Log.d(TAG, checkResp.toString()); - } - } - }); - } - - - @Test - public void query_include_embedded_items_unit_test() throws Exception { - final Query query = stack.contentType("testembededobjects").query(); - query.includeEmbeddedItems().find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - Entry checkResp = queryresult.getResultObjects().get(0); - Log.d(TAG, queryresult.getResultObjects().toString()); - } - } - }); - } - - -} \ No newline at end of file diff --git a/contentstack/src/androidTest/java/com/contentstack/sdk/TransformTestcase.java b/contentstack/src/androidTest/java/com/contentstack/sdk/TransformTestcase.java deleted file mode 100644 index 7e60cfcb..00000000 --- a/contentstack/src/androidTest/java/com/contentstack/sdk/TransformTestcase.java +++ /dev/null @@ -1,240 +0,0 @@ -package com.contentstack.sdk; - -import android.content.Context; -import android.util.Log; - -import androidx.test.core.app.ApplicationProvider; - -import org.junit.*; - -import java.util.LinkedHashMap; -import java.util.concurrent.CountDownLatch; - - -/** - * - */ -public class TransformTestcase { - - static final String TAG = TransformTestcase.class.getSimpleName(); - private static CountDownLatch latch; - private static Stack stack; - private final LinkedHashMap imageParams = new LinkedHashMap<>(); - private final String IMAGE_URL = "https://images.contentstack.io/v3/assets/download"; - - - @BeforeClass - public static void oneTimeSetUp() throws Exception { - Context appContext = ApplicationProvider.getApplicationContext(); - - Config config = new Config(); - String DEFAULT_API_KEY = BuildConfig.APIKey; - String DEFAULT_DELIVERY_TOKEN = BuildConfig.deliveryToken; - String DEFAULT_ENV = BuildConfig.environment; - String DEFAULT_HOST = BuildConfig.host; - config.setHost(DEFAULT_HOST); - stack = Contentstack.stack(appContext, DEFAULT_API_KEY, DEFAULT_DELIVERY_TOKEN, DEFAULT_ENV, config); - - latch = new CountDownLatch(1); - } - - @Before - public void setUp() { - latch = new CountDownLatch(1); - } - - - @Test - public void test_00_fetchAllImageTransformation() { - - imageParams.put("auto", "webp"); - imageParams.put("quality", 200); - imageParams.put("width", 100); - imageParams.put("height", 50); - imageParams.put("format", "png"); - imageParams.put("crop", "3:5"); - imageParams.put("trim", "20,20,20,20"); - imageParams.put("disable", "upscale"); - imageParams.put("pad", "10,10,10,10"); - imageParams.put("bg-color", "#FFFFFF"); - imageParams.put("dpr", 20); - imageParams.put("canvas", "3:5"); - imageParams.put("orient", "l"); - - String image_url = stack.ImageTransform(IMAGE_URL, imageParams); - int counter = 0; - if (image_url.contains("?")) { - String[] imgKeys = image_url.split("\\?"); - String rightUrl = imgKeys[1]; - String[] getAllPairs = rightUrl.split("\\&"); - counter = 0; - if (imageParams.size() > 0) { - for (int i = 0; i < imageParams.size(); i++) { - String keyValueParis = getAllPairs[i]; - Log.i(TAG, "pairs:--> " + keyValueParis); - ++counter; - } - } - } else { - try { - latch.await(); - } catch (Exception e) { - Log.i(TAG, "---------------||" + e.toString()); - } - } - - if (counter == imageParams.size()) { - latch.countDown(); - Log.i(TAG, "Testcases Passed"); - } else { - Log.i(TAG, "Testcases Failed"); - try { - latch.await(); - } catch (Exception e) { - Log.i(TAG, "---------------||" + e.toString()); - } - } - } - - - @Test - public void test_01_fetchAllImageTransformation() { - - imageParams.put("auto", "webp"); - imageParams.put("quality", 200); - imageParams.put("width", 100); - imageParams.put("height", 50); - imageParams.put("format", "png"); - imageParams.put("crop", "3:5"); - - String image_url = stack.ImageTransform(IMAGE_URL, imageParams); - int counter = 0; - /* check url contains "?" */ - if (image_url.contains("?")) { - String[] imgKeys = image_url.split("\\?"); - String rightUrl = imgKeys[1]; - String[] getAllPairs = rightUrl.split("\\&"); - counter = 0; - if (imageParams.size() > 0) { - for (int i = 0; i < imageParams.size(); i++) { - String keyValueParis = getAllPairs[i]; - Log.i(TAG, "pairs:--> " + keyValueParis); - ++counter; - } - } - } else { - Log.i(TAG, "Testcases Failed"); - try { - latch.await(); - } catch (Exception e) { - Log.i(TAG, "---------------||" + e.toString()); - } - } - - if (counter == imageParams.size()) { - latch.countDown(); - Log.i(TAG, "Testcases Passed"); - } else { - Log.i(TAG, "Testcases Failed"); - try { - latch.await(); - } catch (Exception e) { - Log.i(TAG, "---------------||" + e.toString()); - } - } - } - - - @Test - public void test_02_fetchAllImageTransformation() { - imageParams.put("trim", "20,20,20,20"); - imageParams.put("disable", "upscale"); - imageParams.put("pad", "10,10,10,10"); - imageParams.put("bg-color", "#FFFFFF"); - imageParams.put("dpr", 20); - imageParams.put("canvas", "3:5"); - imageParams.put("orient", "l"); - String image_url = stack.ImageTransform(IMAGE_URL, imageParams); - int counter = 0; - /* check url contains "?" */ - if (!image_url.equalsIgnoreCase("") && image_url.contains("?")) { - String[] imgKeys = image_url.split("\\?"); - String rightUrl = imgKeys[1]; - String[] getAllPairs = rightUrl.split("\\&"); - counter = 0; - if (imageParams.size() > 0) { - for (int i = 0; i < imageParams.size(); i++) { - String keyValueParis = getAllPairs[i]; - Log.i(TAG, "pairs:--> " + keyValueParis); - ++counter; - } - } - } else { - Log.i(TAG, "Testcases Failed"); - try { - latch.await(); - } catch (Exception e) { - Log.i(TAG, "---------------||" + e.toString()); - } - } - - if (counter == imageParams.size()) { - latch.countDown(); - Log.i(TAG, "Testcases Passed"); - } else { - Log.i(TAG, "Testcases Failed"); - try { - latch.await(); - } catch (Exception e) { - Log.i(TAG, "---------------||" + e.toString()); - } - } - } - - - @Test - public void test_03_fetchAllImageTransformation() { - - - imageParams.put("trim", "20,20,20,20"); - imageParams.put("disable", "upscale"); - imageParams.put("canvas", "3:5"); - imageParams.put("orient", "l"); - - String image_url = stack.ImageTransform(IMAGE_URL, imageParams); - int counter = 0; - /* check url contains "?" */ - if (image_url.contains("?")) { - String[] imgKeys = image_url.split("\\?"); - String rightUrl = imgKeys[1]; - String[] getAllPairs = rightUrl.split("\\&"); - counter = 0; - if (imageParams.size() > 0) { - for (int i = 0; i < imageParams.size(); i++) { - String keyValueParis = getAllPairs[i]; - Log.i(TAG, "pairs:--> " + keyValueParis); - ++counter; - } - } - } else { - Log.i(TAG, "Testcases Failed"); - try { - latch.await(); - } catch (Exception e) { - Log.i(TAG, "---------------||" + e.toString()); - } - } - - if (counter == imageParams.size()) { - latch.countDown(); - Log.i(TAG, "Testcases Passed"); - } else { - Log.i(TAG, "Testcases Failed"); - try { - latch.await(); - } catch (Exception e) { - Log.i(TAG, "---------------||" + e.toString()); - } - } - } -} diff --git a/contentstack/src/azure-eu/java/AzureEUTest.java b/contentstack/src/azure-eu/java/AzureEUTest.java new file mode 100644 index 00000000..00821f86 --- /dev/null +++ b/contentstack/src/azure-eu/java/AzureEUTest.java @@ -0,0 +1,20 @@ +package com.contentstack.sdk; + +import static org.junit.Assert.assertEquals; + +import android.content.Context; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.test.platform.app.InstrumentationRegistry; + +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + @Test + public void useAppContext() { + Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); + assertEquals("com.shaileshmishra.myapplication", appContext.getPackageName()); + } +} \ No newline at end of file diff --git a/contentstack/src/azure-na/java/AzureNATest.java b/contentstack/src/azure-na/java/AzureNATest.java new file mode 100644 index 00000000..00821f86 --- /dev/null +++ b/contentstack/src/azure-na/java/AzureNATest.java @@ -0,0 +1,20 @@ +package com.contentstack.sdk; + +import static org.junit.Assert.assertEquals; + +import android.content.Context; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.test.platform.app.InstrumentationRegistry; + +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + @Test + public void useAppContext() { + Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); + assertEquals("com.shaileshmishra.myapplication", appContext.getPackageName()); + } +} \ No newline at end of file diff --git a/contentstack/src/eu/java/EUInstrumentedTest.java b/contentstack/src/eu/java/EUInstrumentedTest.java new file mode 100644 index 00000000..00821f86 --- /dev/null +++ b/contentstack/src/eu/java/EUInstrumentedTest.java @@ -0,0 +1,20 @@ +package com.contentstack.sdk; + +import static org.junit.Assert.assertEquals; + +import android.content.Context; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.test.platform.app.InstrumentationRegistry; + +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + @Test + public void useAppContext() { + Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); + assertEquals("com.shaileshmishra.myapplication", appContext.getPackageName()); + } +} \ No newline at end of file diff --git a/contentstack/src/main/AndroidManifest.xml b/contentstack/src/main/AndroidManifest.xml index 62a04f3d..d94c12f5 100755 --- a/contentstack/src/main/AndroidManifest.xml +++ b/contentstack/src/main/AndroidManifest.xml @@ -23,6 +23,13 @@ + + + - + \ No newline at end of file diff --git a/contentstack/src/main/java/com/contentstack/sdk/Asset.java b/contentstack/src/main/java/com/contentstack/sdk/Asset.java index 26c2173f..828e609d 100755 --- a/contentstack/src/main/java/com/contentstack/sdk/Asset.java +++ b/contentstack/src/main/java/com/contentstack/sdk/Asset.java @@ -4,11 +4,6 @@ import android.util.ArrayMap; import android.util.Log; -import com.contentstack.sdk.utilities.CSAppConstants; -import com.contentstack.sdk.utilities.CSAppUtils; -import com.contentstack.sdk.utilities.CSController; -import com.contentstack.sdk.utilities.ContentstackUtil; - import org.json.JSONException; import org.json.JSONObject; @@ -17,15 +12,16 @@ import java.util.HashMap; import java.util.Iterator; import java.util.Map; +import java.util.Objects; /** - * Asset class to fetch files details on Conentstack server. + * Asset class to fetch files details on Contentstack server. * * @author contentstack.com */ public class Asset { - private final static String TAG = "Asset"; + private final static String TAG = Asset.class.getSimpleName(); protected String assetUid = null; protected String contentType = null; protected String fileSize = null; @@ -34,28 +30,26 @@ public class Asset { protected JSONObject json = null; protected String[] tagsArray = null; JSONObject urlQueries = new JSONObject(); - protected ArrayMap headerGroup_app; - protected ArrayMap headerGroup_local; + protected ArrayMap headerGroupApp; + protected ArrayMap headerGroupLocal; protected Stack stackInstance; private CachePolicy cachePolicyForCall = CachePolicy.IGNORE_CACHE; - - private final long maxCacheTimeForCall = 0; - private final long defaultCacheTimeInterval = 0; + private final long MAX_CACHE_TIME_FOR_CALL = 0; protected Asset() { - this.headerGroup_local = new ArrayMap<>(); - this.headerGroup_app = new ArrayMap<>(); + this.headerGroupLocal = new ArrayMap<>(); + this.headerGroupApp = new ArrayMap<>(); } protected Asset(String assetUid) { this.assetUid = assetUid; - this.headerGroup_local = new ArrayMap<>(); - this.headerGroup_app = new ArrayMap<>(); + this.headerGroupLocal = new ArrayMap<>(); + this.headerGroupApp = new ArrayMap<>(); } protected void setStackInstance(Stack stack) { this.stackInstance = stack; - this.headerGroup_app = stack.localHeader; + this.headerGroupApp = stack.localHeader; } /** @@ -64,28 +58,26 @@ protected void setStackInstance(Stack stack) { * * @param jsonObject json object of particular file attached in the built object.
*

- * {@link Asset} can be generate using of data filled {@link Entry} and {@link #configure(JSONObject)}.
- * + * {@link Asset} can be generate using of data filled {@link Entry} + * and {@link #configure(JSONObject)}.
*

Example :
*
1. Single Attachment :-
*

      *                   assetObject.configure(entryObject.getJSONObject(attached_image_field_uid));
- * - *
2. Multiple Attachment :-
+ *
2. Multiple Attachment : *

*

      *                   for (int i = 0; i < array.length(); i++) {
* Asset assetObject = stack.asset("assetUid");
- * assetObject.configure(entryObject.getJSONObject(attached_image_field_uid));
+ * assetObject.configure(entryObject.getJSONObject(attached_image_field_uid)); * }
*
* @return {@link Asset} instance. */ public Asset configure(JSONObject jsonObject) { - AssetModel model = null; model = new AssetModel(jsonObject, true, false); this.contentType = model.contentType; @@ -115,10 +107,9 @@ public Asset configure(JSONObject jsonObject) { * */ public void setHeader(String key, String value) { - if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)) { removeHeader(key); - headerGroup_local.put(key, value); + headerGroupLocal.put(key, value); } } @@ -136,12 +127,9 @@ public void setHeader(String key, String value) { * */ public void removeHeader(String key) { - if (headerGroup_local != null) { - + if (headerGroupLocal != null) { if (!TextUtils.isEmpty(key)) { - if (headerGroup_local.containsKey(key)) { - headerGroup_local.remove(key); - } + headerGroupLocal.remove(key); } } } @@ -253,9 +241,9 @@ public Calendar getCreateAt() { try { String value = json.optString("created_at"); - return ContentstackUtil.parseDate(value, null); + return CSUtil.parseDate(value, null); } catch (Exception e) { - CSAppUtils.showLog(TAG, e.getLocalizedMessage()); + SDKUtil.showLog(TAG, e.getLocalizedMessage()); } return null; } @@ -286,9 +274,9 @@ public Calendar getUpdateAt() { try { String value = json.optString("updated_at"); - return ContentstackUtil.parseDate(value, null); + return CSUtil.parseDate(value, null); } catch (Exception e) { - CSAppUtils.showLog(TAG, e.getLocalizedMessage()); + SDKUtil.showLog(TAG, e.getLocalizedMessage()); } return null; } @@ -319,9 +307,9 @@ public Calendar getDeleteAt() { try { String value = json.optString("deleted_at"); - return ContentstackUtil.parseDate(value, null); + return CSUtil.parseDate(value, null); } catch (Exception e) { - CSAppUtils.showLog(TAG, e.getLocalizedMessage()); + SDKUtil.showLog(TAG, e.getLocalizedMessage()); } return null; } @@ -390,67 +378,56 @@ public void setCachePolicy(CachePolicy cachePolicy) { * */ public void fetch(FetchResultCallback callback) { - try { - - String URL = "/" + stackInstance.VERSION + "/assets/" + assetUid; - ArrayMap headers = getHeader(headerGroup_local); + String urlEndpoint = "/" + stackInstance.VERSION + "/assets/" + assetUid; + ArrayMap headers = getHeader(headerGroupLocal); if (headers.containsKey("environment")) { urlQueries.put("environment", headers.get("environment")); } - - String mainStringForMD5 = URL + new JSONObject().toString() + headers.toString(); - String md5Value = new CSAppUtils().getMD5FromString(mainStringForMD5.trim()); - File cacheFile = new File(CSAppConstants.cacheFolderName + File.separator + md5Value); + String mainStringForMD5 = urlEndpoint + new JSONObject().toString() + headers.toString(); + String md5Value = new SDKUtil().getMD5FromString(mainStringForMD5.trim()); + File cacheFile = new File(SDKConstant.cacheFolderName + File.separator + md5Value); switch (cachePolicyForCall) { - case IGNORE_CACHE: - case NETWORK_ONLY: - fetchFromNetwork(URL, urlQueries, headers, cacheFile.getPath(), callback); + fetchFromNetwork(urlEndpoint, urlQueries, headers, cacheFile.getPath(), callback); break; - case CACHE_ONLY: fetchFromCache(cacheFile, callback); break; - case CACHE_ELSE_NETWORK: - if (cacheFile.exists()) { boolean needToSendCall = false; - needToSendCall = new CSAppUtils().getResponseTimeFromCacheFile(cacheFile, (int) maxCacheTimeForCall); + needToSendCall = new SDKUtil().getResponseTimeFromCacheFile(cacheFile, (int) MAX_CACHE_TIME_FOR_CALL); if (needToSendCall) { - fetchFromNetwork(URL, urlQueries, headers, cacheFile.getPath(), callback); + fetchFromNetwork(urlEndpoint, urlQueries, headers, cacheFile.getPath(), callback); } else { setCacheModel(cacheFile, callback); } } else { - fetchFromNetwork(URL, urlQueries, headers, cacheFile.getPath(), callback); + fetchFromNetwork(urlEndpoint, urlQueries, headers, cacheFile.getPath(), callback); } break; case CACHE_THEN_NETWORK: if (cacheFile.exists()) { setCacheModel(cacheFile, callback); } - // from network - fetchFromNetwork(URL, urlQueries, headers, cacheFile.getPath(), callback); + fetchFromNetwork(urlEndpoint, urlQueries, headers, cacheFile.getPath(), callback); break; case NETWORK_ELSE_CACHE: - - if (CSAppConstants.isNetworkAvailable) { - fetchFromNetwork(URL, urlQueries, headers, cacheFile.getPath(), callback); + if (SDKConstant.IS_NETWORK_AVAILABLE) { + fetchFromNetwork(urlEndpoint, urlQueries, headers, cacheFile.getPath(), callback); } else { fetchFromCache(cacheFile, callback); } - break; } } catch (Exception e) { Error error = new Error(); - error.setErrorMessage(CSAppConstants.ErrorMessage_JsonNotProper); + error.setErrorMessage(SDKConstant.PLEASE_PROVIDE_VALID_JSON); callback.onRequestFail(ResponseType.UNKNOWN, error); } } @@ -458,7 +435,7 @@ public void fetch(FetchResultCallback callback) { private void fetchFromNetwork(String URL, JSONObject urlQueries, ArrayMap headers, String cacheFilePath, FetchResultCallback callback) { if (callback != null) { HashMap urlParams = getUrlParams(urlQueries); - new CSBackgroundTask(this, stackInstance, CSController.FETCHASSETS, URL, headers, urlParams, new JSONObject(), cacheFilePath, CSAppConstants.callController.ASSET.toString(), false, CSAppConstants.RequestMethod.GET, callback); + new CSBackgroundTask(this, stackInstance, SDKController.GET_ASSETS, URL, headers, urlParams, new JSONObject(), cacheFilePath, SDKConstant.callController.ASSET.toString(), false, SDKConstant.RequestMethod.GET, callback); } } @@ -467,16 +444,16 @@ private void fetchFromCache(File cacheFile, FetchResultCallback callback) { Error error = null; if (cacheFile.exists()) { boolean needToSendCall = false; - needToSendCall = new CSAppUtils().getResponseTimeFromCacheFile(cacheFile, (int) maxCacheTimeForCall); + needToSendCall = new SDKUtil().getResponseTimeFromCacheFile(cacheFile, (int) MAX_CACHE_TIME_FOR_CALL); if (needToSendCall) { error = new Error(); - error.setErrorMessage(CSAppConstants.ErrorMessage_EntryNotFoundInCache); + error.setErrorMessage(SDKConstant.ENTRY_IS_NOT_PRESENT_IN_CACHE); } else { setCacheModel(cacheFile, callback); } } else { error = new Error(); - error.setErrorMessage(CSAppConstants.ErrorMessage_EntryNotFoundInCache); + error.setErrorMessage(SDKConstant.ENTRY_IS_NOT_PRESENT_IN_CACHE); } if (callback != null && error != null) { @@ -486,9 +463,7 @@ private void fetchFromCache(File cacheFile, FetchResultCallback callback) { //Asset modeling from cache. private void setCacheModel(File cacheFile, FetchResultCallback callback) { - - AssetModel model = new AssetModel(CSAppUtils.getJsonFromCacheFile(cacheFile), false, true); - + AssetModel model = new AssetModel(SDKUtil.getJsonFromCacheFile(cacheFile), false, true); this.contentType = model.contentType; this.fileSize = model.fileSize; this.uploadUrl = model.uploadUrl; @@ -496,9 +471,7 @@ private void setCacheModel(File cacheFile, FetchResultCallback callback) { this.json = model.json; this.assetUid = model.uploadedUid; this.setTags(model.tags); - model = null; - if (callback != null) { callback.onRequestFinish(ResponseType.CACHE); } @@ -523,14 +496,14 @@ protected Asset setTags(String[] tags) { private HashMap getUrlParams(JSONObject urlQueriesJSON) { HashMap hashMap = new HashMap<>(); if (urlQueriesJSON != null && urlQueriesJSON.length() > 0) { - Iterator iter = urlQueriesJSON.keys(); - while (iter.hasNext()) { - String key = iter.next(); + Iterator iterator = urlQueriesJSON.keys(); + while (iterator.hasNext()) { + String key = iterator.next(); try { Object value = urlQueriesJSON.opt(key); hashMap.put(key, value); } catch (Exception e) { - CSAppUtils.showLog(TAG, "setQueryJson" + e.getLocalizedMessage()); + SDKUtil.showLog(TAG, "setQueryJson" + e.getLocalizedMessage()); } } return hashMap; @@ -539,7 +512,7 @@ private HashMap getUrlParams(JSONObject urlQueriesJSON) { } private ArrayMap getHeader(ArrayMap localHeader) { - ArrayMap mainHeader = headerGroup_app; + ArrayMap mainHeader = headerGroupApp; ArrayMap classHeaders = new ArrayMap<>(); if (localHeader != null && localHeader.size() > 0) { if (mainHeader != null && mainHeader.size() > 0) { @@ -558,7 +531,7 @@ private ArrayMap getHeader(ArrayMap localHeader) return localHeader; } } else { - return headerGroup_app; + return headerGroupApp; } } @@ -591,7 +564,7 @@ public Asset addParam(String key, String value) { try { urlQueries.put(key, value); } catch (JSONException e) { - Log.e(TAG, e.getLocalizedMessage()); + Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage())); } } return this; @@ -608,7 +581,7 @@ public Asset includeDimension() { try { urlQueries.put("include_dimension", true); } catch (JSONException e) { - Log.e(TAG, e.getLocalizedMessage()); + Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage())); } return this; } @@ -629,7 +602,7 @@ public Asset includeFallback() { try { urlQueries.put("include_fallback", true); } catch (JSONException e) { - Log.e(TAG, e.getLocalizedMessage()); + Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage())); } return this; } diff --git a/contentstack/src/main/java/com/contentstack/sdk/AssetLibrary.java b/contentstack/src/main/java/com/contentstack/sdk/AssetLibrary.java index 6c5888e0..e47cf2b0 100644 --- a/contentstack/src/main/java/com/contentstack/sdk/AssetLibrary.java +++ b/contentstack/src/main/java/com/contentstack/sdk/AssetLibrary.java @@ -4,10 +4,6 @@ import android.util.ArrayMap; import android.util.Log; -import com.contentstack.sdk.utilities.CSAppConstants; -import com.contentstack.sdk.utilities.CSAppUtils; -import com.contentstack.sdk.utilities.CSController; - import org.json.JSONException; import org.json.JSONObject; @@ -17,6 +13,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Objects; /** * AssetLibrary class to fetch all files details on Conentstack server. @@ -25,7 +22,7 @@ */ public class AssetLibrary implements INotifyClass { - private final static String TAG = "AssetLibrary"; + private final static String TAG = AssetLibrary.class.getSimpleName(); private Stack stackInstance; private ArrayMap stackHeader; private ArrayMap localHeader; @@ -34,7 +31,7 @@ public class AssetLibrary implements INotifyClass { private int count; private static CachePolicy cachePolicyForCall = CachePolicy.IGNORE_CACHE; private long maxCacheTimeForCall = 0; - private long defaultCacheTimeInterval = 0; + private final long defaultCacheTimeInterval = 0; /** * Sorting order enum for {@link AssetLibrary}. @@ -119,7 +116,7 @@ public AssetLibrary sort(String key, ORDERBY orderby) { break; } } catch (Exception e) { - throwException("sort", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("sort", SDKConstant.PROVIDE_VALID_PARAMS, e); } return this; @@ -140,7 +137,7 @@ public AssetLibrary includeCount() { try { urlQueries.put("include_count", "true"); } catch (Exception e) { - throwException("includeCount", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("includeCount", SDKConstant.PROVIDE_VALID_PARAMS, e); } return this; } @@ -160,7 +157,7 @@ public AssetLibrary includeRelativeUrl() { try { urlQueries.put("relative_urls", "true"); } catch (Exception e) { - throwException("relative_urls", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("relative_urls", SDKConstant.PROVIDE_VALID_PARAMS, e); } return this; } @@ -218,8 +215,8 @@ public void fetchAll(FetchAssetsCallback assetsCallback) { urlQueries.put("environment", headers.get("environment")); } String mainStringForMD5 = URL + new JSONObject().toString() + headers.toString(); - String md5Value = new CSAppUtils().getMD5FromString(mainStringForMD5.trim()); - File cacheFile = new File(CSAppConstants.cacheFolderName + File.separator + md5Value); + String md5Value = new SDKUtil().getMD5FromString(mainStringForMD5.trim()); + File cacheFile = new File(SDKConstant.cacheFolderName + File.separator + md5Value); switch (cachePolicyForCall) { case IGNORE_CACHE: fetchFromNetwork(URL, urlQueries, headers, cacheFile.getPath(), assetsCallback); @@ -233,7 +230,7 @@ public void fetchAll(FetchAssetsCallback assetsCallback) { case CACHE_ELSE_NETWORK: if (cacheFile.exists()) { boolean needToSendCall = false; - needToSendCall = new CSAppUtils().getResponseTimeFromCacheFile(cacheFile, (int) maxCacheTimeForCall); + needToSendCall = new SDKUtil().getResponseTimeFromCacheFile(cacheFile, (int) maxCacheTimeForCall); if (needToSendCall) { fetchFromNetwork(URL, urlQueries, headers, cacheFile.getPath(), assetsCallback); } else { @@ -250,7 +247,7 @@ public void fetchAll(FetchAssetsCallback assetsCallback) { fetchFromNetwork(URL, urlQueries, headers, cacheFile.getPath(), assetsCallback); break; case NETWORK_ELSE_CACHE: - if (CSAppConstants.isNetworkAvailable) { + if (SDKConstant.IS_NETWORK_AVAILABLE) { fetchFromNetwork(URL, urlQueries, headers, cacheFile.getPath(), assetsCallback); } else { fetchFromCache(cacheFile, assetsCallback); @@ -259,14 +256,14 @@ public void fetchAll(FetchAssetsCallback assetsCallback) { } } catch (Exception e) { - CSAppUtils.showLog(TAG, e.toString()); + SDKUtil.showLog(TAG, e.toString()); } } private void fetchFromNetwork(String URL, JSONObject urlQueries, ArrayMap headers, String cacheFilePath, FetchAssetsCallback callback) { if (callback != null) { HashMap urlParams = getUrlParams(urlQueries); - new CSBackgroundTask(this, stackInstance, CSController.FETCHALLASSETS, URL, headers, urlParams, new JSONObject(), cacheFilePath, CSAppConstants.callController.ASSETLIBRARY.toString(), false, CSAppConstants.RequestMethod.GET, assetsCallback); + new CSBackgroundTask(this, stackInstance, SDKController.GET_ALL_ASSETS, URL, headers, urlParams, new JSONObject(), cacheFilePath, SDKConstant.callController.ASSET_LIBRARY.toString(), false, SDKConstant.RequestMethod.GET, assetsCallback); } } @@ -274,16 +271,16 @@ private void fetchFromCache(File cacheFile, FetchAssetsCallback callback) { Error error = null; if (cacheFile.exists()) { boolean needToSendCall = false; - needToSendCall = new CSAppUtils().getResponseTimeFromCacheFile(cacheFile, (int) maxCacheTimeForCall); + needToSendCall = new SDKUtil().getResponseTimeFromCacheFile(cacheFile, (int) maxCacheTimeForCall); if (needToSendCall) { error = new Error(); - error.setErrorMessage(CSAppConstants.ErrorMessage_EntryNotFoundInCache); + error.setErrorMessage(SDKConstant.ENTRY_IS_NOT_PRESENT_IN_CACHE); } else { setCacheModel(cacheFile, callback); } } else { error = new Error(); - error.setErrorMessage(CSAppConstants.ErrorMessage_EntryNotFoundInCache); + error.setErrorMessage(SDKConstant.ENTRY_IS_NOT_PRESENT_IN_CACHE); } if (callback != null && error != null) { @@ -294,7 +291,7 @@ private void fetchFromCache(File cacheFile, FetchAssetsCallback callback) { //Asset modeling from cache. private void setCacheModel(File cacheFile, FetchAssetsCallback callback) { - AssetsModel assetsModel = new AssetsModel(CSAppUtils.getJsonFromCacheFile(cacheFile), true); + AssetsModel assetsModel = new AssetsModel(SDKUtil.getJsonFromCacheFile(cacheFile), true); List objectList = assetsModel.objects; assetsModel = null; count = objectList.size(); @@ -334,7 +331,7 @@ private HashMap getUrlParams(JSONObject urlQueriesJSON) { Object value = urlQueriesJSON.opt(key); hashMap.put(key, value); } catch (Exception e) { - CSAppUtils.showLog(TAG, e.toString()); + SDKUtil.showLog(TAG, e.toString()); } } @@ -352,6 +349,7 @@ private void throwException(String tag, String messageString, Exception e) { } if (e != null) { error.setErrorMessage(e.getLocalizedMessage()); + assert messageString != null; Log.d(tag, messageString); } } @@ -434,10 +432,25 @@ public AssetLibrary includeFallback() { try { urlQueries.put("include_fallback", true); } catch (JSONException e) { - Log.d("AssetLibrary", e.getLocalizedMessage()); + Log.d("AssetLibrary", Objects.requireNonNull(e.getLocalizedMessage())); throwException("AssetLibrary", null, e); } return this; } + + /** + * Include metadata asset response. + * + * @return the asset library + */ + public AssetLibrary includeMetadata() { + try { + urlQueries.put("include_metadata", true); + } catch (JSONException e) { + Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage())); + } + return this; + } + } diff --git a/contentstack/src/main/java/com/contentstack/sdk/AssetModel.java b/contentstack/src/main/java/com/contentstack/sdk/AssetModel.java index bd069495..4e0d7105 100755 --- a/contentstack/src/main/java/com/contentstack/sdk/AssetModel.java +++ b/contentstack/src/main/java/com/contentstack/sdk/AssetModel.java @@ -45,7 +45,6 @@ public AssetModel(JSONObject responseJSON, boolean isArray, boolean isFromCache) if (json.opt("tags") instanceof JSONArray) { if ((json.has("tags")) && (json.opt("tags") != null) && (!(json.opt("tags").equals("")))) { - JSONArray tagsArray = (JSONArray) json.opt("tags"); if (tagsArray.length() > 0) { int count = tagsArray.length(); @@ -59,6 +58,7 @@ public AssetModel(JSONObject responseJSON, boolean isArray, boolean isFromCache) if (json != null && json.has("_metadata")) { JSONObject _metadataJSON = json.optJSONObject("_metadata"); + assert _metadataJSON != null; Iterator iterator = _metadataJSON.keys(); _metadata = new WeakHashMap<>(); while (iterator.hasNext()) { diff --git a/contentstack/src/main/java/com/contentstack/sdk/AssetsModel.java b/contentstack/src/main/java/com/contentstack/sdk/AssetsModel.java index e96de11a..1ba82a22 100644 --- a/contentstack/src/main/java/com/contentstack/sdk/AssetsModel.java +++ b/contentstack/src/main/java/com/contentstack/sdk/AssetsModel.java @@ -11,18 +11,13 @@ */ class AssetsModel { - List objects = new ArrayList(); public AssetsModel(JSONObject jsonObject, boolean isFromCache) { - jsonObject = !isFromCache && jsonObject.opt("response") == null ? jsonObject : jsonObject.optJSONObject("response"); - JSONArray jsonArray = jsonObject != null && jsonObject.has("assets") ? jsonObject.optJSONArray("assets") : null; - if (jsonArray != null) { for (int i = 0; i < jsonArray.length(); i++) { - AssetModel model = new AssetModel(jsonArray.optJSONObject(i), true, false); objects.add(model); model = null; diff --git a/contentstack/src/main/java/com/contentstack/sdk/CSBackgroundTask.java b/contentstack/src/main/java/com/contentstack/sdk/CSBackgroundTask.java index 14458615..ac0b1461 100755 --- a/contentstack/src/main/java/com/contentstack/sdk/CSBackgroundTask.java +++ b/contentstack/src/main/java/com/contentstack/sdk/CSBackgroundTask.java @@ -2,8 +2,6 @@ import android.util.ArrayMap; -import com.contentstack.sdk.utilities.CSAppConstants; - import org.json.JSONObject; import java.util.HashMap; @@ -13,12 +11,12 @@ */ class CSBackgroundTask { - public CSBackgroundTask(Query queryInstance, Stack stackInstance, String controller, String url, ArrayMap headers, HashMap urlQueries, JSONObject jsonMain, String cacheFilePath, String requestInfo, CSAppConstants.RequestMethod method, ResultCallBack callback) { + public CSBackgroundTask(Query queryInstance, Stack stackInstance, String controller, String url, ArrayMap headers, HashMap urlQueries, JSONObject jsonMain, String cacheFilePath, String requestInfo, SDKConstant.RequestMethod method, ResultCallBack callback) { - if (CSAppConstants.isNetworkAvailable) { + if (SDKConstant.IS_NETWORK_AVAILABLE) { if (headers != null && headers.size() > 0) { - String URL = stackInstance.URLSCHEMA + stackInstance.URL + url; + String URL = stackInstance.PROTOCOL + stackInstance.URL + url; CSConnectionRequest csConnectionRequest = new CSConnectionRequest(queryInstance); csConnectionRequest.setQueryInstance(queryInstance); @@ -33,11 +31,11 @@ public CSBackgroundTask(Query queryInstance, Stack stackInstance, String control } } - public CSBackgroundTask(Entry entryInstance, Stack stackInstance, String controller, String url, ArrayMap headers, HashMap urlQueries, JSONObject jsonMain, String cacheFilePath, String requestInfo, boolean isOffline, CSAppConstants.RequestMethod method, ResultCallBack callBack) { - if (CSAppConstants.isNetworkAvailable) { + public CSBackgroundTask(Entry entryInstance, Stack stackInstance, String controller, String url, ArrayMap headers, HashMap urlQueries, JSONObject jsonMain, String cacheFilePath, String requestInfo, boolean isOffline, SDKConstant.RequestMethod method, ResultCallBack callBack) { + if (SDKConstant.IS_NETWORK_AVAILABLE) { if (headers != null && headers.size() > 0) { - String URL = stackInstance.URLSCHEMA + stackInstance.URL + url; + String URL = stackInstance.PROTOCOL + stackInstance.URL + url; CSConnectionRequest csConnectionRequest = new CSConnectionRequest(entryInstance); csConnectionRequest.setURLQueries(urlQueries); @@ -51,11 +49,11 @@ public CSBackgroundTask(Entry entryInstance, Stack stackInstance, String control } } - public CSBackgroundTask(AssetLibrary assetLibrary, Stack stackInstance, String controller, String url, ArrayMap headers, HashMap urlQueries, JSONObject jsonMain, String cacheFilePath, String requestInfo, boolean isOffline, CSAppConstants.RequestMethod method, ResultCallBack callback) { - if (CSAppConstants.isNetworkAvailable) { + public CSBackgroundTask(AssetLibrary assetLibrary, Stack stackInstance, String controller, String url, ArrayMap headers, HashMap urlQueries, JSONObject jsonMain, String cacheFilePath, String requestInfo, boolean isOffline, SDKConstant.RequestMethod method, ResultCallBack callback) { + if (SDKConstant.IS_NETWORK_AVAILABLE) { if (headers != null && headers.size() > 0) { - String URL = stackInstance.URLSCHEMA + stackInstance.URL + url; + String URL = stackInstance.PROTOCOL + stackInstance.URL + url; CSConnectionRequest csConnectionRequest = new CSConnectionRequest(assetLibrary); csConnectionRequest.setURLQueries(urlQueries); @@ -69,11 +67,11 @@ public CSBackgroundTask(AssetLibrary assetLibrary, Stack stackInstance, String c } } - public CSBackgroundTask(Asset asset, Stack stackInstance, String controller, String url, ArrayMap headers, HashMap urlQueries, JSONObject jsonMain, String cacheFilePath, String requestInfo, boolean isOffline, CSAppConstants.RequestMethod method, ResultCallBack callback) { - if (CSAppConstants.isNetworkAvailable) { + public CSBackgroundTask(Asset asset, Stack stackInstance, String controller, String url, ArrayMap headers, HashMap urlQueries, JSONObject jsonMain, String cacheFilePath, String requestInfo, boolean isOffline, SDKConstant.RequestMethod method, ResultCallBack callback) { + if (SDKConstant.IS_NETWORK_AVAILABLE) { if (headers != null && headers.size() > 0) { - String URL = stackInstance.URLSCHEMA + stackInstance.URL + url; + String URL = stackInstance.PROTOCOL + stackInstance.URL + url; CSConnectionRequest csConnectionRequest = new CSConnectionRequest(asset); csConnectionRequest.setURLQueries(urlQueries); @@ -88,12 +86,12 @@ public CSBackgroundTask(Asset asset, Stack stackInstance, String controller, Str } - public CSBackgroundTask(Stack stack, Stack stackInstance, String controller, String url, ArrayMap headers, HashMap urlParams, JSONObject jsonMain, String cacheFilePath, String requestInfo, boolean b, CSAppConstants.RequestMethod method, ResultCallBack callback) { + public CSBackgroundTask(Stack stack, Stack stackInstance, String controller, String url, ArrayMap headers, HashMap urlParams, JSONObject jsonMain, String cacheFilePath, String requestInfo, boolean b, SDKConstant.RequestMethod method, ResultCallBack callback) { - if (CSAppConstants.isNetworkAvailable) { + if (SDKConstant.IS_NETWORK_AVAILABLE) { if (headers != null && headers.size() > 0) { - String URL = stackInstance.URLSCHEMA + stackInstance.URL + url; + String URL = stackInstance.PROTOCOL + stackInstance.URL + url; CSConnectionRequest csConnectionRequest = new CSConnectionRequest(stack); csConnectionRequest.setStackInstance(stack); @@ -109,12 +107,12 @@ public CSBackgroundTask(Stack stack, Stack stackInstance, String controller, Str } - public CSBackgroundTask(ContentType contentType, Stack stackInstance, String controller, String url, ArrayMap headers, HashMap urlParams, JSONObject jsonMain, String cacheFilePath, String requestInfo, boolean b, CSAppConstants.RequestMethod method, ResultCallBack callback) { + public CSBackgroundTask(ContentType contentType, Stack stackInstance, String controller, String url, ArrayMap headers, HashMap urlParams, JSONObject jsonMain, String cacheFilePath, String requestInfo, boolean b, SDKConstant.RequestMethod method, ResultCallBack callback) { - if (CSAppConstants.isNetworkAvailable) { + if (SDKConstant.IS_NETWORK_AVAILABLE) { if (headers != null && headers.size() > 0) { - String URL = stackInstance.URLSCHEMA + stackInstance.URL + url; + String URL = stackInstance.PROTOCOL + stackInstance.URL + url; CSConnectionRequest csConnectionRequest = new CSConnectionRequest(contentType); csConnectionRequest.setContentTypeInstance(contentType); @@ -132,8 +130,8 @@ public CSBackgroundTask(ContentType contentType, Stack stackInstance, String con private void sendErrorToUser(ResultCallBack callbackObject) { Error error = new Error(); - error.setErrorCode(CSAppConstants.NONETWORKCONNECTION); - error.setErrorMessage(CSAppConstants.ErrorMessage_NoNetwork); + error.setErrorCode(SDKConstant.NO_NETWORK_CONNECTION); + error.setErrorMessage(SDKConstant.NOT_AVAILABLE); if (callbackObject != null) { callbackObject.onRequestFail(ResponseType.UNKNOWN, error); } @@ -141,7 +139,7 @@ private void sendErrorToUser(ResultCallBack callbackObject) { private void sendErrorForHeader(ResultCallBack callbackObject) { Error error = new Error(); - error.setErrorMessage(CSAppConstants.ErrorMessage_CalledDefaultMethod); + error.setErrorMessage(SDKConstant.STACK_FIRST); if (callbackObject != null) { callbackObject.onRequestFail(ResponseType.UNKNOWN, error); } diff --git a/contentstack/src/main/java/com/contentstack/sdk/CSConnectionRequest.java b/contentstack/src/main/java/com/contentstack/sdk/CSConnectionRequest.java index 9a61476d..5ba1f8b8 100755 --- a/contentstack/src/main/java/com/contentstack/sdk/CSConnectionRequest.java +++ b/contentstack/src/main/java/com/contentstack/sdk/CSConnectionRequest.java @@ -3,10 +3,6 @@ import android.util.ArrayMap; -import com.contentstack.sdk.utilities.CSAppConstants; -import com.contentstack.sdk.utilities.CSAppUtils; -import com.contentstack.sdk.utilities.CSController; - import org.json.JSONObject; import java.io.File; @@ -24,10 +20,9 @@ */ class CSConnectionRequest implements IRequestModelHTTP { - private static final String TAG = "CSConnectionRequest"; - + private static final String TAG = CSConnectionRequest.class.getSimpleName(); private String urlToCall; - private CSAppConstants.RequestMethod method; + private SDKConstant.RequestMethod method; private String controller; private JSONObject paramsJSON; private ArrayMap header; @@ -88,10 +83,10 @@ public void setContentTypeInstance(ContentType contentTypeInstance) { } public void setParams(Object... objects) { - CSAppUtils.showLog(TAG, "ParallelTasks------|" + objects[0] + " started"); + SDKUtil.showLog(TAG, "ParallelTasks------|" + objects[0] + " started"); this.urlToCall = (String) objects[0]; - this.method = (CSAppConstants.RequestMethod) objects[1]; + this.method = (SDKConstant.RequestMethod) objects[1]; this.controller = (String) objects[2]; paramsJSON = (JSONObject) objects[3]; this.header = (ArrayMap) objects[4]; @@ -142,11 +137,9 @@ public void onRequestFailed(JSONObject error, int statusCode, ResultCallBack cal if (errorJObject != null) { errorMessage = (errorJObject).isNull("error_message") ? "" : (errorJObject).optString("error_message"); - if ((!errorJObject.isNull("error_code")) && (!errorJObject.optString("error_code").contains(" "))) { errorCode = (Integer) errorJObject.opt("error_code"); } - if (!errorJObject.isNull("errors")) { resultHashMap = new HashMap(); if (errorJObject.opt("errors") instanceof JSONObject) { @@ -164,11 +157,11 @@ public void onRequestFailed(JSONObject error, int statusCode, ResultCallBack cal } } catch (Exception e) { - CSAppUtils.showLog(TAG, "------------------catch 210 urlReq---|" + e); + SDKUtil.showLog(TAG, "------------------catch 210 urlReq---|" + e); errorMessage = e.getLocalizedMessage(); } if (errorMessage == null || (!(errorMessage.length() > 0))) { - errorMessage = CSAppConstants.ErrorMessage_Default; + errorMessage = SDKConstant.ERROR_MESSAGE_DEFAULT; } errorObject.setErrorCode(errorCode); errorObject.setErrorMessage(errorMessage); @@ -182,30 +175,24 @@ public void onRequestFailed(JSONObject error, int statusCode, ResultCallBack cal @Override public void onRequestFinished(CSHttpConnection request) { - responseJSON = request.getResponse(); - String controller = request.getController(); if (cacheFileName != null) { createFileIntoCacheDir(responseJSON); } - - if (controller.equalsIgnoreCase(CSController.QUERYOBJECT)) { - + if (controller.equalsIgnoreCase(SDKController.GET_QUERY_ENTRIES)) { EntriesModel model = new EntriesModel(responseJSON, null, false); notifyClass.getResult(model.formName, null); notifyClass.getResultObject(model.objectList, responseJSON, false); model = null; - } else if (controller.equalsIgnoreCase(CSController.SINGLEQUERYOBJECT)) { - + } else if (controller.equalsIgnoreCase(SDKController.SINGLE_QUERY_ENTRIES)) { EntriesModel model = new EntriesModel(responseJSON, null, false); notifyClass.getResult(model.formName, null); notifyClass.getResultObject(model.objectList, responseJSON, true); model = null; - } else if (controller.equalsIgnoreCase(CSController.FETCHENTRY)) { - + } else if (controller.equalsIgnoreCase(SDKController.GET_ENTRY)) { EntryModel model = new EntryModel(responseJSON, null, false, false, false); entryInstance.resultJson = model.jsonObject; entryInstance.ownerEmailId = model.ownerEmailId; @@ -227,16 +214,13 @@ public void onRequestFinished(CSHttpConnection request) { ((EntryResultCallBack) request.getCallBackObject()).onRequestFinish(ResponseType.NETWORK); } - } else if (controller.equalsIgnoreCase(CSController.FETCHALLASSETS)) { + } else if (controller.equalsIgnoreCase(SDKController.GET_ALL_ASSETS)) { AssetsModel assetsModel = new AssetsModel(responseJSON, false); List objectList = assetsModel.objects; assetsModel = null; - assetLibrary.getResultObject(objectList, responseJSON, false); - - } else if (controller.equalsIgnoreCase(CSController.FETCHASSETS)) { + } else if (controller.equalsIgnoreCase(SDKController.GET_ASSETS)) { AssetModel model = new AssetModel(responseJSON, false, false); - assetInstance.contentType = model.contentType; assetInstance.fileSize = model.fileSize; assetInstance.uploadUrl = model.uploadUrl; @@ -249,7 +233,7 @@ public void onRequestFinished(CSHttpConnection request) { if (request.getCallBackObject() != null) { ((FetchResultCallback) request.getCallBackObject()).onRequestFinish(ResponseType.NETWORK); } - } else if (controller.equalsIgnoreCase(CSController.FETCHSYNC)) { + } else if (controller.equalsIgnoreCase(SDKController.GET_SYNC)) { SyncStack model = new SyncStack(); model.setJSON(responseJSON); @@ -257,16 +241,14 @@ public void onRequestFinished(CSHttpConnection request) { ((SyncResultCallBack) request.getCallBackObject()).onRequestFinish(model); } - } else if (controller.equalsIgnoreCase(CSController.FETCHCONTENTTYPES)) { + } else if (controller.equalsIgnoreCase(SDKController.GET_CONTENT_TYPES)) { ContentTypesModel model = new ContentTypesModel(); model.setJSON(responseJSON); if (request.getCallBackObject() != null) { ((ContentTypesCallback) request.getCallBackObject()).onRequestFinish(model); } - } - } protected void createFileIntoCacheDir(Object jsonObject) { @@ -274,10 +256,7 @@ protected void createFileIntoCacheDir(Object jsonObject) { JSONObject jsonObj = new JSONObject(); JSONObject mainJsonObj = new JSONObject(); JSONObject headerJson = new JSONObject(); - - jsonObj = paramsJSON; - Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTime(new Date()); @@ -296,9 +275,7 @@ protected void createFileIntoCacheDir(Object jsonObject) { headerJson.put(key, entry.getValue()); } mainJsonObj.put("header", headerJson); - File cacheFile = new File(cacheFileName); - if (cacheFile.exists()) { cacheFile.delete(); } @@ -309,14 +286,14 @@ protected void createFileIntoCacheDir(Object jsonObject) { file.close(); } catch (Exception e) { Error error = new Error(); - error.setErrorMessage(CSAppConstants.ErrorMessage_SavingNetworkCallResponseForCache); + error.setErrorMessage(SDKConstant.NETWORK_CALL_RESPONSE); HashMap hashMap = new HashMap(); hashMap.put("error", e.getLocalizedMessage()); error.setErrors(hashMap); if (callBackObject != null) { callBackObject.onRequestFail(ResponseType.CACHE, error); } - CSAppUtils.showLog(TAG, e.getLocalizedMessage()); + SDKUtil.showLog(TAG, e.getLocalizedMessage()); } } diff --git a/contentstack/src/main/java/com/contentstack/sdk/CSHttpConnection.java b/contentstack/src/main/java/com/contentstack/sdk/CSHttpConnection.java index e1a9ecc5..3decf64e 100755 --- a/contentstack/src/main/java/com/contentstack/sdk/CSHttpConnection.java +++ b/contentstack/src/main/java/com/contentstack/sdk/CSHttpConnection.java @@ -1,15 +1,11 @@ package com.contentstack.sdk; -import android.util.ArrayMap; import android.text.TextUtils; +import android.util.ArrayMap; import android.util.Log; import com.android.volley.DefaultRetryPolicy; -import com.android.volley.Request; import com.android.volley.VolleyError; -import com.android.volley.toolbox.JsonObjectRequest; -import com.contentstack.sdk.utilities.CSAppConstants; -import com.contentstack.sdk.utilities.CSAppUtils; import org.json.JSONArray; import org.json.JSONObject; @@ -34,7 +30,7 @@ class CSHttpConnection implements IURLRequestHTTP { private JSONObject requestJSON; private final IRequestModelHTTP connectionRequest; private ResultCallBack callBackObject; - private CSAppConstants.RequestMethod requestMethod; + private SDKConstant.RequestMethod requestMethod; private JSONObject responseJSON; public HashMap getFormParams() { @@ -110,12 +106,12 @@ public boolean getTreatDuplicateKeysAsArrayItems() { } @Override - public void setRequestMethod(CSAppConstants.RequestMethod requestMethod) { + public void setRequestMethod(SDKConstant.RequestMethod requestMethod) { this.requestMethod = requestMethod; } @Override - public CSAppConstants.RequestMethod getRequestMethod() { + public SDKConstant.RequestMethod getRequestMethod() { return requestMethod; } @@ -129,7 +125,7 @@ public String setFormParamsGET(HashMap params) { if (params != null && params.size() > 0) { String urlParams = null; - urlParams = info.equalsIgnoreCase(CSAppConstants.callController.QUERY.name()) || info.equalsIgnoreCase(CSAppConstants.callController.ENTRY.name()) ? getParams(params) : null; + urlParams = info.equalsIgnoreCase(SDKConstant.callController.QUERY.name()) || info.equalsIgnoreCase(SDKConstant.callController.ENTRY.name()) ? getParams(params) : null; if (TextUtils.isEmpty(urlParams)) { for (Map.Entry e : params.entrySet()) { @@ -213,7 +209,7 @@ private String getParams(HashMap params) { } } catch (Exception e1) { - CSAppUtils.showLog(TAG, "--------------------getQueryParam--||" + e1.toString()); + SDKUtil.showLog(TAG, "--------------------getQueryParam--||" + e1.toString()); } } @@ -224,12 +220,9 @@ private String getParams(HashMap params) { @Override public void send() { String url = null; - String protocol = CSAppConstants.URLSCHEMA_HTTPS; int requestId = getRequestId(requestMethod); final HashMap headers = new HashMap<>(); - int count = this.headers.size(); - - if (requestMethod == CSAppConstants.RequestMethod.GET) { + if (requestMethod == SDKConstant.RequestMethod.GET) { String params = setFormParamsGET(formParams); if (params != null) { url = urlPath + params; @@ -240,57 +233,38 @@ public void send() { url = urlPath; } - for (Map.Entry entry : this.headers.entrySet()) { String key = entry.getKey(); headers.put(key, (String) entry.getValue()); } - headers.put("Content-Type", "application/json"); headers.put("User-Agent", defaultUserAgent()); - headers.put("X-User-Agent", "contentstack-android/" + CSAppConstants.SDK_VERSION); + headers.put("X-User-Agent", "contentstack-android/" + SDKConstant.SDK_VERSION); - System.out.println(headers); + Log.d("url requested", url); jsonObjectRequest = new JSONUTF8Request(requestId, url, requestJSON, response -> { responseJSON = response; - Log.i("response", response.toString()); if (responseJSON != null) { connectionRequest.onRequestFinished(CSHttpConnection.this); } }, this::generateBuiltError) { - @Override public Map getHeaders() { return headers; } - }; - - jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(CSAppConstants.TimeOutDuration, CSAppConstants.NumRetry, CSAppConstants.BackOFMultiplier)); + jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(SDKConstant.TimeOutDuration, SDKConstant.NumRetry, SDKConstant.BackOFMultiplier)); jsonObjectRequest.setShouldCache(false); - Contentstack.addToRequestQueue(protocol, jsonObjectRequest, info); + Contentstack.addToRequestQueue(SDKConstant.PROTOCOL, jsonObjectRequest, info); } - private void httpRequest(String url) { - JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, requestJSON, response -> { - responseJSON = response; - if (responseJSON != null) { - connectionRequest.onRequestFinished(CSHttpConnection.this); - } - }, this::generateBuiltError); - - jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(CSAppConstants.TimeOutDuration, CSAppConstants.NumRetry, CSAppConstants.BackOFMultiplier)); - jsonObjectRequest.setShouldCache(false); - Contentstack.addToRequestQueue("https://", jsonObjectRequest, info); - } - private String defaultUserAgent() { String agent = System.getProperty("http.agent"); return agent != null ? agent : ("Android" + System.getProperty("java.version")); } - private int getRequestId(CSAppConstants.RequestMethod requestMethod) { + private int getRequestId(SDKConstant.RequestMethod requestMethod) { switch (requestMethod) { case GET: return 0; @@ -309,7 +283,7 @@ private void generateBuiltError(VolleyError error) { try { int statusCode = 0; responseJSON = new JSONObject(); - responseJSON.put("error_message", CSAppConstants.ErrorMessage_Default); + responseJSON.put("error_message", SDKConstant.ERROR_MESSAGE_DEFAULT); if (error != null) { @@ -322,27 +296,27 @@ private void generateBuiltError(VolleyError error) { } else { if (error.toString().equalsIgnoreCase("NoConnectionError")) { - responseJSON.put("error_message", CSAppConstants.ErrorMessage_VolleyNoConnectionError); + responseJSON.put("error_message", SDKConstant.CONNECTION_ERROR); } else if (error.toString().equalsIgnoreCase("AuthFailureError")) { - responseJSON.put("error_message", CSAppConstants.ErrorMessage_VolleyAuthFailureError); + responseJSON.put("error_message", SDKConstant.AUTHENTICATION_NOT_PRESENT); } else if (error.toString().equalsIgnoreCase("NetworkError")) { - responseJSON.put("error_message", CSAppConstants.ErrorMessage_NoNetwork); + responseJSON.put("error_message", SDKConstant.NOT_AVAILABLE); } else if (error.toString().equalsIgnoreCase("ParseError")) { - responseJSON.put("error_message", CSAppConstants.ErrorMessage_VolleyParseError); + responseJSON.put("error_message", SDKConstant.PARSING_ERROR); } else if (error.toString().equalsIgnoreCase("ServerError")) { - responseJSON.put("error_message", CSAppConstants.ErrorMessage_VolleyServerError); + responseJSON.put("error_message", SDKConstant.TRY_AGAIN); } else if (error.toString().equalsIgnoreCase("TimeoutError")) { - responseJSON.put("error_message", CSAppConstants.ErrorMessage_VolleyServerError); + responseJSON.put("error_message", SDKConstant.TRY_AGAIN); } else { if (error.getMessage() != null) { @@ -364,7 +338,7 @@ private void generateBuiltError(VolleyError error) { connectionRequest.onRequestFailed(responseJSON, 0, callBackObject); } } catch (Exception exception) { - CSAppUtils.showLog(TAG, exception.toString()); + SDKUtil.showLog(TAG, exception.toString()); } } diff --git a/contentstack/src/main/java/com/contentstack/sdk/utilities/ContentstackUtil.java b/contentstack/src/main/java/com/contentstack/sdk/CSUtil.java similarity index 73% rename from contentstack/src/main/java/com/contentstack/sdk/utilities/ContentstackUtil.java rename to contentstack/src/main/java/com/contentstack/sdk/CSUtil.java index 38367bad..cef8f146 100755 --- a/contentstack/src/main/java/com/contentstack/sdk/utilities/ContentstackUtil.java +++ b/contentstack/src/main/java/com/contentstack/sdk/CSUtil.java @@ -1,6 +1,10 @@ -package com.contentstack.sdk.utilities; +package com.contentstack.sdk; import android.annotation.SuppressLint; +import android.content.Context; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.util.Log; import java.text.ParseException; import java.text.SimpleDateFormat; @@ -14,20 +18,16 @@ * * @author contentstack.com, Inc */ -public class ContentstackUtil { +public class CSUtil { /** * Converts the given date to user's timezone. * * @param date date in ISO format. * @return {@link Calendar} object. - * @throws ParseException

Example :
- *
-     *                                                                       Util.parseDate(dateString, TimeZone.getDefault());
-     *                                                                       
*/ - public static Calendar parseDate(String date, TimeZone timeZone) throws ParseException { - ArrayList knownPatterns = new ArrayList(); + public static Calendar parseDate(String date, TimeZone timeZone) { + ArrayList knownPatterns = new ArrayList<>(); knownPatterns.add("yyyy-MM-dd'T'HH:mm:ssZ"); knownPatterns.add("yyyy-MM-dd'T'HH:mm:ss'Z'"); knownPatterns.add("yyyy-MM-dd'T'HH:mm.ss'Z'"); @@ -44,7 +44,7 @@ public static Calendar parseDate(String date, TimeZone timeZone) throws ParseExc try { return parseDate(date, formatString, timeZone); } catch (ParseException e) { - System.out.println(e.getLocalizedMessage()); + Log.e("CSUtils", e.getLocalizedMessage()); } } @@ -59,8 +59,8 @@ public static Calendar parseDate(String date, TimeZone timeZone) throws ParseExc * @return {@link Calendar} object. * @throws ParseException

Example :
*
-     *                                                                                               Util.parseDate(dateString, "yyyy-MM-dd'T'HH:mm:ssZ", TimeZone.getTimeZone("GMT"));
-     *                                                                                             
+ * Util.parseDate(dateString, "yyyy-MM-dd'T'HH:mm:ssZ", TimeZone.getTimeZone("GMT")); + * */ @SuppressLint("SimpleDateFormat") public static Calendar parseDate(String date, String dateFormat, TimeZone timeZone) throws ParseException { @@ -107,5 +107,12 @@ public static Calendar parseDate(String date, String dateFormat, TimeZone timeZo return cal; } - ; + + protected static void isNetworkAvailable(Context context) { + ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); + if (connectivityManager.getNetworkInfo(0) != null || connectivityManager.getNetworkInfo(1).getState() != null) { + SDKConstant.IS_NETWORK_AVAILABLE = connectivityManager.getActiveNetworkInfo() != null; + } else + SDKConstant.IS_NETWORK_AVAILABLE = connectivityManager.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED || connectivityManager.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED; + } } diff --git a/contentstack/src/main/java/com/contentstack/sdk/ClearCache.java b/contentstack/src/main/java/com/contentstack/sdk/ClearCache.java index bdb48d5b..f0a388b0 100755 --- a/contentstack/src/main/java/com/contentstack/sdk/ClearCache.java +++ b/contentstack/src/main/java/com/contentstack/sdk/ClearCache.java @@ -4,8 +4,6 @@ import android.content.Context; import android.content.Intent; -import com.contentstack.sdk.utilities.CSAppUtils; - import org.json.JSONObject; import java.io.File; @@ -31,19 +29,15 @@ public void onReceive(Context context, Intent intent) { if (cacheResponseFolder.isDirectory()) { File[] childFiles = cacheResponseFolder.listFiles(); - for (File child : childFiles) { File file = new File(cacheResponseFolder, child.getName()); - File sessionFile = new File(cacheResponseFolder.getPath() + File.separator + "Session"); File installationFile = new File(cacheResponseFolder.getPath() + File.separator + "Installation"); - if ((file.getName().equalsIgnoreCase(sessionFile.getName())) || (file.getName().equalsIgnoreCase(installationFile.getName()))) { } else { - if (file.exists()) { - JSONObject jsonObj = CSAppUtils.getJsonFromCacheFile(file); + JSONObject jsonObj = SDKUtil.getJsonFromCacheFile(file); if (jsonObj != null) { if (jsonObj.optString("timestamp") != null) { long responseTime = Long.parseLong(jsonObj.optString("timestamp")); @@ -59,7 +53,7 @@ public void onReceive(Context context, Intent intent) { } } } else { - CSAppUtils.showLog("ClearCache", "--------------------no offline network calls"); + SDKUtil.showLog("ClearCache", "--------------------no offline network calls"); } } } diff --git a/contentstack/src/main/java/com/contentstack/sdk/Config.java b/contentstack/src/main/java/com/contentstack/sdk/Config.java index 30449e57..4ca35af1 100755 --- a/contentstack/src/main/java/com/contentstack/sdk/Config.java +++ b/contentstack/src/main/java/com/contentstack/sdk/Config.java @@ -2,45 +2,44 @@ import android.text.TextUtils; -import com.contentstack.sdk.utilities.CSAppConstants; - /** * Set Configuration for stack instance creation. * * @author contentstack.com, Inc */ public class Config { - - protected String URLSCHEMA = "https://"; + protected String PROTOCOL = "https://"; protected String URL = "cdn.contentstack.io"; protected String VERSION = "v3"; protected String environment = null; protected ContentstackRegion region = ContentstackRegion.US; - public enum ContentstackRegion {US, EU, AZURE_NA} - - - public ContentstackRegion getRegion() { - return this.region; - } - /** * Sets region allow you to set your region for the Contentstack server. * * @param region

* Note: Default region sets to us * - *

Example :
+ *

Example For Different Regions:
*

-     *                                                                                                   config.setRegion(ContentstackRegion.US);
-     *                                                                                                   
+ * config.setRegion(ContentstackRegion.US); + * config.setRegion(ContentstackRegion.EU); + * config.setRegion(ContentstackRegion.AZURE_EU); + * config.setRegion(ContentstackRegion.AZURE_NA); + * */ - public ContentstackRegion setRegion(ContentstackRegion region) { this.region = region; return this.region; } + + public ContentstackRegion getRegion() { + return this.region; + } + + public enum ContentstackRegion {US, EU, AZURE_NA, AZURE_EU} + /** * Config constructor * @@ -49,7 +48,6 @@ public ContentstackRegion setRegion(ContentstackRegion region) { * Config config = new Config(); * */ - public Config() { } @@ -57,7 +55,6 @@ public Config() { * Sets host name of the Contentstack server. * * @param hostName host name. - * *

* Note: Default hostname sets to cdn.contentstack.io * and default protocol is HTTPS. @@ -75,8 +72,7 @@ public void setHost(String hostName) { /** - * Get URL. - * + * Get Host. * *

Example :
*

 headerGroup = new HashMap();
-
-                CSAppConstants.isNetworkAvailable = true;
-
+                HashMap headerGroup = new HashMap<>();
+                IS_NETWORK_AVAILABLE = true;
                 File offlineCallsFolder = new File(context.getDir("OfflineCalls", 0).getPath());
 
                 if (offlineCallsFolder.isDirectory()) {
                     File[] childFiles = offlineCallsFolder.listFiles();
+                    assert childFiles != null;
                     for (File child : childFiles) {
                         File file = new File(offlineCallsFolder, child.getName());
                         if (file.exists()) {
-                            jsonObj = CSAppUtils.getJsonFromCacheFile(file);
+                            jsonObj = SDKUtil.getJsonFromCacheFile(file);
                             if (jsonObj != null) {
                                 headerObject = jsonObj.optJSONObject("headers");
-                                int count = headerObject.names().length();
+                                assert headerObject != null;
+                                int count = Objects.requireNonNull(headerObject.names()).length();
                                 for (int i = 0; i < count; i++) {
-                                    String key = headerObject.names().getString(i);
+                                    String key = Objects.requireNonNull(headerObject.names()).getString(i);
                                     headerGroup.put(key, headerObject.optString(key));
                                 }
                                 CSConnectionRequest connectionRequest = new CSConnectionRequest();
                                 connectionRequest.setParams(
-                                        jsonObj.opt("url").toString(),
-                                        CSAppConstants.RequestMethod.POST,
-                                        jsonObj.opt("controller").toString(),
+                                        Objects.requireNonNull(jsonObj.opt("url")).toString(),
+                                        RequestMethod.POST,
+                                        Objects.requireNonNull(jsonObj.opt("controller")).toString(),
                                         jsonObj.optJSONObject("params"),
                                         headerGroup,
                                         jsonObj.opt("cacheFileName"),
@@ -69,17 +72,14 @@ public void onReceive(Context context, Intent intent) {
                             }
                             child.delete();
                         } else {
-                            CSAppUtils.showLog("ConnectionStatus", "--------------------no offline network calls");
+                            SDKUtil.showLog(TAG, "No offline network calls");
                         }
                     }
                 }
             } catch (Exception e) {
-                CSAppUtils.showLog("ConnectionStatus", "-----content stack----------send  saved network calls-------catch|" + e);
+                SDKUtil.showLog(TAG, "contentstack send saved network calls-------catch|" + e);
             }
         }
-
-        CSAppUtils.showLog("ConnectionStatus", "---------------------BuiltAppConstants.isNetworkAvailable|" + CSAppConstants.isNetworkAvailable);
-
     }
 
 }
diff --git a/contentstack/src/main/java/com/contentstack/sdk/ContentType.java b/contentstack/src/main/java/com/contentstack/sdk/ContentType.java
index 193efe2e..3b631e9f 100755
--- a/contentstack/src/main/java/com/contentstack/sdk/ContentType.java
+++ b/contentstack/src/main/java/com/contentstack/sdk/ContentType.java
@@ -3,10 +3,6 @@
 import android.util.ArrayMap;
 import android.text.TextUtils;
 
-import com.contentstack.sdk.utilities.CSAppConstants;
-import com.contentstack.sdk.utilities.CSAppUtils;
-import com.contentstack.sdk.utilities.CSController;
-
 import org.json.JSONObject;
 
 import java.util.HashMap;
@@ -31,7 +27,7 @@ private ContentType() {
 
     protected ContentType(String contentTypeName) {
         this.contentTypeName = contentTypeName;
-        this.localHeader = new ArrayMap();
+        this.localHeader = new ArrayMap<>();
     }
 
     protected void setStackInstance(Stack stack) {
@@ -39,7 +35,6 @@ protected void setStackInstance(Stack stack) {
         this.stackHeader = stack.localHeader;
     }
 
-
     /**
      * To set headers for Contentstack rest calls.
      * 
@@ -50,10 +45,10 @@ protected void setStackInstance(Stack stack) { * *

Example :
*
-     *                            Stack stack = Contentstack.stack(context, "apiKey", "deliveryToken", "environment");
-     *                            ContentType contentType = stack.contentType("form_name");
- * contentType.setHeader("custom_key", "custom_value"); - *
+ * Stack stack = Contentstack.stack(context, "apiKey", "deliveryToken", "environment"); + * ContentType contentType = stack.contentType("form_name");
+ * contentType.setHeader("custom_key", "custom_value"); + *
*/ public void setHeader(String key, String value) { if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)) { @@ -68,10 +63,10 @@ public void setHeader(String key, String value) { * *

Example :
*
-     *                        Stack stack = Contentstack.stack(context, "apiKey", "deliveryToken", "environment");
-     *                        ContentType contentType = stack.contentType("form_name");
- * contentType.removeHeader("custom_header_key"); - *
+ * Stack stack = Contentstack.stack(context, "apiKey", "deliveryToken", "environment"); + * ContentType contentType = stack.contentType("form_name");
+ * contentType.removeHeader("custom_header_key"); + * */ public void removeHeader(String key) { if (!TextUtils.isEmpty(key)) { @@ -106,7 +101,6 @@ public Entry entry(String entryUid) { entry.formHeader = getHeader(localHeader); entry.setContentTypeInstance(this); entry.setUid(entryUid); - return entry; } @@ -139,61 +133,48 @@ public Query query() { * *

Example :
*
-     *                                 ContentType  contentType = stack.contentType("content_type_uid");
-     *                                 JSONObject params = new JSONObject();
-     *                                 params.put("include_snippet_schema", true);
-     *                                 params.put("limit", 3);
-     *                                 contentType.fetch(new ContentTypesCallback() {
-     *                                 @Override
-     *                                 public void onCompletion(ContentTypesModel contentTypesModel, Error error) {
-     *                                 if (error==null){
-     *
-     *                                 }else {
-     *
-     *                                 }
-     *                                 }
-     *                                 });
-     *                                 
+ * ContentType contentType = stack.contentType("content_type_uid"); + * JSONObject params = new JSONObject(); + * params.put("include_snippet_schema", true); + * params.put("limit", 3); + * contentType.fetch(new ContentTypesCallback() { + * @Override + * public void onCompletion(ContentTypesModel contentTypesModel, Error error) { + * if (error==null){ + * }else { + * } + * } + * }); + * */ public void fetch(JSONObject params, final ContentTypesCallback callback) { - try { - String URL = "/" + stackInstance.VERSION + "/content_types/" + contentTypeName; ArrayMap headers = getHeader(localHeader); if (params == null) { params = new JSONObject(); } - Iterator keys = params.keys(); while (keys.hasNext()) { - // loop to get the dynamic key String key = (String) keys.next(); - // get the value of the dynamic key Object value = params.opt(key); - // do something here with the value... params.put(key, value); } - if (headers.containsKey("environment")) { params.put("environment", headers.get("environment")); } - if (contentTypeName != null && !contentTypeName.isEmpty()) { fetchContentTypes(URL, params, headers, null, callback); } else { Error error = new Error(); - error.setErrorMessage(CSAppConstants.ErrorMessage_JsonNotProper); + error.setErrorMessage(SDKConstant.PLEASE_PROVIDE_VALID_JSON); callback.onRequestFail(ResponseType.UNKNOWN, error); } - - } catch (Exception e) { - Error error = new Error(); - error.setErrorMessage(CSAppConstants.ErrorMessage_JsonNotProper); + error.setErrorMessage(SDKConstant.PLEASE_PROVIDE_VALID_JSON); callback.onRequestFail(ResponseType.UNKNOWN, error); } @@ -205,7 +186,7 @@ private void fetchContentTypes(String urlString, JSONObject urlQueries, ArrayMap if (callback != null) { HashMap urlParams = getUrlParams(urlQueries); - new CSBackgroundTask(this, stackInstance, CSController.FETCHCONTENTTYPES, urlString, headers, urlParams, new JSONObject(), cacheFilePath, CSAppConstants.callController.CONTENTTYPES.toString(), false, CSAppConstants.RequestMethod.GET, callback); + new CSBackgroundTask(this, stackInstance, SDKController.GET_CONTENT_TYPES, urlString, headers, urlParams, new JSONObject(), cacheFilePath, SDKConstant.callController.CONTENT_TYPES.toString(), false, SDKConstant.RequestMethod.GET, callback); } } @@ -222,7 +203,7 @@ private HashMap getUrlParams(JSONObject urlQueriesJSON) { Object value = urlQueriesJSON.opt(key); hashMap.put(key, value); } catch (Exception e) { - CSAppUtils.showLog(TAG, "------setQueryJson" + e.toString()); + SDKUtil.showLog(TAG, "------setQueryJson" + e.toString()); } } diff --git a/contentstack/src/main/java/com/contentstack/sdk/ContentTypesModel.java b/contentstack/src/main/java/com/contentstack/sdk/ContentTypesModel.java index dceed4af..5e363b92 100644 --- a/contentstack/src/main/java/com/contentstack/sdk/ContentTypesModel.java +++ b/contentstack/src/main/java/com/contentstack/sdk/ContentTypesModel.java @@ -6,6 +6,8 @@ import org.json.JSONException; import org.json.JSONObject; +import java.util.Objects; + public class ContentTypesModel { private JSONObject responseJSON = new JSONObject(); @@ -20,7 +22,7 @@ public void setJSON(JSONObject responseJSON) { try { this.responseJSON = responseJSON.getJSONObject("content_type"); } catch (JSONException e) { - Log.e(TAG, e.getLocalizedMessage()); + Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage())); } } @@ -28,7 +30,7 @@ public void setJSON(JSONObject responseJSON) { try { this.responseJSONArray = responseJSON.getJSONArray("content_types"); } catch (JSONException e) { - Log.e(TAG, e.getLocalizedMessage()); + Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage())); } } diff --git a/contentstack/src/main/java/com/contentstack/sdk/Contentstack.java b/contentstack/src/main/java/com/contentstack/sdk/Contentstack.java index e110c9ca..8191646d 100755 --- a/contentstack/src/main/java/com/contentstack/sdk/Contentstack.java +++ b/contentstack/src/main/java/com/contentstack/sdk/Contentstack.java @@ -1,79 +1,56 @@ package com.contentstack.sdk; -import android.app.AlarmManager; -import android.app.PendingIntent; import android.content.Context; -import android.content.Intent; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; -import android.os.SystemClock; import android.text.TextUtils; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; -import com.contentstack.sdk.utilities.CSAppConstants; -import com.contentstack.sdk.utilities.CSAppUtils; + +import org.jetbrains.annotations.NotNull; import java.io.File; /** - * Contains all Contentstack API classes and functions. + * Contains all Contentstack SDK Classes And Methods. * - * @author contentstack.com, Inc + * @author ishaileshmishra */ public class Contentstack { - private static final String TAG = "Contentstack"; + private static final String TAG = Contentstack.class.getSimpleName(); + /** + * The constant requestQueue. + */ protected static RequestQueue requestQueue; + + private static Context ctx; private static Contentstack instance; - protected static Context context = null; - private Contentstack() { + private Contentstack(Context context) { throw new IllegalStateException("Private constructor not allowed"); } - public Contentstack(Context applicationContext) { - context = applicationContext; - } - /** * Authenticates the stack api key of your stack. * This must be called before your stack uses Contentstack sdk. *
* You can find your stack api key from web. * - * @param context application context. - * @param stackApiKey application api Key of your application on Contentstack. - * @param accessToken access token - * @param environment environment name - * @return {@link Stack} instance. - * - * - *

Example :
- *
-     * Stack stack = Contentstack.stack(context, "apiKey", "deliveryToken", "stag");
-     * 
+ * @param context application context. + * @param apiKey The api Key of your stack on Contentstack. + * @param deliveryToken The Delivery Token for the stack + * @param environment environment name + * @return {@link Stack} instance.

Example :
 Stack stack = Contentstack.stack(context, "apiKey", "deliveryToken", "stag"); 
+ * @throws Exception the exception */ - public static Stack stack(Context context, String stackApiKey, String accessToken, String environment) throws Exception { - if (context != null) { - if (!TextUtils.isEmpty(stackApiKey)) { - if (!TextUtils.isEmpty(accessToken)) { - if (!TextUtils.isEmpty(environment)) { - Config config = new Config(); - config.setEnvironment(environment); - return initializeStack(context, stackApiKey, accessToken, config); - } else { - throw new Exception(CSAppConstants.ErrorMessage_Stack_Environment_IsNull); - } - } else { - throw new Exception(CSAppConstants.ErrorMessage_Stack_AccessToken_IsNull); - } - } else { - throw new Exception(CSAppConstants.ErrorMessage_StackApiKeyIsNull); - } + public static Stack stack(@NotNull Context context, @NotNull String apiKey, @NotNull String deliveryToken, @NotNull String environment) throws Exception { + if (!TextUtils.isEmpty(apiKey) || !TextUtils.isEmpty(deliveryToken) || !TextUtils.isEmpty(environment)) { + Config config = new Config(); + config.setEnvironment(environment); + return initializeStack(context, apiKey, deliveryToken, config); } else { - throw new Exception(CSAppConstants.ErrorMessage_StackContextIsNull); + throw new Exception(SDKConstant.EMPTY_CREDENTIALS_NOT_ALLOWED); } } @@ -83,136 +60,101 @@ public static Stack stack(Context context, String stackApiKey, String accessToke *
* You can find your stack api key from web. * - * @param context application context. - * @param stackApiKey application api Key of your application on Contentstack. - * @param accessToken access token - * @param config {@link Config} instance to set environment and other configuration details. - * @return {@link Stack} instance. - * - * - *

Example :
- *
-     * Config config = new Config();
-     * config.setEnvironment("stag");
-     * Stack stack = Contentstack.stack(context, "apiKey", "delierytoken", config);
+     * @param context       application context.
+     * @param apiKey        The api Key of your stack on Contentstack.
+     * @param deliveryToken The delivery token for the stack on Contentstack
+     * @param environment   the environment
+     * @param config        {@link Config} instance to set environment and other configuration details.
+     * @return {@link Stack} instance. 

Example :
 Config config = new Config(); config.setEnvironment("stag"); Stack stack = Contentstack.stack(context, "apiKey", "deliveryToken", config);
+     * @throws Exception the exception
      */
-
-
-    public static Stack stack(Context context, String stackApiKey, String accessToken,
-                              String environment, Config config) throws Exception {
-        if (context != null) {
-            if (!TextUtils.isEmpty(stackApiKey)) {
-                if (!TextUtils.isEmpty(accessToken)) {
-                    if (!TextUtils.isEmpty(environment)) {
-
-                        if (config != null) {
-                            config.setEnvironment(environment);
-                        } else {
-                            config = new Config();
-                            config.setEnvironment(environment);
-                        }
-                        return initializeStack(context, stackApiKey, accessToken, config);
-                    } else {
-                        throw new Exception(CSAppConstants.ErrorMessage_Stack_Environment_IsNull);
-                    }
-                } else {
-                    throw new Exception(CSAppConstants.ErrorMessage_Stack_AccessToken_IsNull);
-                }
-            } else {
-                throw new Exception(CSAppConstants.ErrorMessage_StackApiKeyIsNull);
-            }
+    public static Stack stack(@NotNull Context context, @NotNull String apiKey, @NotNull String deliveryToken, @NotNull String environment, @NotNull Config config) throws Exception {
+        if (!TextUtils.isEmpty(apiKey) || !TextUtils.isEmpty(deliveryToken) || !TextUtils.isEmpty(environment)) {
+            config = new Config();
+            config.setEnvironment(environment);
+            return initializeStack(context, apiKey, deliveryToken, config);
         } else {
-            throw new Exception(CSAppConstants.ErrorMessage_StackContextIsNull);
+            throw new Exception(SDKConstant.EMPTY_CREDENTIALS_NOT_ALLOWED);
         }
     }
 
 
-    private static Stack initializeStack(Context mContext, String stackApiKey, String accessToken, Config config) {
-        Stack stack = new Stack(stackApiKey.trim());
-        stack.setHeader("api_key", stackApiKey);
-        stack.setHeader("access_token", accessToken);
-        context = mContext;
+    private static Stack initializeStack(Context appContext, String apiKey, String deliveryToken, Config config) {
+        Stack stack = new Stack(apiKey.trim());
+        stack.setHeader("api_key", apiKey);
+        stack.setHeader("access_token", deliveryToken);
         stack.setConfig(config);
-
-        if (context != null) {
-            try {
-                File queryCacheFile = context.getDir("ContentstackCache", 0);
-                CSAppConstants.cacheFolderName = queryCacheFile.getPath();
-                clearCache(context);
-            } catch (Exception e) {
-                CSAppUtils.showLog(TAG, "Contentstack-" + e.getLocalizedMessage());
-            }
+        try {
+            ctx = appContext;
+            File queryCacheFile = appContext.getDir(SDKConstant.CACHE, 0);
+            SDKConstant.cacheFolderName = queryCacheFile.getPath();
+            SDKUtil.clearCache(appContext);
+        } catch (Exception e) {
+            SDKUtil.showLog(TAG, SDKConstant.CACHE + e.getLocalizedMessage());
         }
         return stack;
     }
 
-
-    /********************************************************************************************************
-     *
-     * // Private Functionality
+    /**
+     * Gets instance.
      *
-     ********************************************************************************************************/
-
-
-    public static synchronized Contentstack getInstance(Context context) {
+     * @param context the context
+     * @return the instance
+     */
+    protected static synchronized Contentstack getInstance(Context context) {
         if (instance == null) {
             instance = new Contentstack(context);
         }
         return instance;
     }
 
-    public RequestQueue getRequestQueue() {
+    /**
+     * Gets request queue.
+     *
+     * @return the request queue
+     */
+    protected RequestQueue getRequestQueue() {
         if (requestQueue == null) {
-            // getApplicationContext() is key, it keeps you from leaking the
-            // Activity or BroadcastReceiver if someone passes one in.
-            requestQueue = Volley.newRequestQueue(context);
+            requestQueue = Volley.newRequestQueue(ctx);
         }
         return requestQueue;
     }
 
-    public  void addToRequestQueue(Request req) {
+    /**
+     * Add to request queue.
+     *
+     * @param  the type parameter
+     * @param req the req
+     */
+    protected  void addToRequestQueue(Request req) {
         getRequestQueue().add(req);
     }
 
+    /**
+     * Gets request queue.
+     *
+     * @param protocol the protocol
+     * @return the request queue
+     */
     protected static RequestQueue getRequestQueue(String protocol) {
         if (requestQueue == null) {
-            requestQueue = Volley.newRequestQueue(context);
+            requestQueue = Volley.newRequestQueue(ctx);
         }
         return requestQueue;
     }
 
+    /**
+     * Add to request queue.
+     *
+     * @param       the type parameter
+     * @param protocol the protocol
+     * @param req      the req
+     * @param tag      the tag
+     */
     protected static  void addToRequestQueue(String protocol, Request req, String tag) {
-        // set the default tag if tag is empty
         req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
         getRequestQueue(protocol).add(req);
     }
 
-    /**
-     * To start schedule for clearing cache.
-     *
-     * @param context application context.
-     */
 
-    private static void clearCache(Context context) {
-        Intent alarmIntent = new Intent("StartContentStackClearingCache");
-        alarmIntent.setPackage(context.getPackageName());
-        int flag = PendingIntent.FLAG_UPDATE_CURRENT;
-        if (android.os.Build.VERSION.SDK_INT >= 23) flag = PendingIntent.FLAG_IMMUTABLE | flag;
-        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, flag);
-        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
-        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
-                SystemClock.elapsedRealtime(), AlarmManager.INTERVAL_DAY, pendingIntent);
-    }
-
-    /**
-     * To check network availability.
-     */
-    protected static void isNetworkAvailable(Context context) {
-        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
-        if (connectivityManager.getNetworkInfo(0) != null || connectivityManager.getNetworkInfo(1).getState() != null) {
-            CSAppConstants.isNetworkAvailable = connectivityManager.getActiveNetworkInfo() != null;
-        } else
-            CSAppConstants.isNetworkAvailable = connectivityManager.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
-                    connectivityManager.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED;
-    }
 }
diff --git a/contentstack/src/main/java/com/contentstack/sdk/EntriesModel.java b/contentstack/src/main/java/com/contentstack/sdk/EntriesModel.java
index 5b8007dc..3d278591 100755
--- a/contentstack/src/main/java/com/contentstack/sdk/EntriesModel.java
+++ b/contentstack/src/main/java/com/contentstack/sdk/EntriesModel.java
@@ -1,7 +1,5 @@
 package com.contentstack.sdk;
 
-import com.contentstack.sdk.utilities.CSAppUtils;
-
 import org.json.JSONArray;
 import org.json.JSONObject;
 
@@ -37,7 +35,7 @@ protected EntriesModel(JSONObject responseJSON, String formName, boolean isFromC
                 }
             }
         } catch (Exception localException) {
-            CSAppUtils.showLog("EntriesModel", "Parsing Error" + localException);
+            SDKUtil.showLog("EntriesModel", "Parsing Error" + localException);
         }
 
     }
diff --git a/contentstack/src/main/java/com/contentstack/sdk/Entry.java b/contentstack/src/main/java/com/contentstack/sdk/Entry.java
index 0df401e5..2e83e300 100755
--- a/contentstack/src/main/java/com/contentstack/sdk/Entry.java
+++ b/contentstack/src/main/java/com/contentstack/sdk/Entry.java
@@ -1,13 +1,9 @@
 package com.contentstack.sdk;
 
-import android.util.ArrayMap;
 import android.text.TextUtils;
+import android.util.ArrayMap;
 import android.util.Log;
 
-import com.contentstack.sdk.utilities.CSAppConstants;
-import com.contentstack.sdk.utilities.CSAppUtils;
-import com.contentstack.sdk.utilities.CSController;
-import com.contentstack.sdk.utilities.ContentstackUtil;
 import com.contentstack.txtmark.Configuration;
 import com.contentstack.txtmark.Processor;
 
@@ -102,10 +98,10 @@ public Entry configure(JSONObject jsonObject) {
      *
      *              

Example :
*
-     *                           Stack stack = Contentstack.stack(context, "apiKey", "deliveryToken",  "stag");
-     *                           Entry entry = stack.contentType("form_name").entry("entry_uid");
-     *                           entry.setHeader("custom_header_key", "custom_header_value");
-     *                           
+ * Stack stack = Contentstack.stack(context, "apiKey", "deliveryToken", "stag"); + * Entry entry = stack.contentType("form_name").entry("entry_uid"); + * entry.setHeader("custom_header_key", "custom_header_value"); + *
*/ public void setHeader(String key, String value) { if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)) { @@ -120,10 +116,10 @@ public void setHeader(String key, String value) { * *

Example :
*
-     *                       Stack stack = Contentstack.stack(context, "apiKey", "deliveryToken",  "stag");
-     *                       Entry entry = stack.contentType("form_name").entry("entry_uid");
-     *                       entry.removeHeader("custom_header_key");
-     *                       
+ * Stack stack = Contentstack.stack(context, "apiKey", "deliveryToken", "stag"); + * Entry entry = stack.contentType("form_name").entry("entry_uid"); + * entry.removeHeader("custom_header_key"); + *
*/ public void removeHeader(String key) { if (!TextUtils.isEmpty(key)) { @@ -304,8 +300,8 @@ public JSONObject toJSON() { * *

Example :
*
-     *                       Object obj = entry.get("key");
-     *                       
+ * Object obj = entry.get("key"); + * */ public Object get(String key) { try { @@ -315,7 +311,7 @@ public Object get(String key) { return null; } } catch (Exception e) { - CSAppUtils.showLog(TAG, e.getLocalizedMessage()); + SDKUtil.showLog(TAG, e.getLocalizedMessage()); return null; } } @@ -335,7 +331,7 @@ public String getHtmlText(String markdownKey) { try { return Processor.process(getString(markdownKey), Configuration.builder().forceExtentedProfile().build()); } catch (Exception e) { - CSAppUtils.showLog(TAG, e.getLocalizedMessage()); + SDKUtil.showLog(TAG, e.getLocalizedMessage()); return null; } } @@ -360,7 +356,7 @@ public ArrayList getMultipleHtmlText(String markdownKey) { } return multipleHtmlStrings; } catch (Exception e) { - CSAppUtils.showLog(TAG, e.getLocalizedMessage()); + SDKUtil.showLog(TAG, e.getLocalizedMessage()); return null; } } @@ -372,8 +368,8 @@ public ArrayList getMultipleHtmlText(String markdownKey) { * *

Example :
*
-     *                       String value = entry.getString("key");
-     *                       
+ * String value = entry.getString("key"); + * */ public String getString(String key) { Object value = get(key); @@ -392,8 +388,8 @@ public String getString(String key) { * *

Example :
*
-     *                       Boolean value = entry.getBoolean("key");
-     *                       
+ * Boolean value = entry.getBoolean("key"); + * */ public Boolean getBoolean(String key) { Object value = get(key); @@ -412,8 +408,8 @@ public Boolean getBoolean(String key) { * *

Example :
*
-     *                       JSONArray value = entry.getJSONArray("key");
-     *                       
+ * JSONArray value = entry.getJSONArray("key"); + * */ public JSONArray getJSONArray(String key) { Object value = get(key); @@ -432,8 +428,8 @@ public JSONArray getJSONArray(String key) { * *

Example :
*
-     *                       JSONObject value = entry.getJSONObject("key");
-     *                       
+ * JSONObject value = entry.getJSONObject("key"); + * */ public JSONObject getJSONObject(String key) { Object value = get(key); @@ -452,8 +448,8 @@ public JSONObject getJSONObject(String key) { * *

Example :
*
-     *                       JSONObject value = entry.getJSONObject("key");
-     *                       
+ * JSONObject value = entry.getJSONObject("key"); + * */ public Number getNumber(String key) { Object value = get(key); @@ -472,8 +468,8 @@ public Number getNumber(String key) { * *

Example :
*
-     *                       int value = entry.getInt("key");
-     *                       
+ * int value = entry.getInt("key"); + * */ public int getInt(String key) { Number value = getNumber(key); @@ -490,8 +486,8 @@ public int getInt(String key) { * *

Example :
*
-     *                       float value = entry.getFloat("key");
-     *                       
+ * float value = entry.getFloat("key"); + * */ public float getFloat(String key) { Number value = getNumber(key); @@ -508,8 +504,8 @@ public float getFloat(String key) { * *

Example :
*
-     *                       double value = entry.getDouble("key");
-     *                       
+ * double value = entry.getDouble("key"); + * */ public double getDouble(String key) { Number value = getNumber(key); @@ -526,8 +522,8 @@ public double getDouble(String key) { * *

Example :
*
-     *                       long value = entry.getLong("key");
-     *                       
+ * long value = entry.getLong("key"); + * */ public long getLong(String key) { Number value = getNumber(key); @@ -544,8 +540,8 @@ public long getLong(String key) { * *

Example :
*
-     *                       short value = entry.getShort("key");
-     *                       
+ * short value = entry.getShort("key"); + * */ public short getShort(String key) { Number value = getNumber(key); @@ -562,16 +558,16 @@ public short getShort(String key) { * *

Example :
*
-     *                       Calendar value = entry.getDate("key");
-     *                       
+ * Calendar value = entry.getDate("key"); + * */ public Calendar getDate(String key) { try { String value = getString(key); - return ContentstackUtil.parseDate(value, null); + return CSUtil.parseDate(value, null); } catch (Exception e) { - CSAppUtils.showLog(TAG, e.getLocalizedMessage()); + SDKUtil.showLog(TAG, e.getLocalizedMessage()); } return null; } @@ -589,9 +585,9 @@ public Calendar getCreateAt() { try { String value = getString("created_at"); - return ContentstackUtil.parseDate(value, null); + return CSUtil.parseDate(value, null); } catch (Exception e) { - CSAppUtils.showLog(TAG, e.getLocalizedMessage()); + SDKUtil.showLog(TAG, e.getLocalizedMessage()); } return null; } @@ -622,9 +618,9 @@ public Calendar getUpdateAt() { try { String value = getString("updated_at"); - return ContentstackUtil.parseDate(value, null); + return CSUtil.parseDate(value, null); } catch (Exception e) { - CSAppUtils.showLog(TAG, e.getLocalizedMessage()); + SDKUtil.showLog(TAG, e.getLocalizedMessage()); } return null; } @@ -654,9 +650,9 @@ public Calendar getDeleteAt() { try { String value = getString("deleted_at"); - return ContentstackUtil.parseDate(value, null); + return CSUtil.parseDate(value, null); } catch (Exception e) { - CSAppUtils.showLog(TAG, e.getLocalizedMessage()); + SDKUtil.showLog(TAG, e.getLocalizedMessage()); } return null; } @@ -681,8 +677,8 @@ public String getDeletedBy() { * *

Example :
*
-     *                       Asset asset = entry.getAsset("key");
-     *                       
+ * Asset asset = entry.getAsset("key"); + * */ public Asset getAsset(String key) { @@ -699,8 +695,8 @@ public Asset getAsset(String key) { * *

Example :
*
-     *                       List asset = entry.getAssets("key");
-     *                       
+ * List asset = entry.getAssets("key"); + * */ public List getAssets(String key) { List assets = new ArrayList<>(); @@ -722,8 +718,8 @@ public List getAssets(String key) { * *

Example :
*
-     *                       Group innerGroup = entry.getGroup("key");
-     *                       
+ * Group innerGroup = entry.getGroup("key"); + * */ public Group getGroup(String key) { @@ -743,8 +739,8 @@ public Group getGroup(String key) { * *

Example :
*
-     *                       Group innerGroup = entry.getGroups("key");
-     *                       
+ * Group innerGroup = entry.getGroups("key"); + * */ public List getGroups(String key) { @@ -813,7 +809,7 @@ public ArrayList getAllEntries(String refKey, String refContentType) { entryInstance = contentTypeInstance.stackInstance.contentType(refContentType).entry(); } catch (Exception e) { entryInstance = new Entry(refContentType); - CSAppUtils.showLog(TAG, e.getLocalizedMessage()); + SDKUtil.showLog(TAG, e.getLocalizedMessage()); } entryInstance.setUid(model.entryUid); entryInstance.ownerEmailId = model.ownerEmailId; @@ -833,7 +829,7 @@ public ArrayList getAllEntries(String refKey, String refContentType) { } } } catch (Exception e) { - CSAppUtils.showLog(TAG, e.getLocalizedMessage()); + SDKUtil.showLog(TAG, e.getLocalizedMessage()); return null; } @@ -867,7 +863,7 @@ public Entry except(String[] fieldUid) { } } } catch (Exception e) { - CSAppUtils.showLog(TAG, "--except-catch|" + e); + SDKUtil.showLog(TAG, "--except-catch|" + e); } return this; } @@ -897,7 +893,7 @@ public Entry includeReference(String referenceField) { otherPostJSON.put("include[]", referenceArray); } } catch (Exception e) { - CSAppUtils.showLog(TAG, "--include Reference-catch|" + e.getLocalizedMessage()); + SDKUtil.showLog(TAG, "--include Reference-catch|" + e.getLocalizedMessage()); } return this; @@ -929,7 +925,7 @@ public Entry includeReference(String[] referenceFields) { otherPostJSON.put("include[]", referenceArray); } } catch (Exception e) { - CSAppUtils.showLog(TAG, "--include Reference-catch|" + e.getLocalizedMessage()); + SDKUtil.showLog(TAG, "--include Reference-catch|" + e.getLocalizedMessage()); } return this; @@ -961,7 +957,7 @@ public Entry only(String[] fieldUid) { } } } catch (Exception e) { - CSAppUtils.showLog(TAG, "--include Reference-catch|" + e.getLocalizedMessage()); + SDKUtil.showLog(TAG, "--include Reference-catch|" + e.getLocalizedMessage()); } return this; @@ -999,7 +995,7 @@ public Entry onlyWithReferenceUid(ArrayList fieldUid, String referenceFi includeReference(referenceFieldUid); } } catch (Exception e) { - CSAppUtils.showLog(TAG, "--onlyWithReferenceUid-catch|" + e.getLocalizedMessage()); + SDKUtil.showLog(TAG, "--onlyWithReferenceUid-catch|" + e.getLocalizedMessage()); } return this; } @@ -1038,7 +1034,7 @@ public Entry exceptWithReferenceUid(ArrayList fieldUid, String reference includeReference(referenceFieldUid); } } catch (Exception e) { - CSAppUtils.showLog(TAG, "--exceptWithReferenceUid-catch|" + e.getLocalizedMessage()); + SDKUtil.showLog(TAG, "--exceptWithReferenceUid-catch|" + e.getLocalizedMessage()); } return this; } @@ -1061,14 +1057,14 @@ protected void setUid(String uid) { * *

Example :
*
-     *                                    Stack stack = Contentstack.stack(context, "apiKey", "deliveryToken",  "stag");
-     *                                    Entry entry = stack.contentType("form_name").entry("entry_uid");
- * entry.fetch(new BuiltResultCallBack() {
- * @Override - * public void onCompletion(ResponseType responseType, BuiltError builtError) { - * - * }
- * });
+ * Stack stack = Contentstack.stack(context, "apiKey", "deliveryToken", "stag"); + * Entry entry = stack.contentType("form_name").entry("entry_uid");
+ * entry.fetch(new BuiltResultCallBack() {
+ * @Override + * public void onCompletion(ResponseType responseType, BuiltError builtError) { + * + * }
+ * });
*/ public void fetch(EntryResultCallBack callBack) { try { @@ -1091,9 +1087,9 @@ public void fetch(EntryResultCallBack callBack) { } String mainStringForMD5 = URL + new JSONObject().toString() + headerAll.toString(); - String md5Value = new CSAppUtils().getMD5FromString(mainStringForMD5.trim()); + String md5Value = new SDKUtil().getMD5FromString(mainStringForMD5.trim()); - File cacheFile = new File(CSAppConstants.cacheFolderName + File.separator + md5Value); + File cacheFile = new File(SDKConstant.cacheFolderName + File.separator + md5Value); switch (cachePolicyForCall) { @@ -1111,28 +1107,17 @@ public void fetch(EntryResultCallBack callBack) { break; case CACHE_ELSE_NETWORK: - if (cacheFile.exists()) { boolean needToSendCall = false; - - // if (maxCacheTimeForCall > 0) { - // needToSendCall = new CSAppUtils().getResponseTimeFromCacheFile(cacheFile, (int) maxCacheTimeForCall); - // } else { - // needToSendCall = new CSAppUtils().getResponseTimeFromCacheFile(cacheFile, (int) defaultCacheTimeInterval); - // } - needToSendCall = new CSAppUtils().getResponseTimeFromCacheFile(cacheFile, (int) maxCacheTimeForCall); - + needToSendCall = new SDKUtil().getResponseTimeFromCacheFile(cacheFile, (int) maxCacheTimeForCall); if (needToSendCall) { fetchFromNetwork(URL, urlQueries, cacheFile.getPath(), callBack); - } else { setCacheModel(cacheFile, callBack); } - } else { fetchFromNetwork(URL, urlQueries, cacheFile.getPath(), callBack); } - break; case CACHE_THEN_NETWORK: @@ -1146,7 +1131,7 @@ public void fetch(EntryResultCallBack callBack) { case NETWORK_ELSE_CACHE: - if (CSAppConstants.isNetworkAvailable) { + if (SDKConstant.IS_NETWORK_AVAILABLE) { fetchFromNetwork(URL, urlQueries, cacheFile.getPath(), callBack); } else { fetchFromCache(cacheFile, callBack); @@ -1157,7 +1142,7 @@ public void fetch(EntryResultCallBack callBack) { } } else { - throwException(CSAppConstants.ErrorMessage_EntryUID, null, callBack); + throwException(SDKConstant.PLEASE_SET_ENTRY_UID, null, callBack); } } catch (Exception e) { throwException(null, e, callBack); @@ -1172,11 +1157,11 @@ private void fetchFromNetwork(String URL, JSONObject urlQueries, String cacheFil setIncludeJSON(urlQueries, callBack); mainJson.put("query", urlQueries); - mainJson.put("_method", CSAppConstants.RequestMethod.GET.toString()); + mainJson.put("_method", SDKConstant.RequestMethod.GET.toString()); HashMap urlParams = getUrlParams(mainJson); - new CSBackgroundTask(this, contentTypeInstance.stackInstance, CSController.FETCHENTRY, URL, getHeader(localHeader), urlParams, new JSONObject(), cacheFilePath, CSAppConstants.callController.ENTRY.toString(), false, CSAppConstants.RequestMethod.GET, callBack); + new CSBackgroundTask(this, contentTypeInstance.stackInstance, SDKController.GET_ENTRY, URL, getHeader(localHeader), urlParams, new JSONObject(), cacheFilePath, SDKConstant.callController.ENTRY.toString(), false, SDKConstant.RequestMethod.GET, callBack); } catch (Exception e) { throwException(null, e, callBack); @@ -1194,18 +1179,18 @@ private void fetchFromCache(File cacheFile, EntryResultCallBack callback) { // } else { // needToSendCall = new CSAppUtils().getResponseTimeFromCacheFile(cacheFile, (int) defaultCacheTimeInterval); // } - needToSendCall = new CSAppUtils().getResponseTimeFromCacheFile(cacheFile, (int) maxCacheTimeForCall); + needToSendCall = new SDKUtil().getResponseTimeFromCacheFile(cacheFile, (int) maxCacheTimeForCall); if (needToSendCall) { error = new Error(); - error.setErrorMessage(CSAppConstants.ErrorMessage_EntryNotFoundInCache); + error.setErrorMessage(SDKConstant.ENTRY_IS_NOT_PRESENT_IN_CACHE); } else { setCacheModel(cacheFile, callback); } } else { error = new Error(); - error.setErrorMessage(CSAppConstants.ErrorMessage_EntryNotFoundInCache); + error.setErrorMessage(SDKConstant.ENTRY_IS_NOT_PRESENT_IN_CACHE); } if (callback != null && error != null) { @@ -1216,7 +1201,7 @@ private void fetchFromCache(File cacheFile, EntryResultCallBack callback) { //Entry modeling from cache. private void setCacheModel(File cacheFile, EntryResultCallBack callback) { - EntryModel model = new EntryModel(CSAppUtils.getJsonFromCacheFile(cacheFile), null, false, true, false); + EntryModel model = new EntryModel(SDKUtil.getJsonFromCacheFile(cacheFile), null, false, true, false); this.resultJson = model.jsonObject; this.ownerEmailId = model.ownerEmailId; this.ownerUid = model.ownerUid; @@ -1248,10 +1233,10 @@ private void setCacheModel(File cacheFile, EntryResultCallBack callback) { */ public void cancelRequest() { - CSAppConstants.cancelledCallController.add(CSAppConstants.callController.ENTRY.toString()); + SDKConstant.cancelledCallController.add(SDKConstant.callController.ENTRY.toString()); if (Contentstack.requestQueue != null) { - Contentstack.requestQueue.cancelAll(CSAppConstants.callController.ENTRY.toString()); + Contentstack.requestQueue.cancelAll(SDKConstant.callController.ENTRY.toString()); } } @@ -1285,7 +1270,7 @@ private HashMap getUrlParams(JSONObject jsonMain) { Object value = queryJSON.opt(key); hashMap.put(key, value); } catch (Exception e) { - CSAppUtils.showLog(TAG, e.getLocalizedMessage()); + SDKUtil.showLog(TAG, e.getLocalizedMessage()); } } @@ -1500,4 +1485,13 @@ public Entry includeEmbeddedItems() { } return this; } + + public Entry includeMetadata() { + try { + otherPostJSON.put("include_metadata", true); + } catch (JSONException e) { + Log.e(TAG, e.getLocalizedMessage()); + } + return this; + } } diff --git a/contentstack/src/main/java/com/contentstack/sdk/EntryModel.java b/contentstack/src/main/java/com/contentstack/sdk/EntryModel.java index e8ccbc0d..46e90f89 100755 --- a/contentstack/src/main/java/com/contentstack/sdk/EntryModel.java +++ b/contentstack/src/main/java/com/contentstack/sdk/EntryModel.java @@ -1,12 +1,10 @@ package com.contentstack.sdk; -import com.contentstack.sdk.utilities.CSAppUtils; - import org.json.JSONArray; import org.json.JSONObject; -import java.util.HashMap; import java.util.Iterator; +import java.util.Objects; import java.util.WeakHashMap; /** @@ -42,9 +40,14 @@ public EntryModel(JSONObject jsonObj, String entryUid, boolean isFromObjectsMode } if (isFromDeltaResponse) { - this.entryUid = (String) (jsonObject != null && jsonObject.isNull("uid") ? " " : jsonObject.opt("uid")); + this.entryUid = (String) (jsonObject != null && jsonObject.isNull("uid") ? " " : Objects.requireNonNull(jsonObject).opt("uid")); } else { - jsonObject = jsonObject != null && jsonObject.opt("entry") == null ? null : jsonObject.optJSONObject("entry"); + if (jsonObject != null && jsonObject.opt("entry") == null) { + jsonObject = null; + } else { + assert jsonObject != null; + jsonObject = jsonObject.optJSONObject("entry"); + } } } if (jsonObject != null && jsonObject.has("uid")) { @@ -65,6 +68,7 @@ public EntryModel(JSONObject jsonObj, String entryUid, boolean isFromObjectsMode if (jsonObject != null && jsonObject.has("_metadata")) { JSONObject _metadataJSON = jsonObject.optJSONObject("_metadata"); + assert _metadataJSON != null; Iterator iterator = _metadataJSON.keys(); _metadata = new WeakHashMap<>(); while (iterator.hasNext()) { @@ -75,33 +79,23 @@ public EntryModel(JSONObject jsonObj, String entryUid, boolean isFromObjectsMode _metadata.put(key, _metadataJSON.optString(key)); } } else if (jsonObject != null && jsonObject.has("publish_details")) { - - JSONArray publishArray = jsonObject.optJSONArray("publish_details"); - for (int i = 0; i < publishArray.length(); i++) { - JSONObject jsonObject = publishArray.optJSONObject(i); - Iterator iterator = jsonObject.keys(); - HashMap hashMap = new HashMap<>(); - while (iterator.hasNext()) { - String key = iterator.next(); - hashMap.put(key, jsonObject.opt(key)); - } - } - + JSONObject publishDetailsObj = jsonObject.optJSONObject("publish_details"); _metadata = new WeakHashMap<>(); - _metadata.put("publish_details", publishArray); + _metadata.put("publish_details", publishDetailsObj); } - if (jsonObject != null && jsonObject.has("_owner") && (jsonObject.opt("_owner") != null) && (!jsonObject.opt("_owner").toString().equalsIgnoreCase("null"))) { JSONObject ownerObject = jsonObject.optJSONObject("_owner"); + assert ownerObject != null; if (ownerObject.has("email") && ownerObject.opt("email") != null) { ownerEmailId = (String) ownerObject.opt("email"); } if (ownerObject.has("uid") && ownerObject.opt("uid") != null) { - ownerUid = ownerObject.opt("uid").toString(); + ownerUid = Objects.requireNonNull(ownerObject.opt("uid")).toString(); } JSONObject owner = jsonObject.optJSONObject("_owner"); + assert owner != null; Iterator iterator = owner.keys(); ownerMap = new WeakHashMap<>(); while (iterator.hasNext()) { @@ -110,6 +104,7 @@ public EntryModel(JSONObject jsonObj, String entryUid, boolean isFromObjectsMode } } + assert jsonObject != null; tagsArray = (JSONArray) jsonObject.opt("tags"); if (tagsArray != null && tagsArray.length() > 0) { int count = tagsArray.length(); @@ -121,7 +116,7 @@ public EntryModel(JSONObject jsonObj, String entryUid, boolean isFromObjectsMode } catch (Exception e) { - CSAppUtils.showLog("EntryModel", e.getLocalizedMessage()); + SDKUtil.showLog("EntryModel", e.getLocalizedMessage()); } } diff --git a/contentstack/src/main/java/com/contentstack/sdk/Group.java b/contentstack/src/main/java/com/contentstack/sdk/Group.java index bfe35199..2d27905b 100644 --- a/contentstack/src/main/java/com/contentstack/sdk/Group.java +++ b/contentstack/src/main/java/com/contentstack/sdk/Group.java @@ -2,8 +2,6 @@ import android.text.TextUtils; -import com.contentstack.sdk.utilities.CSAppUtils; -import com.contentstack.sdk.utilities.ContentstackUtil; import com.contentstack.txtmark.Configuration; import com.contentstack.txtmark.Processor; @@ -64,7 +62,7 @@ public Object get(String key) { return null; } } catch (Exception e) { - CSAppUtils.showLog(TAG, "-----------------get|" + e); + SDKUtil.showLog(TAG, "-----------------get|" + e); return null; } } @@ -84,7 +82,7 @@ public String getHtmlText(String markdownKey) { try { return Processor.process(getString(markdownKey), Configuration.builder().forceExtentedProfile().build()); } catch (Exception e) { - CSAppUtils.showLog(TAG, "-----------------getHtmlText|" + e); + SDKUtil.showLog(TAG, "-----------------getHtmlText|" + e); return null; } } @@ -111,7 +109,7 @@ public ArrayList getMultipleHtmlText(String markdownKey) { return multipleHtmlStrings; } catch (Exception e) { - CSAppUtils.showLog(TAG, e.getLocalizedMessage()); + SDKUtil.showLog(TAG, e.getLocalizedMessage()); return null; } } @@ -320,9 +318,9 @@ public Calendar getDate(String key) { try { String value = getString(key); - return ContentstackUtil.parseDate(value, null); + return CSUtil.parseDate(value, null); } catch (Exception e) { - CSAppUtils.showLog(TAG, "-----------------getDate|" + e); + SDKUtil.showLog(TAG, "-----------------getDate|" + e); } return null; } @@ -469,7 +467,7 @@ public ArrayList getAllEntries(String refKey, String refContentType) { entryInstance = stackInstance.contentType(refContentType).entry(); } catch (Exception e) { entryInstance = new Entry(refContentType); - CSAppUtils.showLog("BuiltObject", e.getLocalizedMessage()); + SDKUtil.showLog("BuiltObject", e.getLocalizedMessage()); } entryInstance.setUid(model.entryUid); entryInstance.ownerEmailId = model.ownerEmailId; @@ -489,7 +487,7 @@ public ArrayList getAllEntries(String refKey, String refContentType) { } } } catch (Exception e) { - CSAppUtils.showLog(TAG, e.getLocalizedMessage()); + SDKUtil.showLog(TAG, e.getLocalizedMessage()); return null; } diff --git a/contentstack/src/main/java/com/contentstack/sdk/IURLRequestHTTP.java b/contentstack/src/main/java/com/contentstack/sdk/IURLRequestHTTP.java index e0e642db..67b24d3e 100755 --- a/contentstack/src/main/java/com/contentstack/sdk/IURLRequestHTTP.java +++ b/contentstack/src/main/java/com/contentstack/sdk/IURLRequestHTTP.java @@ -2,8 +2,6 @@ import android.util.ArrayMap; -import com.contentstack.sdk.utilities.CSAppConstants; - import org.json.JSONObject; /** @@ -17,9 +15,9 @@ public interface IURLRequestHTTP { public ArrayMap getHeaders(); - public void setRequestMethod(CSAppConstants.RequestMethod requestMethod); + public void setRequestMethod(SDKConstant.RequestMethod requestMethod); - public CSAppConstants.RequestMethod getRequestMethod(); + public SDKConstant.RequestMethod getRequestMethod(); public JSONObject getResponse(); diff --git a/contentstack/src/main/java/com/contentstack/sdk/InvalidInputException.java b/contentstack/src/main/java/com/contentstack/sdk/InvalidInputException.java new file mode 100644 index 00000000..37720f1f --- /dev/null +++ b/contentstack/src/main/java/com/contentstack/sdk/InvalidInputException.java @@ -0,0 +1,32 @@ +package com.contentstack.sdk; + + +/** + * This class extends the Exception class, which is the base class for all checked exceptions in Java. + * The InvalidInputException class takes a String message as input and passes it to the + * Exception class constructor using the super keyword. + *

+ * You can use this custom exception class to throw an exception when invalid input is detected in your code. + *

For example: + *

+ * + * + * public void processInput(String input) throws InvalidInputException { + * if (input == null || input.isEmpty()) { + * throw new InvalidInputException("Input cannot be null or empty"); + * } + * // Process the input here + * } + * + */ +public class InvalidInputException extends Exception { + /** + * Instantiates a new Invalid input exception. + * + * @param message the message + */ + public InvalidInputException(String message) { + super(message); + } +} + diff --git a/contentstack/src/main/java/com/contentstack/sdk/Query.java b/contentstack/src/main/java/com/contentstack/sdk/Query.java index 9bb7441f..7c540415 100755 --- a/contentstack/src/main/java/com/contentstack/sdk/Query.java +++ b/contentstack/src/main/java/com/contentstack/sdk/Query.java @@ -4,10 +4,6 @@ import android.util.ArrayMap; import android.util.Log; -import com.contentstack.sdk.utilities.CSAppConstants; -import com.contentstack.sdk.utilities.CSAppUtils; -import com.contentstack.sdk.utilities.CSController; - import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -131,10 +127,10 @@ public Query where(String key, Object value) { if (key != null && value != null) { queryValueJSON.put(key, value); } else { - throwException("where", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("where", SDKConstant.PROVIDE_VALID_PARAMS, null); } } catch (Exception e) { - throwException("where", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("where", SDKConstant.PROVIDE_VALID_PARAMS, e); } return this; @@ -158,13 +154,12 @@ public Query where(String key, Object value) { public Query addQuery(String key, String value) { try { if (key != null && value != null) { - urlQueries.put(key, value); } else { - throwException("and", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("and", SDKConstant.PROVIDE_VALID_PARAMS, null); } } catch (Exception e) { - throwException("and", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("and", SDKConstant.PROVIDE_VALID_PARAMS, e); } return this; } @@ -186,7 +181,7 @@ public Query removeQuery(String key) { urlQueries.remove(key); } } catch (Exception e) { - throwException("and", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("and", SDKConstant.PROVIDE_VALID_PARAMS, e); } return this; } @@ -226,10 +221,10 @@ public Query and(ArrayList queryObjects) { queryValueJSON.put("$and", orValueJson); } catch (Exception e) { - throwException("and", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("and", SDKConstant.PROVIDE_VALID_PARAMS, e); } } else { - throwException("and", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("and", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; @@ -271,10 +266,10 @@ public Query or(ArrayList queryObjects) { queryValueJSON.put("$or", orValueJson); } catch (Exception e) { - throwException("or", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("or", SDKConstant.PROVIDE_VALID_PARAMS, e); } } else { - throwException("or", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("or", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; @@ -314,10 +309,10 @@ public Query lessThan(String key, Object value) { } } catch (Exception e) { - throwException("lessThan", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("lessThan", SDKConstant.PROVIDE_VALID_PARAMS, e); } } else { - throwException("lessThan", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("lessThan", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; @@ -358,10 +353,10 @@ public Query lessThanOrEqualTo(String key, Object value) { } } catch (Exception e) { - throwException("lessThanOrEqualTo", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("lessThanOrEqualTo", SDKConstant.PROVIDE_VALID_PARAMS, e); } } else { - throwException("lessThanOrEqualTo", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("lessThanOrEqualTo", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; } @@ -400,10 +395,10 @@ public Query greaterThan(String key, Object value) { } } catch (Exception e) { - throwException("greaterThan", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("greaterThan", SDKConstant.PROVIDE_VALID_PARAMS, e); } } else { - throwException("greaterThan", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("greaterThan", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; @@ -443,10 +438,10 @@ public Query greaterThanOrEqualTo(String key, Object value) { } } catch (Exception e) { - throwException("greaterThanOrEqualTo", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("greaterThanOrEqualTo", SDKConstant.PROVIDE_VALID_PARAMS, e); } } else { - throwException("greaterThanOrEqualTo", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("greaterThanOrEqualTo", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; @@ -492,7 +487,7 @@ public Query notEqualTo(String key, Object value) { } } else { - throwException("notEqualTo", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("notEqualTo", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; @@ -536,10 +531,10 @@ public Query containedIn(String key, Object[] values) { } } catch (Exception e) { - throwException("containedIn", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("containedIn", SDKConstant.PROVIDE_VALID_PARAMS, e); } } else { - throwException("containedIn", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("containedIn", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; @@ -581,10 +576,10 @@ public Query notContainedIn(String key, Object[] values) { } } catch (Exception e) { - throwException("containedIn", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("containedIn", SDKConstant.PROVIDE_VALID_PARAMS, e); } } else { - throwException("containedIn", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("containedIn", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; @@ -622,10 +617,10 @@ public Query exists(String key) { queryValueJSON.put(key, queryValue); } } catch (Exception e) { - throwException("exists", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("exists", SDKConstant.PROVIDE_VALID_PARAMS, e); } } else { - throwException("exists", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("exists", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; @@ -661,10 +656,10 @@ public Query notExists(String key) { queryValueJSON.put(key, queryValue); } } catch (Exception e) { - throwException("notExists", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("notExists", SDKConstant.PROVIDE_VALID_PARAMS, e); } } else { - throwException("notExists", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("notExists", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; @@ -718,7 +713,7 @@ public Query includeReference(String[] keys) { objectUidForInclude.put(key); } } else { - throwException("includeReference", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("includeReference", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; } @@ -747,10 +742,10 @@ public Query tags(String[] tags) { } urlQueries.put("tags", tagsvalue); } else { - throwException("tags", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("tags", SDKConstant.PROVIDE_VALID_PARAMS, null); } } catch (Exception e) { - throwException("tags", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("tags", SDKConstant.PROVIDE_VALID_PARAMS, e); } return this; } @@ -775,10 +770,10 @@ public Query ascending(String key) { try { urlQueries.put("asc", key); } catch (Exception e) { - throwException("ascending", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("ascending", SDKConstant.PROVIDE_VALID_PARAMS, e); } } else { - throwException("ascending", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("ascending", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; } @@ -803,10 +798,10 @@ public Query descending(String key) { try { urlQueries.put("desc", key); } catch (Exception e) { - throwException("descending", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("descending", SDKConstant.PROVIDE_VALID_PARAMS, e); } } else { - throwException("descending", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("descending", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; } @@ -839,10 +834,10 @@ public Query except(ArrayList fieldUid) { objectUidForExcept.put(fieldUid.get(i)); } } else { - throwException("except", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("except", SDKConstant.PROVIDE_VALID_PARAMS, null); } } catch (Exception e) { - throwException("except", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("except", SDKConstant.PROVIDE_VALID_PARAMS, e); } return this; } @@ -872,10 +867,10 @@ public Query except(String[] fieldUids) { objectUidForExcept.put(fieldUids[i]); } } else { - throwException("except", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("except", SDKConstant.PROVIDE_VALID_PARAMS, null); } } catch (Exception e) { - throwException("except", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("except", SDKConstant.PROVIDE_VALID_PARAMS, e); } return this; } @@ -905,10 +900,10 @@ public Query only(String[] fieldUid) { objectUidForOnly.put(fieldUid[i]); } } else { - throwException("only", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("only", SDKConstant.PROVIDE_VALID_PARAMS, null); } } catch (Exception e) { - throwException("only", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("only", SDKConstant.PROVIDE_VALID_PARAMS, e); } return this; } @@ -950,10 +945,10 @@ public Query onlyWithReferenceUid(ArrayList fieldUid, String referenceFi objectUidForInclude.put(referenceFieldUid); } else { - throwException("onlyWithReferenceUid", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("onlyWithReferenceUid", SDKConstant.PROVIDE_VALID_PARAMS, null); } } catch (Exception e) { - throwException("onlyWithReferenceUid", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("onlyWithReferenceUid", SDKConstant.PROVIDE_VALID_PARAMS, e); } return this; } @@ -995,10 +990,10 @@ public Query exceptWithReferenceUid(ArrayList fieldUid, String reference objectUidForInclude.put(referenceFieldUid); } else { - throwException("exceptWithReferenceUid", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("exceptWithReferenceUid", SDKConstant.PROVIDE_VALID_PARAMS, null); } } catch (Exception e) { - throwException("exceptWithReferenceUid", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("exceptWithReferenceUid", SDKConstant.PROVIDE_VALID_PARAMS, e); } return this; } @@ -1022,7 +1017,7 @@ public Query count() { try { urlQueries.put("count", "true"); } catch (Exception e) { - throwException("count", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("count", SDKConstant.PROVIDE_VALID_PARAMS, e); } return this; } @@ -1046,7 +1041,7 @@ public Query includeCount() { try { urlQueries.put("include_count", "true"); } catch (Exception e) { - throwException("includeCount", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("includeCount", SDKConstant.PROVIDE_VALID_PARAMS, e); } return this; } @@ -1071,7 +1066,7 @@ public Query includeContentType() { urlQueries.put("include_content_type", true); urlQueries.put("include_global_field_schema", true); } catch (Exception e) { - throwException("include_content_type", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("include_content_type", SDKConstant.PROVIDE_VALID_PARAMS, e); } return this; } @@ -1095,10 +1090,10 @@ private Query beforeUid(String uid) { try { urlQueries.put("before_uid", uid); } catch (Exception e) { - throwException("beforeUid", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("beforeUid", SDKConstant.PROVIDE_VALID_PARAMS, e); } } else { - throwException("beforeUid", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("beforeUid", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; } @@ -1121,10 +1116,10 @@ private Query afterUid(String uid) { try { urlQueries.put("after_uid", uid); } catch (Exception e) { - throwException("afterUid", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("afterUid", SDKConstant.PROVIDE_VALID_PARAMS, e); } } else { - throwException("afterUid", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("afterUid", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; } @@ -1149,7 +1144,7 @@ public Query skip(int number) { try { urlQueries.put("skip", number); } catch (Exception e) { - throwException("skip", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("skip", SDKConstant.PROVIDE_VALID_PARAMS, e); } return this; } @@ -1173,7 +1168,7 @@ public Query limit(int number) { try { urlQueries.put("limit", number); } catch (Exception e) { - throwException("limit", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("limit", SDKConstant.PROVIDE_VALID_PARAMS, e); } return this; } @@ -1217,10 +1212,10 @@ public Query regex(String key, String regex) { } } catch (Exception e) { - throwException("matches", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("matches", SDKConstant.PROVIDE_VALID_PARAMS, e); } } else { - throwException("matches", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("matches", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; } @@ -1274,10 +1269,10 @@ public Query regex(String key, String regex, String modifiers) { } } catch (Exception e) { - throwException("matches", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("matches", SDKConstant.PROVIDE_VALID_PARAMS, e); } } else { - throwException("matches", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("matches", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; } @@ -1310,10 +1305,10 @@ public Query language(Language language) { } } catch (Exception e) { - throwException("language", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("language", SDKConstant.PROVIDE_VALID_PARAMS, e); } } else { - throwException("language", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("language", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; @@ -1340,10 +1335,10 @@ public Query locale(String locale) { } } catch (Exception e) { - throwException("locale", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("locale", SDKConstant.PROVIDE_VALID_PARAMS, e); } } else { - throwException("locale", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("locale", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; @@ -1371,10 +1366,10 @@ public Query search(String value) { urlQueries.put("typeahead", value); } } catch (Exception e) { - throwException("value", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("value", SDKConstant.PROVIDE_VALID_PARAMS, e); } } else { - throwException("value", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("value", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; @@ -1426,7 +1421,7 @@ public Query find(QueryResultsCallBack callback) { execQuery(null, callback, false); } else { - throwException("find", CSAppConstants.ErrorMessage_FormName, null); + throwException("find", SDKConstant.PLEASE_SET_CONTENT_TYPE_NAME, null); error = new Error(); error.setErrorMessage(errorString); error.setErrors(errorHashMap); @@ -1437,7 +1432,7 @@ public Query find(QueryResultsCallBack callback) { error.setErrors(errorHashMap); } } catch (Exception e) { - throwException("find", CSAppConstants.ErrorMessage_JsonNotProper, null); + throwException("find", SDKConstant.PLEASE_PROVIDE_VALID_JSON, null); error = new Error(); error.setErrorMessage(errorString); error.setErrors(errorHashMap); @@ -1487,7 +1482,7 @@ public Query findOne(SingleQueryResultCallback callBack) { } } else { - throwException("find", CSAppConstants.ErrorMessage_FormName, null); + throwException("find", SDKConstant.PLEASE_SET_CONTENT_TYPE_NAME, null); error = new Error(); error.setErrorMessage(errorString); error.setErrors(errorHashMap); @@ -1498,7 +1493,7 @@ public Query findOne(SingleQueryResultCallback callBack) { error.setErrors(errorHashMap); } } catch (Exception e) { - throwException("find", CSAppConstants.ErrorMessage_JsonNotProper, null); + throwException("find", SDKConstant.PLEASE_PROVIDE_VALID_JSON, null); error = new Error(); error.setErrorMessage(errorString); error.setErrors(errorHashMap); @@ -1521,10 +1516,10 @@ public Query findOne(SingleQueryResultCallback callBack) { *

*/ public void cancelRequest() { - CSAppConstants.cancelledCallController.add(CSAppConstants.callController.QUERY.toString()); + SDKConstant.cancelledCallController.add(SDKConstant.callController.QUERY.toString()); if (Contentstack.requestQueue != null) { - Contentstack.requestQueue.cancelAll(CSAppConstants.callController.QUERY.toString()); + Contentstack.requestQueue.cancelAll(SDKConstant.callController.QUERY.toString()); } } @@ -1578,7 +1573,7 @@ protected void setQueryJson(QueryResultsCallBack callback) { } } catch (Exception e) { - throwException("find", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("find", SDKConstant.PROVIDE_VALID_PARAMS, e); } } @@ -1592,16 +1587,16 @@ protected void execQuery(SingleQueryResultCallback callBack, QueryResultsCallBac ArrayMap headers = getHeader(localHeader); if (headers.size() < 1) { - throwException("find", CSAppConstants.ErrorMessage_CalledDefaultMethod, null); + throwException("find", SDKConstant.STACK_FIRST, null); } else { if (headers.containsKey("environment")) { urlQueries.put("environment", headers.get("environment")); } mainJSON.put("query", urlQueries); - mainJSON.put("_method", CSAppConstants.RequestMethod.GET.toString()); + mainJSON.put("_method", SDKConstant.RequestMethod.GET.toString()); String mainStringForMD5 = URL + mainJSON.toString() + headers.toString(); - String md5Value = new CSAppUtils().getMD5FromString(mainStringForMD5.trim()); - File cacheFile = new File(CSAppConstants.cacheFolderName + File.separator + md5Value); + String md5Value = new SDKUtil().getMD5FromString(mainStringForMD5.trim()); + File cacheFile = new File(SDKConstant.cacheFolderName + File.separator + md5Value); CachePolicy cachePolicy = CachePolicy.NETWORK_ONLY;//contentTypeInstance.stackInstance.globalCachePolicyForCall; if (cachePolicyForCall != null) { cachePolicy = cachePolicyForCall; @@ -1620,9 +1615,9 @@ protected void execQuery(SingleQueryResultCallback callBack, QueryResultsCallBac if (cacheFile.exists()) { boolean needToSendCall = false; if (maxCacheTimeForCall > 0) { - needToSendCall = new CSAppUtils().getResponseTimeFromCacheFile(cacheFile, (int) maxCacheTimeForCall); + needToSendCall = new SDKUtil().getResponseTimeFromCacheFile(cacheFile, (int) maxCacheTimeForCall); } else { - needToSendCall = new CSAppUtils().getResponseTimeFromCacheFile(cacheFile, (int) defaultCacheTimeInterval); + needToSendCall = new SDKUtil().getResponseTimeFromCacheFile(cacheFile, (int) defaultCacheTimeInterval); } if (needToSendCall) { fetchFromNetwork(URL, headers, mainJSON, cacheFile.getPath(), callback, callBack); @@ -1634,7 +1629,7 @@ protected void execQuery(SingleQueryResultCallback callBack, QueryResultsCallBac } break; case NETWORK_ELSE_CACHE: - if (CSAppConstants.isNetworkAvailable) { + if (SDKConstant.IS_NETWORK_AVAILABLE) { fetchFromNetwork(URL, headers, mainJSON, cacheFile.getPath(), callback, callBack); } else { fetchFromCache(cacheFile, callback, callBack); @@ -1655,7 +1650,7 @@ protected void execQuery(SingleQueryResultCallback callBack, QueryResultsCallBac } catch (Exception e) { - throwException("find", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("find", SDKConstant.PROVIDE_VALID_PARAMS, e); } } @@ -1665,9 +1660,9 @@ private void fetchFromNetwork(String URL, ArrayMap headers, JSON HashMap urlParams = getUrlParams(jsonMain); if (resultCallback != null) { - new CSBackgroundTask(this, contentTypeInstance.stackInstance, CSController.SINGLEQUERYOBJECT, URL, headers, urlParams, new JSONObject(), cacheFilePath, CSAppConstants.callController.QUERY.toString(), CSAppConstants.RequestMethod.GET, resultCallback); + new CSBackgroundTask(this, contentTypeInstance.stackInstance, SDKController.SINGLE_QUERY_ENTRIES, URL, headers, urlParams, new JSONObject(), cacheFilePath, SDKConstant.callController.QUERY.toString(), SDKConstant.RequestMethod.GET, resultCallback); } else { - new CSBackgroundTask(this, contentTypeInstance.stackInstance, CSController.QUERYOBJECT, URL, headers, urlParams, new JSONObject(), cacheFilePath, CSAppConstants.callController.QUERY.toString(), CSAppConstants.RequestMethod.GET, callback); + new CSBackgroundTask(this, contentTypeInstance.stackInstance, SDKController.GET_QUERY_ENTRIES, URL, headers, urlParams, new JSONObject(), cacheFilePath, SDKConstant.callController.QUERY.toString(), SDKConstant.RequestMethod.GET, callback); } } @@ -1684,7 +1679,7 @@ private HashMap getUrlParams(JSONObject jsonMain) { Object value = queryJSON.opt(key); hashMap.put(key, value); } catch (Exception e) { - CSAppUtils.showLog(TAG, "----------------setQueryJson" + e.toString()); + SDKUtil.showLog(TAG, "----------------setQueryJson" + e.toString()); } } @@ -1702,21 +1697,21 @@ private void fetchFromCache(File cacheFile, QueryResultsCallBack callback, Singl boolean needToSendCall = false; if (maxCacheTimeForCall > 0) { - needToSendCall = new CSAppUtils().getResponseTimeFromCacheFile(cacheFile, (int) maxCacheTimeForCall); + needToSendCall = new SDKUtil().getResponseTimeFromCacheFile(cacheFile, (int) maxCacheTimeForCall); } else { - needToSendCall = new CSAppUtils().getResponseTimeFromCacheFile(cacheFile, (int) defaultCacheTimeInterval); + needToSendCall = new SDKUtil().getResponseTimeFromCacheFile(cacheFile, (int) defaultCacheTimeInterval); } if (needToSendCall) { error = new Error(); - error.setErrorMessage(CSAppConstants.ErrorMessage_EntryNotFoundInCache); + error.setErrorMessage(SDKConstant.ENTRY_IS_NOT_PRESENT_IN_CACHE); } else { setCacheModel(cacheFile, callback, callBack); } } else { error = new Error(); - error.setErrorMessage(CSAppConstants.ErrorMessage_EntryNotFoundInCache); + error.setErrorMessage(SDKConstant.ENTRY_IS_NOT_PRESENT_IN_CACHE); } if (callback != null && error != null) { @@ -1728,7 +1723,7 @@ private void fetchFromCache(File cacheFile, QueryResultsCallBack callback, Singl //ENTRY modeling from cache. private void setCacheModel(File cacheFile, QueryResultsCallBack callback, SingleQueryResultCallback callBack) { - EntriesModel model = new EntriesModel(CSAppUtils.getJsonFromCacheFile(cacheFile), null, true); + EntriesModel model = new EntriesModel(SDKUtil.getJsonFromCacheFile(cacheFile), null, true); List entries = new ArrayList<>(); List objects = model.objectList; int countObject = objects.size(); @@ -1741,7 +1736,7 @@ private void setCacheModel(File cacheFile, QueryResultsCallBack callback, Single } catch (Exception e) { entry = new Entry(formName); entry.setUid(((EntryModel) objects.get(i)).entryUid); - CSAppUtils.showLog(TAG, "----------------getResultObject" + e.toString()); + SDKUtil.showLog(TAG, "----------------getResultObject" + e.toString()); } entry.resultJson = ((EntryModel) objects.get(i)).jsonObject; @@ -1883,10 +1878,10 @@ public Query addParam(String key, String value) { if (key != null && value != null) { urlQueries.put(key, value); } else { - throwException("and", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("and", SDKConstant.PROVIDE_VALID_PARAMS, null); } } catch (Exception e) { - throwException("and", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("and", SDKConstant.PROVIDE_VALID_PARAMS, e); } return this; } @@ -1943,10 +1938,10 @@ public Query whereIn(String key, Query queryObject) { inQueryObj.put("$in_query", queryObject.queryValueJSON.toString()); queryValueJSON.put(key, inQueryObj); } catch (Exception e) { - throwException("in_query", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("in_query", SDKConstant.PROVIDE_VALID_PARAMS, e); } } else { - throwException("in_query", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("in_query", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; } @@ -1974,10 +1969,10 @@ public Query whereNotIn(String key, Query queryObject) { inQueryObj.put("$nin_query", queryObject.queryValueJSON.toString()); queryValueJSON.put(key, inQueryObj); } catch (Exception e) { - throwException("nin_query", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("nin_query", SDKConstant.PROVIDE_VALID_PARAMS, e); } } else { - throwException("nin_query", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("nin_query", SDKConstant.PROVIDE_VALID_PARAMS, null); } return this; } @@ -2021,5 +2016,14 @@ public Query includeEmbeddedItems() { return this; } + public Query includeMetadata() { + try { + urlQueries.put("include_metadata", true); + } catch (JSONException e) { + Log.e(TAG, e.getLocalizedMessage()); + } + return this; + } + } diff --git a/contentstack/src/main/java/com/contentstack/sdk/QueryResult.java b/contentstack/src/main/java/com/contentstack/sdk/QueryResult.java index 1177ea44..e6dc174b 100755 --- a/contentstack/src/main/java/com/contentstack/sdk/QueryResult.java +++ b/contentstack/src/main/java/com/contentstack/sdk/QueryResult.java @@ -1,7 +1,5 @@ package com.contentstack.sdk; -import com.contentstack.sdk.utilities.CSAppUtils; - import org.json.JSONArray; import org.json.JSONObject; @@ -111,7 +109,7 @@ protected void setJSON(JSONObject jsonobject, List objectList) { } } catch (Exception e) { - CSAppUtils.showLog(TAG, "----------------------QueryResult--setJSON--" + e.toString()); + SDKUtil.showLog(TAG, "----------------------QueryResult--setJSON--" + e.toString()); } } } diff --git a/contentstack/src/main/java/com/contentstack/sdk/SDKConstant.java b/contentstack/src/main/java/com/contentstack/sdk/SDKConstant.java new file mode 100755 index 00000000..5438415d --- /dev/null +++ b/contentstack/src/main/java/com/contentstack/sdk/SDKConstant.java @@ -0,0 +1,52 @@ +package com.contentstack.sdk; + +import java.util.ArrayList; + +public class SDKConstant { + + protected static final String ENVIRONMENT = "environment"; + protected static final String CACHE = "ContentstackCache"; + public static final boolean debug = false; + public static boolean IS_NETWORK_AVAILABLE = true; + public static String PROTOCOL = "https://"; + public static String SDK_VERSION = "3.12.0"; + public final static int NO_NETWORK_CONNECTION = 408; + public final static int TimeOutDuration = 30000; // timeout in millisecond + public final static int NumRetry = 0; + public final static int BackOFMultiplier = 0; + public static ArrayList cancelledCallController = new ArrayList(); + public static String cacheFolderName; + + public static enum RequestMethod { + GET, + POST, + PUT, + DELETE + } + + public static enum callController { + QUERY, + ENTRY, + STACK, + ASSET, + SYNC, + CONTENT_TYPES, + ASSET_LIBRARY; + } + + + public final static String PLEASE_PROVIDE_VALID_JSON = "Please provide valid JSON."; + public final static String EMPTY_CREDENTIALS_NOT_ALLOWED = "Empty credentials are not allowed, Please provide a valid one"; + public final static String PLEASE_SET_CONTENT_TYPE_NAME = "Please set contentType name."; + public final static String PLEASE_SET_ENTRY_UID = "Please set entry uid."; + public final static String CONNECTION_ERROR = "Connection error"; + public final static String AUTHENTICATION_NOT_PRESENT = "Authentication Not present."; + public final static String PARSING_ERROR = "Parsing Error."; + public final static String TRY_AGAIN = "Server interaction went wrong, Please try again."; + public final static String ERROR_MESSAGE_DEFAULT = "Oops! Something went wrong. Please try again."; + public final static String NOT_AVAILABLE = "Network not available."; + public final static String STACK_FIRST = "You must called Contentstack.stack() first"; + public final static String PROVIDE_VALID_PARAMS = "Please provide valid params."; + public final static String ENTRY_IS_NOT_PRESENT_IN_CACHE = "ENTRY is not present in cache"; + public final static String NETWORK_CALL_RESPONSE = "Error while saving network call response."; +} diff --git a/contentstack/src/main/java/com/contentstack/sdk/SDKController.java b/contentstack/src/main/java/com/contentstack/sdk/SDKController.java new file mode 100755 index 00000000..c695e83e --- /dev/null +++ b/contentstack/src/main/java/com/contentstack/sdk/SDKController.java @@ -0,0 +1,44 @@ +package com.contentstack.sdk; + +/** + * The type Sdk controller. + * + * @author contentstack.com, Inc + */ +public class SDKController { + + /** + * The constant GET_QUERY_ENTRIES. + */ + public static final String GET_QUERY_ENTRIES = "getQueryEntries"; + + /** + * The constant SINGLE_QUERY_ENTRIES. + */ + public static final String SINGLE_QUERY_ENTRIES = "getSingleQueryEntries"; + + /** + * The constant GET_ENTRY. + */ + public static final String GET_ENTRY = "getEntry"; + + /** + * The constant GET_ALL_ASSETS. + */ + public static final String GET_ALL_ASSETS = "getAllAssets"; + + /** + * The constant GET_ASSETS. + */ + public static final String GET_ASSETS = "getAssets"; + + /** + * The constant GET_SYNC. + */ + public static final String GET_SYNC = "getSync"; + + /** + * The constant GET_CONTENT_TYPES. + */ + public static final String GET_CONTENT_TYPES = "getContentTypes"; +} diff --git a/contentstack/src/main/java/com/contentstack/sdk/utilities/CSAppUtils.java b/contentstack/src/main/java/com/contentstack/sdk/SDKUtil.java similarity index 84% rename from contentstack/src/main/java/com/contentstack/sdk/utilities/CSAppUtils.java rename to contentstack/src/main/java/com/contentstack/sdk/SDKUtil.java index b8e1ed09..460b41a8 100755 --- a/contentstack/src/main/java/com/contentstack/sdk/utilities/CSAppUtils.java +++ b/contentstack/src/main/java/com/contentstack/sdk/SDKUtil.java @@ -1,6 +1,11 @@ -package com.contentstack.sdk.utilities; +package com.contentstack.sdk; import android.annotation.SuppressLint; +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.os.SystemClock; import android.util.Log; import org.json.JSONObject; @@ -21,17 +26,28 @@ /** * @author contentstack.com */ -public class CSAppUtils { +public class SDKUtil { - public CSAppUtils() { + private static final String CLEAR_CACHE = "StartContentStackClearingCache"; + + public SDKUtil() { } public static void showLog(String tag, String message) { - if (CSAppConstants.debug) { + if (SDKConstant.debug) { Log.i(tag, message); } } + protected static void clearCache(Context context) { + Intent alarmIntent = new Intent(CLEAR_CACHE); + alarmIntent.setPackage(context.getPackageName()); + int flag = PendingIntent.FLAG_UPDATE_CURRENT; + if (android.os.Build.VERSION.SDK_INT >= 23) flag = PendingIntent.FLAG_IMMUTABLE | flag; + PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, flag); + AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); + alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), AlarmManager.INTERVAL_DAY, pendingIntent); + } /** * To check if required response within given time window available in cache @@ -152,8 +168,8 @@ public String getMD5FromString(String value) { * @return {@link Calendar} object. * @throws ParseException

Example :
*
-     *                                                                        Util.parseDate(dateString, TimeZone.getDefault());
-     *                                                                      
+ * Util.parseDate(dateString, TimeZone.getDefault()); + * */ public static Calendar parseDate(String date, TimeZone timeZone) { ArrayList knownPatterns = new ArrayList<>(); @@ -187,8 +203,8 @@ public static Calendar parseDate(String date, TimeZone timeZone) { * @return {@link Calendar} object. * @throws ParseException

Example :
*
-     *                                                                        BuiltUtil.parseDate(dateString, "yyyy-MM-dd'T'HH:mm:ssZ", TimeZone.getTimeZone("GMT"));
-     *                                                                      
+ * BuiltUtil.parseDate(dateString, "yyyy-MM-dd'T'HH:mm:ssZ", TimeZone.getTimeZone("GMT")); + * */ @SuppressLint("SimpleDateFormat") public static Calendar parseDate(String date, String dateFormat, TimeZone timeZone) throws ParseException { diff --git a/contentstack/src/main/java/com/contentstack/sdk/Stack.java b/contentstack/src/main/java/com/contentstack/sdk/Stack.java index 3699d860..d4b4ee6a 100755 --- a/contentstack/src/main/java/com/contentstack/sdk/Stack.java +++ b/contentstack/src/main/java/com/contentstack/sdk/Stack.java @@ -1,13 +1,10 @@ package com.contentstack.sdk; -import android.util.ArrayMap; +import android.os.Build; import android.text.TextUtils; +import android.util.ArrayMap; import android.util.Log; -import com.contentstack.sdk.utilities.CSAppConstants; -import com.contentstack.sdk.utilities.CSAppUtils; -import com.contentstack.sdk.utilities.CSController; - import org.jetbrains.annotations.NotNull; import org.json.JSONException; import org.json.JSONObject; @@ -23,6 +20,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Objects; import java.util.TimeZone; /** @@ -38,55 +36,38 @@ public class Stack implements INotifyClass { protected ArrayMap localHeader = null; private String imageTransformationUrl; private LinkedHashMap imageParams = new LinkedHashMap<>(); - protected String URLSCHEMA = "https://"; + protected String PROTOCOL = "https://"; protected String URL = "cdn.contentstack.io"; protected String VERSION = "v3"; - protected String SYNC_KEY = "sync"; protected Config config; - protected ArrayMap headerGroup_app; - private JSONObject syncParams = null; + protected ArrayMap headerGroupApp; + protected JSONObject syncParams = null; protected String skip = null; protected String limit = null; - protected String sync_token = null; - protected String pagination_token = null; - protected String contentType; protected String localeCode; - protected PublishType publishType; - protected String startFromDate; private SyncResultCallBack syncCallBack; - public enum PublishType { - entry_published, - entry_unpublished, - entry_deleted, - asset_published, - asset_unpublished, - asset_deleted, - content_type_deleted + protected Stack() { } - - private Stack() { - } - - - protected Stack(String stackApiKey) { - this.stackApiKey = stackApiKey; - this.localHeader = new ArrayMap(); - + protected Stack(@NotNull String apiKey) { + this.stackApiKey = apiKey; + if (this.localHeader == null) { + this.localHeader = new ArrayMap<>(); + } + this.localHeader.put("api_key", this.stackApiKey); } protected void setConfig(Config config) { this.config = config; - URLSCHEMA = config.URLSCHEMA; + PROTOCOL = config.PROTOCOL; URL = config.URL; VERSION = config.VERSION; if (!TextUtils.isEmpty(config.environment)) { setHeader("environment", config.environment); } - if (!config.region.name().isEmpty()) { String region = config.region.name().toLowerCase(); if (!region.equalsIgnoreCase("us")) { @@ -95,6 +76,8 @@ protected void setConfig(Config config) { } if (region.equalsIgnoreCase("azure_na")) { URL = "azure-na-cdn.contentstack.com"; + } else if (region.equalsIgnoreCase("azure_eu")) { + URL = "azure-eu-cdn.contentstack.com"; } else { URL = region + "-" + URL; } @@ -103,6 +86,7 @@ protected void setConfig(Config config) { } + /** * Represents a {@link ContentType}.
* Create {@link ContentType} instance. @@ -113,14 +97,12 @@ protected void setConfig(Config config) { *

Example :
*
      * Stack stack = Contentstack.stack(context, "apiKey", "deliveryToken", "stag");
-     *
      * ContentType contentType = stack.contentType("blog");
      * 
*/ public ContentType contentType(String contentTypeName) { ContentType contentType = new ContentType(contentTypeName); contentType.setStackInstance(this); - return contentType; } @@ -139,7 +121,6 @@ public ContentType contentType(String contentTypeName) { public Asset asset(String uid) { Asset asset = new Asset(uid); asset.setStackInstance(this); - return asset; } @@ -157,7 +138,6 @@ public Asset asset(String uid) { protected Asset asset() { Asset asset = new Asset(); asset.setStackInstance(this); - return asset; } @@ -204,7 +184,7 @@ public String getApplicationKey() { *

*/ public String getAccessToken() { - return localHeader != null ? (String) localHeader.get("access_token") : null; + return this.localHeader != null ? (String) this.localHeader.get("access_token") : null; } /** @@ -220,7 +200,7 @@ public String getAccessToken() { */ public void removeHeader(String key) { if (!TextUtils.isEmpty(key)) { - localHeader.remove(key); + this.localHeader.remove(key); } } @@ -235,12 +215,21 @@ public void removeHeader(String key) { *

Example :
*
-     *              stack.setHeader("custom_key", "custom_value");
+     *              stack.setHeader("key", "value");
      *              
*/ public void setHeader(String key, String value) { if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)) { - localHeader.put(key, value); + this.localHeader.put(key, value); + } + } + + public void setHeaders(@NotNull ArrayMap headers) { + if (this.localHeader == null) { + this.localHeader = new ArrayMap<>(); + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + headers.forEach((key, value) -> this.localHeader.put(key, value)); } } @@ -262,9 +251,6 @@ public void setHeader(String key, String value) { * imageParams.put("height",100); * imageUrl = Stack.ImageTransform(image_url, parameters); * stack.ImageTransform(image_url, parameters); - * - * - * * */ public String ImageTransform(String image_url, LinkedHashMap parameters) { @@ -275,17 +261,13 @@ public String ImageTransform(String image_url, LinkedHashMap par private String getImageUrl() { - if (imageParams == null || imageParams.size() == 0) { return imageTransformationUrl; } - for (Map.Entry param : imageParams.entrySet()) { try { - String paramKey = param.getKey(); String paramValue = param.getValue().toString(); - final String encodedKey = URLEncoder.encode(paramKey, "UTF-8"); final String encodedValue = URLEncoder.encode(paramValue, "UTF-8"); if (!imageTransformationUrl.contains("?")) { @@ -293,12 +275,10 @@ private String getImageUrl() { } else { imageTransformationUrl += "&" + encodedKey + "=" + encodedValue; } - } catch (UnsupportedEncodingException e) { - Log.e(TAG, e.getLocalizedMessage()); + Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage())); } } - return imageTransformationUrl; } @@ -307,36 +287,31 @@ private String getImageUrl() { * @param params query parameters * @param callback ContentTypesCallback * This call returns comprehensive information of all the content types available in a particular stack in your account. - * *

Example :
- *
+     *                 
+     *                                                                                                                                                                                                                                                                                                                                                                                 JSONObject params = new JSONObject();
+     *                                                                                                                                                                                                                                                                                                                                                                                 params.put("include_snippet_schema", true);
+     *                                                                                                                                                                                                                                                                                                                                                                                 params.put("limit", 3);
+     *                                                                                                                                                                                                                                                                                                                                                                                 stack.getContentTypes(params, new ContentTypesCallback() {
+     *                                                                                                                                                                                                                                                                                                                                                                                 @Override  public void onCompletion(ContentTypesModel contentTypesModel, Error error) {
+     *                                                                                                                                                                                                                                                                                                                                                                                 if (error == null){
+     *                                                                                                                                                                                                                                                                                                                                                                                 // do your stuff.
+     *                                                                                                                                                                                                                                                                                                                                                                                 }
+     *                                                                                                                                                                                                                                                                                                                                                                                 }
+     *                                                                                                                                                                                                                                                                                                                                                                                 });
+     *                                                                                                                                                                                                                                                                                                                                                                                 
*/ public void getContentTypes(JSONObject params, final ContentTypesCallback callback) { - try { String URL = "/" + this.VERSION + "/content_types"; - ArrayMap headers = getHeader(localHeader); + ArrayMap headers = getHeader(this.localHeader); if (params == null) { params = new JSONObject(); } Iterator keys = params.keys(); while (keys.hasNext()) { - // loop to get the dynamic key String key = (String) keys.next(); - // get the value of the dynamic key Object value = params.opt(key); - // do something here with the value... params.put(key, value); } @@ -344,24 +319,21 @@ public void getContentTypes(JSONObject params, final ContentTypesCallback callba params.put("environment", headers.get("environment")); params.put("include_count", true); } - fetchContentTypes(URL, params, headers, null, callback); } catch (Exception e) { Error error = new Error(); - error.setErrorMessage(CSAppConstants.ErrorMessage_JsonNotProper); + error.setErrorMessage(SDKConstant.PLEASE_PROVIDE_VALID_JSON); callback.onRequestFail(ResponseType.UNKNOWN, error); } } private void fetchContentTypes(String urlString, JSONObject urlQueries, ArrayMap headers, String cacheFilePath, ContentTypesCallback callback) { - if (callback != null) { - HashMap urlParams = getUrlParams(urlQueries); - new CSBackgroundTask(this, this, CSController.FETCHCONTENTTYPES, urlString, headers, urlParams, new JSONObject(), cacheFilePath, CSAppConstants.callController.CONTENTTYPES.toString(), false, CSAppConstants.RequestMethod.GET, callback); + new CSBackgroundTask(this, this, SDKController.GET_CONTENT_TYPES, urlString, headers, urlParams, new JSONObject(), cacheFilePath, SDKConstant.callController.CONTENT_TYPES.toString(), false, SDKConstant.RequestMethod.GET, callback); } } @@ -376,65 +348,53 @@ private void fetchContentTypes(String urlString, JSONObject urlQueries, ArrayMap * since this token is used to get subsequent delta updates later. * *

Example :
- *
+     *                     
      *
-     *                                                                                                                                                                                                                                                                                                                                                                                                                                     stack.sync(SyncResultCallBack syncCallBack){  }
-     *
-     *                                                                                                                                                                                                                                                                                                                                                                                                                                     
+ * Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment"); + * stack.syncPaginationToken(pagination_token, new SyncResultCallBack()) {} + *
*/ public void sync(SyncResultCallBack syncCallBack) { - - if (syncParams == null) { - syncParams = new JSONObject(); - } try { - syncParams.put("init", true); + this.syncParams = new JSONObject(); + this.syncParams.put("init", true); } catch (JSONException e) { - Log.e(TAG, e.getLocalizedMessage()); + Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage())); } - this.requestSync(syncCallBack); - } - /** - * @param pagination_token If the response is paginated, use the pagination token under this parameter. - * @param syncCallBack returns callback for sync result - *

- * If the result of the initial sync (or subsequent sync) contains more than 100 records, - * the response would be paginated. It provides pagination token in the response. However, - * you do not have to use the pagination token manually to get the next batch, - * the SDK does that automatically until the sync is complete. - * Pagination token can be used in case you want to fetch only selected batches. - * It is especially useful if the sync process is interrupted midway (due to network issues, etc.). - * In such cases, this token can be used to restart the sync process from where it was interrupted. - * - *

Example :
- *

-     *                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         stack.syncPaginationToken(pagination_token, new SyncResultCallBack()) {}
-     *                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
+ * @param paginationToken If the response is paginated, use the pagination token under this parameter. + * @param syncCallBack returns callback for sync result + *

+ * If the result of the initial sync (or subsequent sync) contains more than 100 records, + * the response would be paginated. It provides pagination token in the response. However, + * you do not have to use the pagination token manually to get the next batch, + * the SDK does that automatically until the sync is complete. + * Pagination token can be used in case you want to fetch only selected batches. + * It is especially useful if the sync process is interrupted midway (due to network issues, etc.). + * In such cases, this token can be used to restart the sync process from where it was interrupted. + * + * + * Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment"); + * stack.syncPaginationToken(pagination_token, new SyncResultCallBack()) {} + * + *

*/ - public void syncPaginationToken(String pagination_token, SyncResultCallBack syncCallBack) { - this.pagination_token = pagination_token; - if (syncParams == null) { - syncParams = new JSONObject(); - } - + public void syncPaginationToken(String paginationToken, SyncResultCallBack syncCallBack) { try { - syncParams.put("init", true); - syncParams.put("pagination_token", pagination_token); + this.syncParams = new JSONObject(); + this.syncParams.put("pagination_token", paginationToken); } catch (JSONException e) { - Log.e(TAG, e.getLocalizedMessage()); + Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage())); } - this.requestSync(syncCallBack); } - /** - * @param sync_token Use the sync token that you received in the previous/initial sync under this parameter. + * @param syncToken Use the sync token that you received in the previous/initial sync under this parameter. * @param syncCallBack returns callback for sync result *

* You can use the sync token (that you receive after initial sync) to get the updated content next time. @@ -442,29 +402,20 @@ public void syncPaginationToken(String pagination_token, SyncResultCallBack sync * and the details of the content that was deleted or updated. *

Example :
*

-     *                                                                                                                                                                                                                                                                                                                                                                                                                                      stack.syncToken(sync_token, new SyncResultCallBack() ){ }
-     *
-     *                                                                                                                                                                                                                                                                                                                                                                                                                                     
+ * */ - public void syncToken(String sync_token, SyncResultCallBack syncCallBack) { - - this.sync_token = sync_token; - if (syncParams == null) { - syncParams = new JSONObject(); - } + public void syncToken(String syncToken, SyncResultCallBack syncCallBack) { try { - syncParams.put("init", true); - syncParams.put("sync_token", sync_token); + this.syncParams = new JSONObject(); + this.syncParams.put("sync_token", syncToken); } catch (JSONException e) { - Log.e(TAG, e.getLocalizedMessage()); + Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage())); } - this.requestSync(syncCallBack); } - /** - * @param from_date Enter the start date for initial sync. + * @param fromDate Enter the start date for initial sync. * @param syncCallBack Returns callback for sync result. *

* You can also initialize sync with entries published after a specific date. To do this, use syncWithDate @@ -472,67 +423,49 @@ public void syncToken(String sync_token, SyncResultCallBack syncCallBack) { * *

Example :
*

-     *                                                                                                                                                                                                                                                                                                                                                                                                                                    stack.syncFromDate(start_date, new SyncResultCallBack()) { }
-     *                                                                                                                                                                                                                                                                                                                                                                                                                                      
+ * stack.syncFromDate(start_date, new SyncResultCallBack()) { } + * */ - public void syncFromDate(Date from_date, SyncResultCallBack syncCallBack) { - startFromDate = convertUTCToISO(from_date); - if (syncParams == null) { - syncParams = new JSONObject(); - } - + public void syncFromDate(Date fromDate, SyncResultCallBack syncCallBack) { + String startFromDate = convertUTCToISO(fromDate); try { - syncParams.put("init", true); - syncParams.put("start_from", startFromDate); + this.syncParams = new JSONObject(); + this.syncParams.put("init", true); + this.syncParams.put("start_from", startFromDate); } catch (JSONException e) { - Log.e(TAG, e.getLocalizedMessage()); + Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage())); } this.requestSync(syncCallBack); } - - private String convertUTCToISO(Date date) { - - TimeZone tz = TimeZone.getTimeZone("UTC"); - DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US); - dateFormat.setTimeZone(tz); - return dateFormat.format(date); - } - - /** - * @param content_type Provide uid of your content_type + * @param contentType Provide uid of your content_type * @param syncCallBack Returns callback for sync result. *

* You can also initialize sync with entries of only specific content_type. * To do this, use syncContentType and specify the content type uid as its value. * However, if you do this, the subsequent syncs will only include the entries of the specified content_type. - * - *

Example :
- *

-     *
-     *                                                                                                                                                                                                                                                                                                                                                                                                                                     // dummy content_type like "session"
-     *                                                                                                                                                                                                                                                                                                                                                                                                                                     stack.syncContentType(String content_type, new SyncResultCallBack()){  }
-     *
-     *                                                                                                                                                                                                                                                                                                                                                                                                                                      
+ *

*/ - public void syncContentType(String content_type, SyncResultCallBack syncCallBack) { - - this.contentType = content_type; - if (syncParams == null) { - syncParams = new JSONObject(); - } + public void syncContentType(String contentType, SyncResultCallBack syncCallBack) { try { - syncParams.put("init", true); - syncParams.put("content_type_uid", contentType); + this.syncParams = new JSONObject(); + this.syncParams.put("init", true); + this.syncParams.put("content_type_uid", contentType); } catch (JSONException e) { - Log.e(TAG, e.getLocalizedMessage()); + Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage())); } - this.requestSync(syncCallBack); } + private String convertUTCToISO(Date date) { + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US); + dateFormat.setTimeZone(tz); + return dateFormat.format(date); + } + /** * @param language Select the required locale from the Language class. * @param syncCallBack Returns callback for sync result. @@ -542,22 +475,17 @@ public void syncContentType(String content_type, SyncResultCallBack syncCallBack * */ public void syncLocale(Language language, SyncResultCallBack syncCallBack) { - this.localeCode = getLanguageCode(language); - - if (syncParams == null) { - syncParams = new JSONObject(); - } + String localeCode = getLanguageCode(language); try { - syncParams.put("init", true); - syncParams.put("locale", localeCode); + this.syncParams = new JSONObject(); + this.syncParams.put("init", true); + this.syncParams.put("locale", localeCode); } catch (JSONException e) { - Log.e(TAG, e.getLocalizedMessage()); + Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage())); } - this.requestSync(syncCallBack); } - /** * @param localeCode Provide locale code * @param syncCallBack Returns callback for sync result. @@ -567,33 +495,17 @@ public void syncLocale(Language language, SyncResultCallBack syncCallBack) { * */ public void syncLocale(@NotNull String localeCode, SyncResultCallBack syncCallBack) { - if (syncParams == null) { - syncParams = new JSONObject(); - } try { - syncParams.put("init", true); - syncParams.put("locale", localeCode); + this.syncParams = new JSONObject(); + this.syncParams.put("init", true); + this.syncParams.put("locale", localeCode); } catch (JSONException e) { - Log.e(TAG, e.getLocalizedMessage()); + Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage())); } this.requestSync(syncCallBack); } - - private String getLanguageCode(Language language) { - String localeCode = null; - if (language != null) { - Language languageName = Language.valueOf(language.name()); - int localeValue = languageName.ordinal(); - LanguageCode[] languageCodeValues = LanguageCode.values(); - localeCode = languageCodeValues[localeValue].name(); - localeCode = localeCode.replace("_", "-"); - } - return localeCode; - } - - /** * @param type - Use the type parameter to get a specific type of content * like ( asset_published, entry_published, asset_unpublished, asset_deleted, entry_unpublished, entry_deleted, content_type_deleted.) @@ -602,32 +514,39 @@ private String getLanguageCode(Language language) { * Use the type parameter to get a specific type of content. You can pass one of the following values: * asset_published, entry_published, asset_unpublished, asset_deleted, entry_unpublished, entry_deleted, content_type_deleted. * If you do not specify any value, it will bring all published entries and published assets. + *

+ * + * stackInstance.syncPublishType(Stack.PublishType.ENTRY_PUBLISHED, new SyncResultCallBack()) { } + * * - *

Example :
- *

-     *
-     *                                                                                                                                                                                                                                                                                                                                                                                                                                       stackInstance.syncPublishType(Stack.PublishType.entry_published, new SyncResultCallBack()) { }
-     *
-     *                                                                                                                                                                                                                                                                                                                                                                                                                                      
+ * */ public void syncPublishType(PublishType type, SyncResultCallBack syncCallBack) { - this.publishType = type; - if (syncParams == null) { - syncParams = new JSONObject(); - } - try { - syncParams.put("init", true); - syncParams.put("type", publishType); + this.syncParams = new JSONObject(); + this.syncParams.put("init", true); + this.syncParams.put("type", type.toString().toLowerCase()); } catch (JSONException e) { - Log.e(TAG, e.getLocalizedMessage()); + Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage())); } this.requestSync(syncCallBack); } + private String getLanguageCode(Language language) { + String localeCode = null; + if (language != null) { + Language languageName = Language.valueOf(language.name()); + int localeValue = languageName.ordinal(); + LanguageCode[] languageCodeValues = LanguageCode.values(); + localeCode = languageCodeValues[localeValue].name(); + localeCode = localeCode.replace("_", "-"); + } + return localeCode; + } + /** * @param contentType the content type * @param fromDate the from date @@ -640,59 +559,51 @@ public void syncPublishType(PublishType type, SyncResultCallBack syncCallBack) { */ public void sync(String contentType, Date fromDate, Language language, PublishType type, SyncResultCallBack syncCallBack) { - startFromDate = convertUTCToISO(fromDate); - this.contentType = contentType; - this.publishType = type; - this.localeCode = getLanguageCode(language); + String locale = getLanguageCode(language); + sync(contentType, fromDate, locale, type, syncCallBack); + } - if (syncParams == null) { - syncParams = new JSONObject(); - } + public void sync(String contentType, Date fromDate, String locale, PublishType type, SyncResultCallBack syncCallBack) { + String startFromDate = convertUTCToISO(fromDate); try { - syncParams.put("init", true); - syncParams.put("start_from", this.startFromDate); - syncParams.put("content_type_uid", this.contentType); - syncParams.put("type", publishType); - syncParams.put("locale", this.localeCode); + this.syncParams = new JSONObject(); + this.syncParams.put("init", true); + if (contentType != null && !contentType.isEmpty()) { + this.syncParams.put("content_type_uid", contentType); + } + if (!startFromDate.isEmpty()) { + this.syncParams.put("start_from", startFromDate); + } + if (locale != null && locale.isEmpty()) { + this.syncParams.put("locale", locale); + } + if (type != null && !type.toString().isEmpty()) { + this.syncParams.put("type", type.toString().toLowerCase()); + } } catch (JSONException e) { - Log.e(TAG, e.getLocalizedMessage()); + Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage())); } this.requestSync(syncCallBack); } - public void sync(String contentType, Date fromDate, String locale, PublishType type, SyncResultCallBack syncCallBack) { - startFromDate = convertUTCToISO(fromDate); - this.contentType = contentType; - this.publishType = type; - if (syncParams == null) { - syncParams = new JSONObject(); - } - try { - syncParams.put("init", true); - syncParams.put("start_from", this.startFromDate); - syncParams.put("content_type_uid", this.contentType); - syncParams.put("type", publishType); - syncParams.put("locale", locale); - } catch (JSONException e) { - Log.e(TAG, e.getLocalizedMessage()); - } - this.requestSync(syncCallBack); + /** + * The enum Publish type. + */ + public enum PublishType { + ENTRY_PUBLISHED, ENTRY_UNPUBLISHED, ENTRY_DELETED, ASSET_PUBLISHED, ASSET_UNPUBLISHED, ASSET_DELETED, CONTENT_TYPE_DELETED } private void requestSync(final SyncResultCallBack callback) { - try { - String URL = "/" + this.VERSION + "/stacks/" + SYNC_KEY; - ArrayMap headers = getHeader(localHeader); - - JSONObject urlQueries = new JSONObject(); - if (headers.containsKey("environment")) { - syncParams.put("environment", headers.get("environment")); + String URL = "/" + this.VERSION + "/stacks/sync"; + ArrayMap headers = getHeader(this.localHeader); + if (headers.containsKey(SDKConstant.ENVIRONMENT)) { + this.syncParams.put(SDKConstant.ENVIRONMENT, headers.get(SDKConstant.ENVIRONMENT)); } - urlQueries = syncParams; - fetchFromNetwork(URL, urlQueries, headers, null, new SyncResultCallBack() { + + fetchFromNetwork(URL, this.syncParams, headers, null, new SyncResultCallBack() { @Override public void onCompletion(SyncStack syncStack, Error error) { if (error == null) { @@ -704,21 +615,18 @@ public void onCompletion(SyncStack syncStack, Error error) { callback.onCompletion(syncStack, error); } }); - - } catch (Exception e) { Error error = new Error(); - error.setErrorMessage(CSAppConstants.ErrorMessage_JsonNotProper); + error.setErrorMessage(SDKConstant.PLEASE_PROVIDE_VALID_JSON); callback.onRequestFail(ResponseType.UNKNOWN, error); } - } private void fetchFromNetwork(String urlString, JSONObject urlQueries, ArrayMap headers, String cacheFilePath, SyncResultCallBack callback) { if (callback != null) { HashMap urlParams = getUrlParams(urlQueries); - new CSBackgroundTask(this, this, CSController.FETCHSYNC, urlString, headers, urlParams, new JSONObject(), cacheFilePath, CSAppConstants.callController.SYNC.toString(), false, CSAppConstants.RequestMethod.GET, callback); + new CSBackgroundTask(this, this, SDKController.GET_SYNC, urlString, headers, urlParams, new JSONObject(), cacheFilePath, SDKConstant.callController.SYNC.toString(), false, SDKConstant.RequestMethod.GET, callback); } } @@ -733,7 +641,7 @@ private HashMap getUrlParams(JSONObject urlQueriesJSON) { Object value = urlQueriesJSON.opt(key); hashMap.put(key, value); } catch (Exception e) { - CSAppUtils.showLog(TAG, e.getLocalizedMessage()); + SDKUtil.showLog(TAG, e.getLocalizedMessage()); } } return hashMap; @@ -743,7 +651,7 @@ private HashMap getUrlParams(JSONObject urlQueriesJSON) { private ArrayMap getHeader(ArrayMap localHeader) { - ArrayMap mainHeader = headerGroup_app; + ArrayMap mainHeader = headerGroupApp; ArrayMap classHeaders = new ArrayMap<>(); if (localHeader != null && localHeader.size() > 0) { if (mainHeader != null && mainHeader.size() > 0) { @@ -762,7 +670,7 @@ private ArrayMap getHeader(ArrayMap localHeader) return localHeader; } } else { - return headerGroup_app; + return headerGroupApp; } } diff --git a/contentstack/src/main/java/com/contentstack/sdk/SyncStack.java b/contentstack/src/main/java/com/contentstack/sdk/SyncStack.java index b115f900..96551bb4 100755 --- a/contentstack/src/main/java/com/contentstack/sdk/SyncStack.java +++ b/contentstack/src/main/java/com/contentstack/sdk/SyncStack.java @@ -1,13 +1,14 @@ package com.contentstack.sdk; -import com.contentstack.sdk.utilities.CSAppUtils; - import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; +/** + * The type Sync stack. + */ public class SyncStack { private static final String TAG = SyncStack.class.getSimpleName(); @@ -21,38 +22,83 @@ public class SyncStack { private ArrayList syncItems; + /** + * Gets url. + * + * @return the url + */ public String getURL() { return this.URL; } + /** + * Gets json response. + * + * @return the json response + */ public JSONObject getJSONResponse() { return this.receiveJson; } + /** + * Gets count. + * + * @return the count + */ public int getCount() { return this.count; } + /** + * Gets limit. + * + * @return the limit + */ public int getLimit() { return this.limit; } + /** + * Gets skip. + * + * @return the skip + */ public int getSkip() { return this.skip; } + /** + * Gets pagination token. + * + * @return the pagination token + */ public String getPaginationToken() { return this.pagination_token; } + /** + * Gets sync token. + * + * @return the sync token + */ public String getSyncToken() { return this.sync_token; } + /** + * Gets items. + * + * @return the items + */ public ArrayList getItems() { return this.syncItems; } + /** + * Sets json. + * + * @param jsonobject the jsonobject + */ protected void setJSON(JSONObject jsonobject) { if (jsonobject != null) { @@ -93,7 +139,7 @@ protected void setJSON(JSONObject jsonobject) { } } } catch (Exception e) { - CSAppUtils.showLog(TAG, e.getLocalizedMessage()); + SDKUtil.showLog(TAG, e.getLocalizedMessage()); } } diff --git a/contentstack/src/main/java/com/contentstack/sdk/TestActivity.java b/contentstack/src/main/java/com/contentstack/sdk/TestActivity.java index 7225266d..93f38c2a 100755 --- a/contentstack/src/main/java/com/contentstack/sdk/TestActivity.java +++ b/contentstack/src/main/java/com/contentstack/sdk/TestActivity.java @@ -1,15 +1,18 @@ package com.contentstack.sdk; -import android.app.Application; +import android.os.Bundle; + +import androidx.annotation.Nullable; +import androidx.appcompat.app.AppCompatActivity; /** * @author Contentstack.com, Inc */ -public class TestActivity extends Application { +public class TestActivity extends AppCompatActivity { @Override - public void onCreate() { - super.onCreate(); + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); } } diff --git a/contentstack/src/main/java/com/contentstack/sdk/package-info.java b/contentstack/src/main/java/com/contentstack/sdk/package-info.java new file mode 100755 index 00000000..dbbc6515 --- /dev/null +++ b/contentstack/src/main/java/com/contentstack/sdk/package-info.java @@ -0,0 +1,5 @@ +/** + * Okio complements {@link java.io} and {@link java.nio} to make it much easier to access, store, + * and process your data. + */ +package com.contentstack.sdk; diff --git a/contentstack/src/main/java/com/contentstack/sdk/utilities/CSAppConstants.java b/contentstack/src/main/java/com/contentstack/sdk/utilities/CSAppConstants.java deleted file mode 100755 index 5baaccd2..00000000 --- a/contentstack/src/main/java/com/contentstack/sdk/utilities/CSAppConstants.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.contentstack.sdk.utilities; - -import java.util.ArrayList; - -/** - * @author contentstack.com, Inc - */ -public class CSAppConstants { - - public static final boolean debug = false; - public static boolean isNetworkAvailable = true; - public static String URLSCHEMA_HTTPS = "https://"; - public static String SDK_VERSION = "3.11.0"; - public final static int NONETWORKCONNECTION = 408; - public final static int TimeOutDuration = 30000; // timeout in millisecond - public final static int NumRetry = 0; - public final static int BackOFMultiplier = 0; - - //Implemented for single network call cancellation. for class-level network call cancellation. - public static ArrayList cancelledCallController = new ArrayList(); - - /** - * Directory path to store offline data. - * used to saved cached network calls with response. - */ - public static String cacheFolderName; - - public static enum RequestMethod { - - GET, POST, PUT, DELETE - } - - public static enum callController { - - QUERY, - ENTRY, - STACK, - ASSET, - SYNC, - CONTENTTYPES, - ASSETLIBRARY; - } - - - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - public final static String ErrorMessage_JsonNotProper = "Please provide valid JSON."; - public final static String ErrorMessage_StackContextIsNull = "Context can not be null."; - public final static String ErrorMessage_StackApiKeyIsNull = "Stack api key can not be null."; - public final static String ErrorMessage_FormName = "Please set contentType name."; - public final static String ErrorMessage_EntryUID = "Please set entry uid."; - public final static String ErrorMessage_Stack_AccessToken_IsNull = "Access token can not be null."; - public final static String ErrorMessage_Stack_Environment_IsNull = "Environment can not be null."; - public final static String ErrorMessage_VolleyNoConnectionError = "Connection error"; - public final static String ErrorMessage_VolleyAuthFailureError = "Authentication Not present."; - public final static String ErrorMessage_VolleyParseError = "Parsing Error."; - public final static String ErrorMessage_VolleyServerError = "Server interaction went wrong, Please try again."; - public final static String ErrorMessage_Default = "Oops! Something went wrong. Please try again."; - public final static String ErrorMessage_NoNetwork = "Network not available."; - public final static String ErrorMessage_CalledDefaultMethod = "You must called Contentstack.stack() first"; - public final static String ErrorMessage_QueryFilterException = "Please provide valid params."; - public final static String ErrorMessage_EntryNotFoundInCache = "ENTRY is not present in cache"; - public final static String ErrorMessage_SavingNetworkCallResponseForCache = "Error while saving network call response."; -} diff --git a/contentstack/src/main/java/com/contentstack/sdk/utilities/CSController.java b/contentstack/src/main/java/com/contentstack/sdk/utilities/CSController.java deleted file mode 100755 index e0250ba6..00000000 --- a/contentstack/src/main/java/com/contentstack/sdk/utilities/CSController.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.contentstack.sdk.utilities; - -/** - * @author contentstack.com, Inc - */ -public class CSController { - - public static final String QUERYOBJECT = "getQueryEntries"; - - public static final String SINGLEQUERYOBJECT = "getSingleQueryEntries"; - - public static final String FETCHENTRY = "getEntry"; - - public static final String FETCHALLASSETS = "getAllAssets"; - - public static final String FETCHASSETS = "getAssets"; - - public static final String FETCHSYNC = "getSync"; - - public static final String FETCHCONTENTTYPES = "getContentTypes"; -} diff --git a/contentstack/src/main/res/mipmap-hdpi/ic_launcher.png b/contentstack/src/main/res/mipmap-hdpi/ic_launcher.png deleted file mode 100755 index cde69bcc..00000000 Binary files a/contentstack/src/main/res/mipmap-hdpi/ic_launcher.png and /dev/null differ diff --git a/contentstack/src/main/res/mipmap-mdpi/ic_launcher.png b/contentstack/src/main/res/mipmap-mdpi/ic_launcher.png deleted file mode 100755 index c133a0cb..00000000 Binary files a/contentstack/src/main/res/mipmap-mdpi/ic_launcher.png and /dev/null differ diff --git a/contentstack/src/main/res/mipmap-xhdpi/ic_launcher.png b/contentstack/src/main/res/mipmap-xhdpi/ic_launcher.png deleted file mode 100755 index bfa42f0e..00000000 Binary files a/contentstack/src/main/res/mipmap-xhdpi/ic_launcher.png and /dev/null differ diff --git a/contentstack/src/main/res/mipmap-xxhdpi/ic_launcher.png b/contentstack/src/main/res/mipmap-xxhdpi/ic_launcher.png deleted file mode 100755 index 324e72cd..00000000 Binary files a/contentstack/src/main/res/mipmap-xxhdpi/ic_launcher.png and /dev/null differ diff --git a/contentstack/src/test/java/com/contentstack/sdk/ExampleUnitTest.java b/contentstack/src/test/java/com/contentstack/sdk/ExampleUnitTest.java new file mode 100644 index 00000000..e7748124 --- /dev/null +++ b/contentstack/src/test/java/com/contentstack/sdk/ExampleUnitTest.java @@ -0,0 +1,13 @@ +package com.contentstack.sdk; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class ExampleUnitTest { + @Test + public void defaultTest() { + assertEquals(4, 2 + 2); + } + +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 1c3af5cd..e5bcd27d 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,7 @@ #Tue Dec 13 11:19:51 IST 2022 +#gradle-7.6-bin.zip distributionBase=GRADLE_USER_HOME -distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip distributionPath=wrapper/dists zipStorePath=wrapper/dists zipStoreBase=GRADLE_USER_HOME diff --git a/scripts/publish-module.gradle b/scripts/publish-module.gradle index 8d4ecc08..b407a099 100644 --- a/scripts/publish-module.gradle +++ b/scripts/publish-module.gradle @@ -2,70 +2,81 @@ apply plugin: 'maven-publish' apply plugin: 'signing' -task androidSourcesJar(type: Jar) { +ext { + PUBLISH_GROUP_ID = 'com.contentstack.sdk' + PUBLISH_ARTIFACT_ID = 'android' + PUBLISH_VERSION = '3.12.0-SNAPSHOT' + POM_NAME = 'contentstack-android' + WEBSITE = 'http://www.contentstack.com' + PUBLISH_DESCRIPTION = 'The Content Delivery SDK is used to retrieve content from your Contentstack account and deliver it to your web or mobile properties.' + PUBLISH_URL = 'https://github.com/contentstack/contentstack-android' + PUBLISH_LICENSE_NAME = 'MIT License' + PUBLISH_LICENSE_URL = 'https://github.com/contentstack/contentstack-android/blob/master/LICENSE' + PUBLISH_DEVELOPER_ID = 'ishaileshmishra' + PUBLISH_DEVELOPER_NAME = 'Shailesh Mishra' + PUBLISH_DEVELOPER_EMAIL = 'mobile@contentstack.com' + PUBLISH_SCM_CONNECTION = 'scm:git@github.com:contentstack/contentstack-android' + SCM_DEVELOPER_CONNECTION = 'scm:git@github.com:contentstack/contentstack-android.git' + PUBLISH_SCM_URL = 'https://github.com/contentstack/contentstack-android/tree/master' +} + +tasks.register('androidSourcesJar', Jar) { archiveClassifier.set('sources') if (project.plugins.findPlugin("com.android.library")) { - // For Android libraries from android.sourceSets.main.java.srcDirs - from android.sourceSets.main.kotlin.srcDirs } else { - // For pure Kotlin libraries, in case you have them from sourceSets.main.java.srcDirs - from sourceSets.main.kotlin.srcDirs } } - artifacts { archives androidSourcesJar } -group = "com.contentstack.sdk" -version = "3.11.0-SNAPSHOT" afterEvaluate { publishing { publications { release(MavenPublication) { - groupId = 'com.contentstack.sdk' - artifactId = 'android' - version = '3.11.0-SNAPSHOT' + groupId = PUBLISH_GROUP_ID + artifactId = PUBLISH_ARTIFACT_ID + version = PUBLISH_VERSION if (project.plugins.findPlugin("com.android.library")) { - from components.release + //from components.release } else { artifact("$buildDir/libs/${project.getName()}-${version}.jar") } artifact androidSourcesJar pom { - name = 'contentstack-android' - description = 'Android SDK for Contentstack Content Delivery API, Contentstack is a headless CMS with an API-first approach' - url = 'http://www.contentstack.com' + name = POM_NAME + description = PUBLISH_DESCRIPTION + url = WEBSITE licenses { license { - name = 'The MIT License' - url = 'http://www.opensource.org/licenses/mit-license.php' + name = PUBLISH_LICENSE_NAME + url = PUBLISH_LICENSE_URL } } developers { developer { - id = 'ishaileshmishra' - name = 'Shailesh Mishra' - email = 'mobile@contentstack.com' + id = PUBLISH_DEVELOPER_ID + name = PUBLISH_DEVELOPER_NAME + email = PUBLISH_DEVELOPER_EMAIL } } scm { - connection = 'scm:git@github.com:contentstack/contentstack-android' - developerConnection = 'scm:git@github.com:contentstack/contentstack-android.git' - url = 'https://github.com/contentstack/contentstack-android' + connection = PUBLISH_SCM_CONNECTION + developerConnection = SCM_DEVELOPER_CONNECTION + url = PUBLISH_SCM_URL } - } } } } } + ext["signing.keyId"] = rootProject.ext["signing.keyId"] ext["signing.password"] = rootProject.ext["signing.password"] ext["signing.secretKeyRingFile"] = rootProject.ext["signing.secretKeyRingFile"] diff --git a/scripts/publish-root.gradle b/scripts/publish-root.gradle index a04452f5..6ee1c85b 100644 --- a/scripts/publish-root.gradle +++ b/scripts/publish-root.gradle @@ -11,14 +11,6 @@ if (secretPropsFile.exists()) { Properties p = new Properties() new FileInputStream(secretPropsFile).withCloseable { is -> p.load(is) } p.each { name, value -> ext[name] = value } -} else { - // Use system environment variables - ext["ossrhUsername"] = System.getenv('OSSRH_USERNAME') - ext["ossrhPassword"] = System.getenv('OSSRH_PASSWORD') - ext["sonatypeStagingProfileId"] = System.getenv('SONATYPE_STAGING_PROFILE_ID') - ext["signing.keyId"] = System.getenv('SIGNING_KEY_ID') - ext["signing.password"] = System.getenv('SIGNING_PASSWORD') - ext["signing.secretKeyRingFile"] = System.getenv('SIGNING_SECRET_KEY_RING_FILE') } nexusPublishing { @@ -27,6 +19,8 @@ nexusPublishing { stagingProfileId = sonatypeStagingProfileId username = ossrhUsername password = ossrhPassword + nexusUrl.set(uri("https://oss.sonatype.org/service/local/")) + snapshotRepositoryUrl.set(uri("https://oss.sonatype.org/content/repositories/snapshots/")) if (project.version.endsWith('-SNAPSHOT')) { snapshotRepositoryUrl.set(uri("https://oss.sonatype.org/content/repositories/snapshots")) } else { diff --git a/talismanrc b/talismanrc new file mode 100644 index 00000000..afb4a066 --- /dev/null +++ b/talismanrc @@ -0,0 +1 @@ +threshold: medium \ No newline at end of file