diff --git a/contentstack/src/androidTest/java/com/contentstack/sdk/AssetTestCase.java b/contentstack/src/androidTest/java/com/contentstack/sdk/AssetTestCase.java index 7bccbb2d..8d5847a4 100644 --- a/contentstack/src/androidTest/java/com/contentstack/sdk/AssetTestCase.java +++ b/contentstack/src/androidTest/java/com/contentstack/sdk/AssetTestCase.java @@ -69,7 +69,7 @@ public void test_C_Asset_fetch() throws Exception { public void onCompletion(ResponseType responseType, Error error) { assertEquals(BuildConfig.assetUID, asset.getAssetUid()); assertEquals("image/jpeg", asset.getFileType()); - assertEquals("image1.jpg", asset.getFileName()); + assertEquals("phoenix2.jpg", asset.getFileName()); latch.countDown(); } }); @@ -84,7 +84,7 @@ public void test_E_AssetLibrary_includeCount_fetch() throws InterruptedException assetLibrary.fetchAll(new FetchAssetsCallback() { @Override public void onCompletion(ResponseType responseType, List assets, Error error) { - assertEquals(5, assetLibrary.getCount()); + assertEquals(6, assetLibrary.getCount()); latch.countDown(); } }); @@ -122,6 +122,22 @@ public void onCompletion(ResponseType responseType, Error error) { latch.await(5, TimeUnit.SECONDS); } + @Test + public void test_include_branch() { + final Asset asset = stack.asset(assetUid); + asset.includeBranch(); + asset.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(); diff --git a/contentstack/src/androidTest/java/com/contentstack/sdk/EntryFindTest.java b/contentstack/src/androidTest/java/com/contentstack/sdk/EntryFindTest.java index 0e9b0447..0f6f2ada 100644 --- a/contentstack/src/androidTest/java/com/contentstack/sdk/EntryFindTest.java +++ b/contentstack/src/androidTest/java/com/contentstack/sdk/EntryFindTest.java @@ -3,6 +3,7 @@ import static junit.framework.TestCase.assertEquals; import android.content.Context; +import android.util.Log; import androidx.test.core.app.ApplicationProvider; @@ -13,6 +14,7 @@ import org.junit.Test; import static org.junit.Assert.*; +import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -44,7 +46,7 @@ public void testFindEntry() throws InterruptedException { public void onCompletion(ResponseType responseType, QueryResult queryResult, Error error) { assertNull("There should be no error", error); assertNotNull("Entry should have been fetched", queryResult); - assertEquals("source5", queryResult.getResultObjects().get(0).getTitle()); + assertEquals("variant-base-product", queryResult.getResultObjects().get(0).getTitle()); // Unlock the latch to allow the test to proceed latch.countDown(); } @@ -124,9 +126,9 @@ public void onCompletion(ResponseType responseType, QueryResult queryResult, Err @Test public void testFindLessThan() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); - final Query query = stack.contentType("numbers_content_type").query(); - int value = 11; - query.lessThan("num_field", value); + final Query query = stack.contentType(CONTENT_TYPE_UID).query(); + int value = 90; + query.lessThan("price", value); query.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryResult, Error error) { @@ -134,8 +136,8 @@ public void onCompletion(ResponseType responseType, QueryResult queryResult, Err assertNotNull("Entry should have been fetched", queryResult); List entries = queryResult.getResultObjects(); for (int i = 0; i < entries.size(); i++) { - Integer currNum = (int)entries.get(i).get("num_field"); - assertTrue("Curr num_field should be less than the value", currNum < value); + Integer currNum = (int)entries.get(i).get("price"); + assertTrue("Curr price should be less than the value", currNum < value); } latch.countDown(); } @@ -147,9 +149,9 @@ public void onCompletion(ResponseType responseType, QueryResult queryResult, Err @Test public void testFindLessThanOrEqualTo() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); - final Query query = stack.contentType("numbers_content_type").query(); - int value = 11; - query.lessThanOrEqualTo("num_field", value); + final Query query = stack.contentType(CONTENT_TYPE_UID).query(); + int value = 90; + query.lessThanOrEqualTo("price", value); query.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryResult, Error error) { @@ -157,8 +159,8 @@ public void onCompletion(ResponseType responseType, QueryResult queryResult, Err assertNotNull("Entry should have been fetched", queryResult); List entries = queryResult.getResultObjects(); for (int i = 0; i < entries.size(); i++) { - Integer currNum = (int)entries.get(i).get("num_field"); - assertTrue("Curr num_field should be less than or equal to the value", currNum <= value); + Integer currNum = (int)entries.get(i).get("price"); + assertTrue("Curr price should be less than or equal to the value", currNum <= value); } latch.countDown(); } @@ -170,9 +172,9 @@ public void onCompletion(ResponseType responseType, QueryResult queryResult, Err @Test public void testFindGreaterThan() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); - final Query query = stack.contentType("numbers_content_type").query(); - int value = 11; - query.greaterThan("num_field", value); + final Query query = stack.contentType(CONTENT_TYPE_UID).query(); + int value = 90; + query.greaterThan("price", value); query.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryResult, Error error) { @@ -180,8 +182,8 @@ public void onCompletion(ResponseType responseType, QueryResult queryResult, Err assertNotNull("Entry should have been fetched", queryResult); List entries = queryResult.getResultObjects(); for (int i = 0; i < entries.size(); i++) { - Integer currNum = (int)entries.get(i).get("num_field"); - assertTrue("Curr num_field should be greater than the value", currNum > value); + Integer currNum = (int)entries.get(i).get("price"); + assertTrue("Curr price should be greater than the value", currNum > value); } latch.countDown(); } @@ -193,9 +195,9 @@ public void onCompletion(ResponseType responseType, QueryResult queryResult, Err @Test public void testFindGreaterThanOREqualTo() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); - final Query query = stack.contentType("numbers_content_type").query(); - int value = 11; - query.greaterThanOrEqualTo("num_field", value); + final Query query = stack.contentType(CONTENT_TYPE_UID).query(); + int value = 90; + query.greaterThanOrEqualTo("price", value); query.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryResult, Error error) { @@ -203,8 +205,8 @@ public void onCompletion(ResponseType responseType, QueryResult queryResult, Err assertNotNull("Entry should have been fetched", queryResult); List entries = queryResult.getResultObjects(); for (int i = 0; i < entries.size(); i++) { - Integer currNum = (int)entries.get(i).get("num_field"); - assertTrue("Curr num_field should be greater than or equal to the value", currNum >= value); + Integer currNum = (int)entries.get(i).get("price"); + assertTrue("Curr price should be greater than or equal to the value", currNum >= value); } latch.countDown(); } @@ -217,7 +219,7 @@ public void onCompletion(ResponseType responseType, QueryResult queryResult, Err public void testFindContainedIn() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final Query query = stack.contentType(CONTENT_TYPE_UID).query(); - String[] values = {"source1"}; + String[] values = {"kids dress"}; query.containedIn("title", values); query.find(new QueryResultsCallBack() { @Override @@ -240,7 +242,7 @@ public void onCompletion(ResponseType responseType, QueryResult queryResult, Err public void testFindNotContainedIn() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final Query query = stack.contentType(CONTENT_TYPE_UID).query(); - String[] values = {"source1"}; + String[] values = {"kids dress"}; query.notContainedIn("title", values); query.find(new QueryResultsCallBack() { @Override @@ -306,10 +308,10 @@ public void onCompletion(ResponseType responseType, QueryResult queryResult, Err @Test public void testFindOr() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); - String[] values = {"source1"}; - String field = "boolean"; + String[] values = {"kids dress"}; + String field = "in_stock"; final Query query1 = stack.contentType(CONTENT_TYPE_UID).query().containedIn("title", values); - final Query query2 = stack.contentType(CONTENT_TYPE_UID).query().where(field, true); + final Query query2 = stack.contentType(CONTENT_TYPE_UID).query().where(field, 300); final Query query = stack.contentType(CONTENT_TYPE_UID).query(); ArrayList queryList = new ArrayList<>(); queryList.add(query1); @@ -362,7 +364,7 @@ public void onCompletion(ResponseType responseType, QueryResult queryResult, Err @Test public void testFindIncludeReference() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); - String field = "reference"; + String field = "image"; final Query query = stack.contentType(CONTENT_TYPE_UID).query(); query.includeReference(field); query.find(new QueryResultsCallBack() { @@ -373,15 +375,8 @@ public void onCompletion(ResponseType responseType, QueryResult queryResult, Err List entries = queryResult.getResultObjects(); for (int i = 0; i < entries.size(); i++) { try { - JSONArray ref = (JSONArray)entries.get(i).get(field); - // Convert JSONArray to List - List list = new ArrayList<>(); - for (int j = 0; j < ref.length(); j++) { - JSONObject jsonObject = ref.getJSONObject(j); // Get the first JSONObject - // Title is a mandatory field, so we can test against it being present - assertTrue("One of or should be true", jsonObject.has("title")); - } - } catch (JSONException e) { + Log.d("Entry", entries.get(i).get(field).toString()); + } catch (Exception e) { throw new RuntimeException(e); } } diff --git a/contentstack/src/androidTest/java/com/contentstack/sdk/EntryTestCase.java b/contentstack/src/androidTest/java/com/contentstack/sdk/EntryTestCase.java new file mode 100644 index 00000000..8e909aa0 --- /dev/null +++ b/contentstack/src/androidTest/java/com/contentstack/sdk/EntryTestCase.java @@ -0,0 +1,347 @@ +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.InstrumentationRegistry; +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; + private static String variantUID = BuildConfig.variantUID; + private static String variantEntryUID = BuildConfig.variantEntryUID; + private static String[] variantsUID = BuildConfig.variantsUID; + + + @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 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(); + } + + @Test + public void VariantsTestSingleUid(){ + final Entry entry = stack.contentType("product").entry(variantEntryUID).variants(variantUID); + entry.fetch(new EntryResultCallBack() { + @Override + public void onCompletion(ResponseType responseType, Error error) { +// assertEquals(variantUID, entry.getHeaders().get("x-cs-variant-uid")); + System.out.println(entry.toJSON()); + } + }); + } + @Test + public void VariantsTestArray(){ + final Entry entry = stack.contentType("product").entry(variantEntryUID).variants(variantsUID); + entry.fetch(new EntryResultCallBack() { + @Override + public void onCompletion(ResponseType responseType, Error error) { + System.out.println(entry.toJSON()); + } + }); + } + +} \ No newline at end of file diff --git a/contentstack/src/androidTest/java/com/contentstack/sdk/GlobalFieldTestCase.java b/contentstack/src/androidTest/java/com/contentstack/sdk/GlobalFieldTestCase.java new file mode 100644 index 00000000..3bdae342 --- /dev/null +++ b/contentstack/src/androidTest/java/com/contentstack/sdk/GlobalFieldTestCase.java @@ -0,0 +1,89 @@ +package com.contentstack.sdk; + +import android.content.Context; +import android.util.Log; + +import androidx.test.core.app.ApplicationProvider; + +import org.json.JSONArray; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +public class GlobalFieldTestCase { + private final String TAG = GlobalFieldTestCase.class.getSimpleName(); +// private static String globalFieldUid = BuildConfig.GlobalFieldUID; + private static Stack stack; + private static CountDownLatch latch; + + + @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); + } + + @Before + public void setUp() { + latch = new CountDownLatch(1); + } + + @Test + public void test_fetchGlobalField() throws Exception { + GlobalField globalField = stack.globalField("specific_gf_uid"); + globalField.findAll(new GlobalFieldsResultCallback() { + @Override + public void onCompletion(GlobalFieldsModel globalFieldsModel, Error error) { + if (error == null) { + JSONArray result = globalFieldsModel.getResultArray(); + System.out.println("✅ Global Fields Response: " + result); + } else { + System.out.println("❌ Error: " + error.getErrorMessage()); + } + latch.countDown(); // Signal that response arrived + } + }); + } + + + @Test + public void test_fetchGlobalField_withInvalidUid() { + GlobalField globalField = new GlobalField(""); // empty UID + globalField.setStackInstance(stack); + + globalField.fetch(new GlobalFieldsResultCallback() { + + @Override + public void onCompletion(GlobalFieldsModel globalFieldsModel, Error error) { + if(error != null){ + System.out.println("❌ Error: " + error.getErrorMessage()); + } + } + }); + } + + @Test + public void test_findAllGlobalFields_success() throws InterruptedException { + GlobalField globalField = stack.globalField(); + globalField.findAll(new GlobalFieldsResultCallback() { + + @Override + public void onCompletion(GlobalFieldsModel globalFieldsModel, Error error) { + if(error == null){ + Assertions.assertNotNull(globalFieldsModel.getResultArray()); + } else { + System.out.println("❌ Error: " + error.getErrorMessage()); + } + } + }); + + } +} diff --git a/contentstack/src/androidTest/java/com/contentstack/sdk/QueryTestCase.java b/contentstack/src/androidTest/java/com/contentstack/sdk/QueryTestCase.java index 06256ec6..9e3e305c 100644 --- a/contentstack/src/androidTest/java/com/contentstack/sdk/QueryTestCase.java +++ b/contentstack/src/androidTest/java/com/contentstack/sdk/QueryTestCase.java @@ -77,7 +77,7 @@ public void onCompletion(ResponseType responseType, QueryResult queryresult, Err fallbackQuery.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - assertEquals(0, queryresult.getResultObjects().size()); + assertEquals(8, queryresult.getResultObjects().size()); } }); } diff --git a/contentstack/src/androidTest/java/com/contentstack/sdk/TaxonomyFindTest.java b/contentstack/src/androidTest/java/com/contentstack/sdk/TaxonomyFindTest.java index 0aefefb3..aa3aab6d 100644 --- a/contentstack/src/androidTest/java/com/contentstack/sdk/TaxonomyFindTest.java +++ b/contentstack/src/androidTest/java/com/contentstack/sdk/TaxonomyFindTest.java @@ -38,15 +38,15 @@ public void testTaxonomyIn() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); Taxonomy taxonomy = stack.taxonomy(); List taxonomyQueryList = new ArrayList<>(); - taxonomyQueryList.add("term_two"); - taxonomy.in("taxonomies.two", taxonomyQueryList).find(new TaxonomyCallback() { + taxonomyQueryList.add("maroon"); + taxonomy.in("taxonomies.color", taxonomyQueryList).find(new TaxonomyCallback() { @Override public void onResponse(JSONObject response, Error error) { assertNull("There should be no error", error); assertNotNull("Entry should have been fetched", response); try { JSONArray entries = (JSONArray)response.get("entries"); - assertEquals(2, entries.length()); + assertEquals(1, entries.length()); } catch (Exception e) { assertNull("Error should be null, fail the test", e); } @@ -66,9 +66,9 @@ public void testTaxonomyOr() throws InterruptedException, JSONException { Taxonomy taxonomy = stack.taxonomy(); List taxonomyQueryList = new ArrayList<>(); JSONObject item1 = new JSONObject(); - item1.put("taxonomies.one", "term_one"); + item1.put("taxonomies.color", "orange"); JSONObject item2 = new JSONObject(); - item2.put("taxonomies.two", "term_two"); + item2.put("taxonomies.country", "zambia"); taxonomyQueryList.add(item1); taxonomyQueryList.add(item2); taxonomy.or(taxonomyQueryList).find(new TaxonomyCallback() { @@ -98,9 +98,9 @@ public void testTaxonomyAnd() throws InterruptedException, JSONException { Taxonomy taxonomy = stack.taxonomy(); List taxonomyQueryList = new ArrayList<>(); JSONObject item1 = new JSONObject(); - item1.put("taxonomies.one", "term_one"); + item1.put("taxonomies.color", "green"); JSONObject item2 = new JSONObject(); - item2.put("taxonomies.two", "term_two"); + item2.put("taxonomies.country", "india"); taxonomyQueryList.add(item1); taxonomyQueryList.add(item2); taxonomy.and(taxonomyQueryList).find(new TaxonomyCallback() { @@ -110,7 +110,7 @@ public void onResponse(JSONObject response, Error error) { assertNotNull("Entry should have been fetched", response); try { JSONArray entries = (JSONArray)response.get("entries"); - assertEquals(2, entries.length()); + assertEquals(1, entries.length()); } catch (Exception e) { assertNull("Error should be null, fail the test", e); } @@ -128,7 +128,7 @@ public void testTaxonomyAbove() throws InterruptedException, JSONException { // Create a latch to wait for the async operation to complete final CountDownLatch latch = new CountDownLatch(1); Taxonomy taxonomy = stack.taxonomy(); - taxonomy.above("taxonomies.one", "term_one_child").find(new TaxonomyCallback() { + taxonomy.above("taxonomies.color", "maroon").find(new TaxonomyCallback() { @Override public void onResponse(JSONObject response, Error error) { assertNull("There should be no error", error); @@ -153,14 +153,14 @@ public void testTaxonomyEqualAndAbove() throws InterruptedException, JSONExcepti // Create a latch to wait for the async operation to complete final CountDownLatch latch = new CountDownLatch(1); Taxonomy taxonomy = stack.taxonomy(); - taxonomy.equalAndBelow("taxonomies.one", "term_one_child").find(new TaxonomyCallback() { + taxonomy.equalAndBelow("taxonomies.color", "maroon").find(new TaxonomyCallback() { @Override public void onResponse(JSONObject response, Error error) { assertNull("There should be no error", error); assertNotNull("Entry should have been fetched", response); try { JSONArray entries = (JSONArray)response.get("entries"); - assertEquals(2, entries.length()); + assertEquals(1, entries.length()); } catch (Exception e) { assertNull("Error should be null, fail the test", e); } @@ -178,7 +178,7 @@ public void testTaxonomyBelow() throws InterruptedException, JSONException { // Create a latch to wait for the async operation to complete final CountDownLatch latch = new CountDownLatch(1); Taxonomy taxonomy = stack.taxonomy(); - taxonomy.below("taxonomies.one", "term_one_child").find(new TaxonomyCallback() { + taxonomy.below("taxonomies.color", "red").find(new TaxonomyCallback() { @Override public void onResponse(JSONObject response, Error error) { assertNull("There should be no error", error); @@ -203,14 +203,14 @@ public void testTaxonomyEqualAndBelow() throws InterruptedException, JSONExcepti // Create a latch to wait for the async operation to complete final CountDownLatch latch = new CountDownLatch(1); Taxonomy taxonomy = stack.taxonomy(); - taxonomy.equalAndBelow("taxonomies.one", "term_one_child").find(new TaxonomyCallback() { + taxonomy.equalAndBelow("taxonomies.color", "red").find(new TaxonomyCallback() { @Override public void onResponse(JSONObject response, Error error) { assertNull("There should be no error", error); assertNotNull("Entry should have been fetched", response); try { JSONArray entries = (JSONArray)response.get("entries"); - assertEquals(2, entries.length()); + assertEquals(4, entries.length()); } catch (Exception e) { assertNull("Error should be null, fail the test", e); } diff --git a/contentstack/src/main/java/com/contentstack/sdk/Asset.java b/contentstack/src/main/java/com/contentstack/sdk/Asset.java index bbac9b8b..c135e2a6 100755 --- a/contentstack/src/main/java/com/contentstack/sdk/Asset.java +++ b/contentstack/src/main/java/com/contentstack/sdk/Asset.java @@ -607,4 +607,13 @@ public Asset includeFallback() { return this; } + public Asset includeBranch() { + try { + urlQueries.put("include_branch", true); + } catch (JSONException e) { + Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage())); + } + return this; + } + } diff --git a/contentstack/src/main/java/com/contentstack/sdk/CSBackgroundTask.java b/contentstack/src/main/java/com/contentstack/sdk/CSBackgroundTask.java index ac0b1461..a060b49f 100755 --- a/contentstack/src/main/java/com/contentstack/sdk/CSBackgroundTask.java +++ b/contentstack/src/main/java/com/contentstack/sdk/CSBackgroundTask.java @@ -127,6 +127,26 @@ public CSBackgroundTask(ContentType contentType, Stack stackInstance, String con } } + public CSBackgroundTask(GlobalField globalField, Stack stackInstance, String controller, String url, ArrayMap headers, HashMap urlParams, JSONObject jsonMain, String cacheFilePath, String requestInfo, boolean b, SDKConstant.RequestMethod method, ResultCallBack callback) { + + if (SDKConstant.IS_NETWORK_AVAILABLE) { + if (headers != null && headers.size() > 0) { + + String URL = stackInstance.PROTOCOL + stackInstance.URL + url; + + CSConnectionRequest csConnectionRequest = new CSConnectionRequest(globalField); + csConnectionRequest.setGlobalFieldInstance(globalField); + csConnectionRequest.setURLQueries(urlParams); + csConnectionRequest.setParams(URL, method, controller, jsonMain, headers, cacheFilePath, requestInfo, callback); + + } else { + sendErrorForHeader(callback); + } + } else { + sendErrorToUser(callback); + } + } + private void sendErrorToUser(ResultCallBack callbackObject) { Error error = new Error(); diff --git a/contentstack/src/main/java/com/contentstack/sdk/CSConnectionRequest.java b/contentstack/src/main/java/com/contentstack/sdk/CSConnectionRequest.java index 6d5e532d..36b8ad9c 100755 --- a/contentstack/src/main/java/com/contentstack/sdk/CSConnectionRequest.java +++ b/contentstack/src/main/java/com/contentstack/sdk/CSConnectionRequest.java @@ -40,6 +40,8 @@ class CSConnectionRequest implements IRequestModelHTTP { private Query queryInstance; private Asset assetInstance; private ContentType contentTypeInstance; + + private GlobalField globalFieldInstance; private JSONObject errorJObject; private Error errorObject = new Error(); @@ -66,6 +68,10 @@ public CSConnectionRequest(ContentType contentType) { this.contentTypeInstance = contentType; } + public CSConnectionRequest(GlobalField globalField) { + this.globalFieldInstance = globalField; + } + public void setQueryInstance(Query queryInstance) { this.queryInstance = queryInstance; } @@ -82,6 +88,10 @@ public void setContentTypeInstance(ContentType contentTypeInstance) { this.contentTypeInstance = contentTypeInstance; } + public void setGlobalFieldInstance(GlobalField globalFieldInstance) { + this.globalFieldInstance = globalFieldInstance; + } + public void setParams(Object... objects) { SDKUtil.showLog(TAG, "ParallelTasks------|" + objects[0] + " started"); @@ -249,6 +259,12 @@ public void onRequestFinished(CSHttpConnection request) { if (request.getCallBackObject() != null) { ((ContentTypesCallback) request.getCallBackObject()).onRequestFinish(model); } + } else if (controller.equalsIgnoreCase(SDKController.GET_GLOBAL_FIELDS)) { + GlobalFieldsModel model = new GlobalFieldsModel(); + model.setJSON(responseJSON); + if (request.getCallBackObject() != null) { + ((GlobalFieldsResultCallback) request.getCallBackObject()).onRequestFinish(model); + } } } diff --git a/contentstack/src/main/java/com/contentstack/sdk/GlobalField.java b/contentstack/src/main/java/com/contentstack/sdk/GlobalField.java new file mode 100644 index 00000000..3c35baca --- /dev/null +++ b/contentstack/src/main/java/com/contentstack/sdk/GlobalField.java @@ -0,0 +1,190 @@ +package com.contentstack.sdk; + +import android.text.TextUtils; +import android.util.ArrayMap; +import android.util.Log; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Objects; + +public class GlobalField { + protected String TAG = GlobalField.class.getSimpleName(); + protected String global_field_uid = null; + protected Stack stackInstance = null; + private ArrayMap localHeader = null; + private ArrayMap stackHeader = null; + + JSONObject urlQueries = new JSONObject(); + + protected GlobalField() { + this.localHeader = new ArrayMap<>(); + } + + protected GlobalField (String global_field_uid) { + this.global_field_uid = global_field_uid; + this.localHeader = new ArrayMap<>(); + } + + protected void setStackInstance(Stack stack) { + this.stackInstance = stack; + this.stackHeader = stack.localHeader; + } + + /** + * To set headers for Contentstack rest calls. + *
+ * Scope is limited to this object and followed classes. + * + * @param key header name. + * @param value header value against given header name. + * + **/ + + public void setHeader(String key, String value) { + if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)) { + localHeader.put(key, value); + } + } + + /** + * Remove header key. + * + * @param key custom_header_key + * + *
+ *
+ * Example :
+ * + *
+     **/
+    public void removeHeader(String key) {
+        if (!TextUtils.isEmpty(key)) {
+            localHeader.remove(key);
+        }
+    }
+
+    /**
+     *
+     *
+     * @throws IllegalAccessException
+     *                                illegal access exception
+     */
+
+    public GlobalField includeBranch() {
+        try {
+            urlQueries.put("include_branch", true);
+        } catch (JSONException e) {
+            Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage()));
+        }
+        return this;
+    }
+
+    public GlobalField includeGlobalFieldSchema() {
+        try {
+            urlQueries.put("include_global_field_schema", true);
+        } catch (JSONException e) {
+            Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage()));
+        }
+        return this;
+    }
+
+    public void fetch( GlobalFieldsResultCallback callback) {
+        try {
+            String URL = "/" + stackInstance.VERSION + "/global_fields/" + global_field_uid;
+            ArrayMap headers = getHeader(localHeader);
+
+            if (global_field_uid != null && !global_field_uid.isEmpty()) {
+                fetchGlobalFields(URL, urlQueries, headers, null, callback);
+            } else {
+                Error error = new Error();
+                error.setErrorMessage(SDKConstant.PLEASE_PROVIDE_VALID_JSON);
+                callback.onRequestFail(ResponseType.UNKNOWN, error);
+            }
+        } catch (Exception e) {
+            Error error = new Error();
+            error.setErrorMessage(SDKConstant.PLEASE_PROVIDE_GLOBAL_FIELD_UID);
+            callback.onRequestFail(ResponseType.UNKNOWN, error);
+        }
+
+    }
+
+    public void findAll(final GlobalFieldsResultCallback callback) {
+        try {
+            String URL = "/" + stackInstance.VERSION + "/global_fields";
+            ArrayMap headers = getHeader(localHeader);
+            fetchGlobalFields(URL, urlQueries, headers, null, callback);
+        } catch (Exception e) {
+            Error error = new Error();
+            error.setErrorMessage(SDKConstant.ERROR_MESSAGE_DEFAULT);
+            callback.onRequestFail(ResponseType.UNKNOWN, error);
+        }
+    }
+
+    private void fetchGlobalFields(String urlString, JSONObject urlQueries, ArrayMap headers,
+            String cacheFilePath, GlobalFieldsResultCallback callback) {
+
+        if (callback != null) {
+
+            HashMap urlParams = getUrlParams(urlQueries);
+            new CSBackgroundTask(this, stackInstance, SDKController.GET_GLOBAL_FIELDS, urlString, headers, urlParams,
+                    new JSONObject(), cacheFilePath, SDKConstant.callController.GLOBAL_FIELDS.toString(), false,
+                    SDKConstant.RequestMethod.GET, callback);
+        }
+    }
+
+    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();
+                try {
+                    Object value = urlQueriesJSON.opt(key);
+                    hashMap.put(key, value);
+                } catch (Exception e) {
+                    SDKUtil.showLog(TAG, "------setQueryJson" + e.toString());
+                }
+            }
+
+            return hashMap;
+        }
+
+        return null;
+    }
+
+    private ArrayMap getHeader(ArrayMap localHeader) {
+        ArrayMap mainHeader = stackHeader;
+        ArrayMap classHeaders = new ArrayMap<>();
+
+        if (localHeader != null && localHeader.size() > 0) {
+            if (mainHeader != null && mainHeader.size() > 0) {
+                for (Map.Entry entry : localHeader.entrySet()) {
+                    String key = entry.getKey();
+                    classHeaders.put(key, entry.getValue());
+                }
+
+                for (Map.Entry entry : mainHeader.entrySet()) {
+                    String key = entry.getKey();
+                    if (!classHeaders.containsKey(key)) {
+                        classHeaders.put(key, entry.getValue());
+                    }
+                }
+
+                return classHeaders;
+
+            } else {
+                return localHeader;
+            }
+
+        } else {
+            return stackHeader;
+        }
+    }
+}
diff --git a/contentstack/src/main/java/com/contentstack/sdk/GlobalFieldsModel.java b/contentstack/src/main/java/com/contentstack/sdk/GlobalFieldsModel.java
new file mode 100644
index 00000000..ff0194b3
--- /dev/null
+++ b/contentstack/src/main/java/com/contentstack/sdk/GlobalFieldsModel.java
@@ -0,0 +1,47 @@
+package com.contentstack.sdk;
+
+import android.util.Log;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.util.Objects;
+
+public class GlobalFieldsModel {
+
+    private JSONObject responseJSON = new JSONObject();
+    private JSONArray responseJSONArray = new JSONArray();
+    private final String TAG = GlobalFieldsModel.class.getSimpleName();
+
+    public void setJSON(JSONObject responseJSON) {
+
+        if (responseJSON != null) {
+
+            if (responseJSON.has("global_field")) {
+                try {
+                    this.responseJSON = responseJSON.getJSONObject("global_field");
+                } catch (JSONException e) {
+                    Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage()));
+                }
+            }
+
+            if (responseJSON.has("global_fields")) {
+                try {
+                    this.responseJSONArray = responseJSON.getJSONArray("global_fields");
+                } catch (JSONException e) {
+                    Log.e(TAG, Objects.requireNonNull(e.getLocalizedMessage()));
+                }
+            }
+
+        }
+    }
+
+    public JSONObject getResponse() {
+        return responseJSON;
+    }
+
+    public JSONArray getResultArray() {
+        return responseJSONArray;
+    }
+}
diff --git a/contentstack/src/main/java/com/contentstack/sdk/GlobalFieldsResultCallback.java b/contentstack/src/main/java/com/contentstack/sdk/GlobalFieldsResultCallback.java
new file mode 100644
index 00000000..87678ae8
--- /dev/null
+++ b/contentstack/src/main/java/com/contentstack/sdk/GlobalFieldsResultCallback.java
@@ -0,0 +1,21 @@
+package com.contentstack.sdk;
+
+public abstract class GlobalFieldsResultCallback extends ResultCallBack{
+    /**
+     * Triggered after call execution complete.
+     *
+     * @param globalFieldsModel {@link GlobalFieldsModel} instance if call success else null.
+     * @param error        {@link Error} instance if call failed else null.
+     */
+    public abstract void onCompletion(GlobalFieldsModel globalFieldsModel, Error error);
+    void onRequestFinish(GlobalFieldsModel globalFieldsModel) {
+        onCompletion(globalFieldsModel, null);
+    }
+    @Override
+    void onRequestFail(ResponseType responseType, Error error) {
+        onCompletion(null, error);
+    }
+    @Override
+    void always() {
+    }
+}
diff --git a/contentstack/src/main/java/com/contentstack/sdk/SDKConstant.java b/contentstack/src/main/java/com/contentstack/sdk/SDKConstant.java
index 1dbf54d2..2e94fbfb 100755
--- a/contentstack/src/main/java/com/contentstack/sdk/SDKConstant.java
+++ b/contentstack/src/main/java/com/contentstack/sdk/SDKConstant.java
@@ -31,6 +31,7 @@ public static enum callController {
         ASSET,
         SYNC,
         CONTENT_TYPES,
+        GLOBAL_FIELDS,
         ASSET_LIBRARY;
     }
 
@@ -49,4 +50,7 @@ public static enum callController {
     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.";
+    public final static String PLEASE_PROVIDE_GLOBAL_FIELD_UID = "Please provide global field uid.";
+
+
 }
diff --git a/contentstack/src/main/java/com/contentstack/sdk/SDKController.java b/contentstack/src/main/java/com/contentstack/sdk/SDKController.java
index c695e83e..cb196fdd 100755
--- a/contentstack/src/main/java/com/contentstack/sdk/SDKController.java
+++ b/contentstack/src/main/java/com/contentstack/sdk/SDKController.java
@@ -41,4 +41,6 @@ public class SDKController {
      * The constant GET_CONTENT_TYPES.
      */
     public static final String GET_CONTENT_TYPES = "getContentTypes";
+
+    public static final String GET_GLOBAL_FIELDS = "getGlobalFields";
 }
diff --git a/contentstack/src/main/java/com/contentstack/sdk/Stack.java b/contentstack/src/main/java/com/contentstack/sdk/Stack.java
index c695da21..1bfcd7e3 100755
--- a/contentstack/src/main/java/com/contentstack/sdk/Stack.java
+++ b/contentstack/src/main/java/com/contentstack/sdk/Stack.java
@@ -138,6 +138,44 @@ public ContentType contentType(String contentTypeName) {
     }
 
 
+
+    /**
+     * Represents a Global field instance.
+     *
+     * 

Example :
+ *
+     * Stack stack = Contentstack.stack(context, "apiKey", "deliveryToken", "stag");
+     * GlobalField globalField = stack.globalField();
+     * 
+ * @return Global field instance + */ + + public GlobalField globalField(){ + GlobalField globalField = new GlobalField(); + globalField.setStackInstance(this); + return globalField; + } + + + + /** + * Represents Global Field with a specific global_field_uid + *

Example :
+ *
+     * Stack stack = Contentstack.stack(context, "apiKey", "deliveryToken", "stag");
+     * GlobalField globalField = stack.globalField("global_field_uid");
+     * 
+ * @param global_field_uid + * @return + */ + public GlobalField globalField(String global_field_uid){ + GlobalField globalField = new GlobalField(global_field_uid); + globalField.setStackInstance(this); + return globalField; + } + + + /** * Create {@link Asset} instance. *