diff --git a/.gitignore b/.gitignore index 6b259ff6..230c79c9 100644 --- a/.gitignore +++ b/.gitignore @@ -3,11 +3,12 @@ # src/test/java/com/contentstack/test/SyncTestCase.java # Language Support for Java(TM) by Red Hat extension for Visual Studio Code - https://marketplace.visualstudio.com/items?itemName=redhat.java +src/main/java/com/contentstack/sdk/models .idea .project .classpath factoryConfiguration.json - +.vscode ### Eclipse ### .metadata .env @@ -15,6 +16,7 @@ factoryConfiguration.json bin/ tmp/ *.tmp +.vscode *.bak *.swp *~.nib @@ -89,7 +91,7 @@ local.properties # Generated files .idea/**/contentModel.xml - +cover # Sensitive or high-churn files .idea/**/dataSources/ .idea/**/dataSources.ids @@ -264,3 +266,6 @@ gradle-app.setting java.iml src/main/resources/ /.idea/ +/src/main/java/com/contentstack/sdk/models/ +/.vscode/ +/.vscode/ diff --git a/.talismanrc b/.talismanrc index afb4a066..7cd3cd8c 100644 --- a/.talismanrc +++ b/.talismanrc @@ -1 +1 @@ -threshold: medium \ No newline at end of file +threshold: medium diff --git a/AUTHORS.md b/AUTHORS.md index 946a75da..bbf4010f 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -1,3 +1,4 @@ # Authors -- [Contentstack](https://www.contentstack.com/) -- [Shailesh-Mishra](shailesh.mishra@contentstack.com) +- [ishaileshmishra](shailesh.mishra@contentstack.com) +- [shaileshmishra](mshaileshr@contentstack.com) +- [admin](dev@contentstack.com) diff --git a/CHANGELOG.md b/CHANGELOG.md index b913578a..9976f1d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,20 @@ # CHANGELOG +## Version 2.0.0 + +### Date: 01-Nov-2021 + +- Added support for live preview +- Added support for branching +- Removed old version of jsoup dependency +- Code improved as per sonar vulnerability guidelines +- Removed deprecated code/Non-working code marked deprecated +- Few breaking changes added. + ## Version 1.7.0 -###### Date: 12-JUL-2021 + +### Date: 12-JUL-2021 + - Added support for utils function gql.jsonToHtml() - Bug #32 issue resolved removed e.printStackTrace() - Instead stacktrace used logger.error() @@ -9,21 +22,27 @@ ------------------------------------------------ ## Version 1.6.0 -###### Date: 05-APR-2021 + +### Date: 05-APR-2021 + - **Query** : query.includeEmbeddedItems() method support added - **Entry** : entry.includeEmbeddedItems() method support added ------------------------------------------------ ## Version 1.5.7 -###### Date: 20-Feb-2021 + +### Date: 20-Feb-2021 + Document updated ------------------------------------------------ ## Version 1.5.6 -###### Date: 27-Jan-2021 -Document updated + +### Date: 27-Jan-2021 + +Document updated New Features: • None @@ -31,13 +50,17 @@ New Features: ------------------------------------------------ ## Version 1.5.5 -###### Date: 22-Jan-2021 -Bug fix: Error contains information like + +### Date: 22-Jan-2021 + +Bug fix: Error contains information like + - Error message - Error code - Error Details Language Enum: + - GERMEN changed to GERMAN - Deprecated Language Enum - Deprecated LanguageCode Enum @@ -48,7 +71,9 @@ New Features: ------------------------------------------------ ## Version 1.5.4 -###### Date: 08-DEC-2020 + +### Date: 08-DEC-2020 + Publish content fallback New Features: • [Entry] - Publish fallback method added @@ -59,132 +84,160 @@ New Features: ------------------------------------------------ ## Version 1.5.3 - ###### Date: 28-July-2020 - - **Build Issue** Build update issue fixed + +### Date: 28-July-2020 + +- **Build Issue** Build update issue fixed ------------------------------------------------ ## Version 1.5.2 - ###### Date: 23-July-2020 - - **Bump Issue** : Bump Issue: log4j-core from 2.5 to 2.13.2 - - **Query** : Query.locale() documentation - - **CSHttpConnection** : StandardCharsets.UTF_8 Support Added +### Date: 23-July-2020 + +- **Bump Issue** : Bump Issue: log4j-core from 2.5 to 2.13.2 +- **Query** : Query.locale() documentation +- **CSHttpConnection** : StandardCharsets.UTF_8 Support Added ------------------------------------------------ ## Version 1.5.1 - ###### Date: 13-Jan-2020 - - **Dependency Vulnerability** Java Github reported vulnerable issue on dependency logj - + +### Date: 13-Jan-2020 + +- **Dependency Vulnerability** Java Github reported vulnerable issue on dependency logj + ------------------------------------------------ ## Version 1.5.0 - ###### Date: 15-Nov-2019 - - **Stack**: Added support for function getContentType() - - **ContentType**: updated function fetch() - - **Query**: Updated support of whereIn(String KEY, Query queryObject) - - **Query**: Updated support of whereNotIn(String KEY, Query queryObject) + +### Date: 15-Nov-2019 + +- **Stack**: Added support for function getContentType() +- **ContentType**: updated function fetch() +- **Query**: Updated support of whereIn(String KEY, Query queryObject) +- **Query**: Updated support of whereNotIn(String KEY, Query queryObject) ------------------------------------------------ ## Version 1.4.2 - ###### Date: 03-Sept-2019 - - **Config** - Added support for Region in Config. + +### Date: 03-Sept-2019 + +- **Config** - Added support for Region in Config. ------------------------------------------------ ## Version 1.4.1 - ###### Date: 21-August-2019 - - **Query** - Added support for whereIn(String key) and whereNotIn(String key) methods - - **CSAppConstants** - Removed google internet connection check from CSAppConstants - ------------------------------------------------- +### Date: 21-August-2019 + +- **Query** - Added support for whereIn(String key) and whereNotIn(String key) methods +- **CSAppConstants** - Removed google internet connection check from CSAppConstants -## Version 1.4.0 - ###### Date: 26-July-2019 - - **Entry** - Added support for includeReferenceContentTypeUid support in Entry. - - **Query** - Added support for includeReferenceContentTypeUid support in Query. - - **Entry** - setLanguage and getLanguage Deprecated in Entry. - - **Query** - language deprecated in Query - - **Entry** - Added method for getLocale and setLocale(String locale) in Entry - - **Query** - Added method for locale in Query. - - **Query** - Removed deprecated method for includeSchema in Query - ------------------------------------------------ +## Version 1.4.0 + +### Date: 26-July-2019 + +- **Entry** - Added support for includeReferenceContentTypeUid support in Entry. +- **Query** - Added support for includeReferenceContentTypeUid support in Query. +- **Entry** - setLanguage and getLanguage Deprecated in Entry. +- **Query** - language deprecated in Query +- **Entry** - Added method for getLocale and setLocale(String locale) in Entry +- **Query** - Added method for locale in Query. +- **Query** - Removed deprecated method for includeSchema in Query + +------------------------------------------------ ## Version 1.3.3 - ###### Date: 21-June-2019 - - **HOTFIX**: Override response hot-fix + +### Date: 21-June-2019 + +- **HOTFIX**: Override response hot-fix ------------------------------------------------ ## Version 1.3.2 - ### Date: 13-May-2019 - - **Code Improvement** Removed println - - **Code Improvement** Added support for Logger + +### Date: 13-May-2019 + +- **Code Improvement** Removed println +- **Code Improvement** Added support for Logger ------------------------------------------------ ## Version 1.3.1 - ###### Date: May-02-2019 - - **Change**: include reference bug fixed - - **Added testcase** report for v1.3.1 +### Date: May-02-2019 ------------------------------------------------- +- **Change**: include reference bug fixed +- **Added testcase** report for v1.3.1 +------------------------------------------------ ## Version 1.3.0 - ###### Date: Apr-12-2019 - Change: Added support of below methods in SDK + +### Date: Apr-12-2019 + + Change: Added support of below methods in SDK -``` - getContentTypes() in Stack class - fetch in ContentType class -``` + ``` + getContentTypes() in Stack class + fetch in ContentType class + ``` -Below two support from the Config class has been removed permanently +Below two support from the Config class has been removed permanently + - public void setSSL(boolean isSSL)setSSL() - public boolean isSSL() ------------------------------------------------ -## Version 1.2.1 -###### Date: 14-Mar-2019 -- Note: Bug Fixes and code clean up: - --------------------------------- +## Version 1.2.1 + +### Date: 14-Mar-2019 + +- Note: Bug Fixes and code clean up: -Date: 20-Feb-2019 +Date: 20-Feb-2019 Maven integration Folder structure modified. ------------------------------------------------ -## Version 1.2.0 -###### Date: 15-Dec-2017 + +## Version 1.2.0 + +### Date: 15-Dec-2017 + - New Features: -``` -Entry- added method ‘addParam’ -Query- added method 'addParam' -Asset- added method 'addParam' - ``` + + ``` + Entry- added method ‘addParam’ + Query- added method 'addParam' + Asset- added method 'addParam' + ``` + ------------------------------------------------ -## Version 1.1.0 -###### Date: 10-Nov-2017 +## Version 1.1.0 + +### Date: 10-Nov-2017 + - New Features: -``` -Stack- added method 'ImageTransform' -Query- added method 'includeContentType' -QueryResult- added method 'contentType' -``` + ``` + Stack- added method 'ImageTransform' + Query- added method 'includeContentType' + QueryResult- added method 'contentType' + ``` + ------------------------------------------------ -#### API deprecation: +### API deprecation + - Query - Deprecated method 'includeSchema' ------------------------------------------------- \ No newline at end of file + +------------------------------------------------ diff --git a/README.md b/README.md index 0a0f92b9..05c88c4d 100644 --- a/README.md +++ b/README.md @@ -15,20 +15,28 @@ You will need JDK installed on your machine. You can install it from [here](http To use the Contentstack Java SDK to your existing project, perform the steps given below: +Group id: `com.contentstack.sdk` + +Artifact id: `java` + +[{ version }](https://search.maven.org/artifact/com.contentstack.sdk/java) + 1. **Maven** ```java com.contentstack.sdk java - 1.7.0 + {version} ``` 2. **Gradle** ```java -implementation 'com.contentstack.sdk:java:1.7.0' +implementation 'com.contentstack.sdk:java:{version}' ``` +_Get updated version from_ [_version_](https://search.maven.org/artifact/com.contentstack.sdk/java) + ### Key Concepts for using Contentstack #### Stack @@ -59,7 +67,7 @@ A publishing environment corresponds to one or more deployment servers or a cont To initialize the SDK, specify application API key, access token, and environment name of the stack as shown in the snippet given below: ```java -Stack stack = Contentstack.stack( "APIKey", "accessToken", "environment_name"); +Stack stack=Contentstack.stack("apiKey","accessToken","environment"); ``` To get the API credentials mentioned above, log in to your Contentstack account and then in your top panel navigation, go to Settings > Stack to view the API Key and Access Token. @@ -70,27 +78,29 @@ To get the API credentials mentioned above, log in to your Contentstack account To retrieve a single entry from a content type use the code snippet given below: ```java +//stack is an instance of Stack class ContentType contentType = stack.contentType("content_type_uid"); -Entry blogEntry = contentType.entry("entry_uid"); -blogEntry.fetch(new EntryResultCallBack() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - //Success block - } else { - //Error block - }} - }); - ``` +Entry entry = contentType.entry("entry_uid"); +entry.fetch(new EntryResultCallBack(){ +@Override +public void onCompletion(ResponseType responseType, Error error){ + if(error==null){ + //Success block + }else{ + //Error block + }} +}); +``` + ##### Get Multiple Entries To retrieve multiple entries of a particular content type, use the code snippet given below: ```java //stack is an instance of Stack class -Query blogQuery = stack.contentType("content_type_uid").query(); -blogQuery.find(new QueryResultsCallBack() { - @Override +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){ //Success block @@ -111,7 +121,7 @@ You can query for content types, entries, assets and more using our Java API Ref We have introduced Image Delivery APIs that let you retrieve images and then manipulate and optimize them for your digital properties. It lets you perform a host of other actions such as crop, trim, resize, rotate, overlay, and so on. -For example, if you want to crop an image (with width as 300 and height as 400), you simply need to append query parameters at the end of the image URL, such as, https://images.contentstack.io/v3/assets/blteae40eb499811073/bltc5064f36b5855343/59e0c41ac0eddd140d5a8e3e/download?crop=300,400. There are several more parameters that you can use for your images. +For example, if you want to crop an image (with width as 300 and height as 400), you simply need to append query parameters at the end of the image URL, such as, https://images.contentstack.io/v3/assets/download?crop=300,400. There are several more parameters that you can use for your images. [Read Image Delivery API documentation](https://www.contentstack.com/docs/apis/image-delivery-api/). diff --git a/pom.xml b/pom.xml index 253e6c8d..92ba89cc 100644 --- a/pom.xml +++ b/pom.xml @@ -6,14 +6,47 @@ 4.0.0 com.contentstack.sdk java - 1.7.0 + 1.8.0-SNAPSHOT jar contentstack-java - Java SDK for Contentstack Content Delivery API, Contentstack is a headless CMS with an API-first - approach - + Java SDK for Contentstack Content Delivery API https://github.com/contentstack/contentstack-java/ + + + + v1.8.0 + v1.8.0 + 1.8 + 1.8 + UTF-8 + 2.22.0 + 2.2.1 + 3.0.0 + 5.2.2 + 3.1.2 + 2.9.0 + 2.9.0 + 4.9.2 + 0.8.5 + 1.18.22 + 5.8.1 + 5.8.0-M1 + 5.8.1 + 2.8.8 + 1.1.1 + 3.3 + 1.5 + 3.8.1 + 1.6.7 + 2.5.3 + 20210307 + 0.8.7 + 2.5.3 + 1.6.7 + 1.1.0 + + org.sonatype.oss oss-parent @@ -44,16 +77,6 @@ http://contentstack.com - - UTF-8 - UTF-8 - 1.8 - 3.0.0 - 2.22.0 - 2.2.1 - 3.1.1 - - shaileshmishra @@ -83,39 +106,64 @@ - + + + + + - com.contentstack.sdk - utils - 1.1.0 + org.json + json + ${json-version} io.github.cdimascio java-dotenv - 5.2.2 + ${dotenv-source.version} - junit - junit - 4.13.1 - test + io.reactivex.rxjava3 + rxjava + ${rxjava-source.version} - org.json - json - 20190722 + com.squareup.retrofit2 + retrofit + ${retrofit-source.version} + + + com.squareup.retrofit2 + converter-gson + ${converter-gson-source.version} + + + com.squareup.okhttp3 + logging-interceptor + ${loggin.version} - org.apache.logging.log4j - log4j-api - 2.5 + org.projectlombok + lombok + ${lombok-source.version} + - org.apache.logging.log4j - log4j-core - 2.13.2 + org.junit.jupiter + junit-jupiter + ${junit-jupiter.version} + test + + + org.junit.vintage + junit-vintage-engine + ${junit-vintage-engine.version} + + com.googlecode.json-simple + json-simple + ${json-simple-version} + @@ -130,19 +178,20 @@ # time-consuming stuff mvn surefire-report:report site -DgenerateReports=false --> - - org.apache.maven.plugins - maven-surefire-report-plugin - ${surefire-report-plugin.version} - - - test - - report-only - - - - + + + + + + + + + + + + + + org.apache.maven.plugins maven-source-plugin @@ -156,6 +205,7 @@ + org.apache.maven.plugins maven-javadoc-plugin @@ -180,12 +230,18 @@ + org.apache.maven.plugins maven-site-plugin 3.3 + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0-M2 + + + + + + + + + + + + + + + + + + org.jacoco jacoco-maven-plugin - 0.8.5 + ${jacoco-maven-plugin-version} + prepare-agent prepare-agent @@ -266,9 +343,39 @@ report + + post-unit-test + test + + report + + + target/jacoco.exec + target/jacoco-ut + + + + + + + + src/main/java/com/contentstack/sdk/Group.class + src/main/java/com/contentstack/sdk/FetchAssetsCallback.class + src/main/java/com/contentstack/sdk/SingleQueryResultCallback.class + src/main/java/com/contentstack/sdk/ContentTypesCallback.class + src/main/java/com/contentstack/sdk/QueryResultsCallBack.class + src/main/java/com/contentstack/sdk/FetchResultCallback.class + src/main/java/com/contentstack/sdk/EntryResultCallBack.class + src/main/java/com/contentstack/sdk/FetchResultCallback.class + + + + + org.apache.maven.plugins + maven-jxr-plugin + 2.3 - diff --git a/src/main/java/com/contentstack/sdk/APIService.java b/src/main/java/com/contentstack/sdk/APIService.java new file mode 100644 index 00000000..ac52a03c --- /dev/null +++ b/src/main/java/com/contentstack/sdk/APIService.java @@ -0,0 +1,15 @@ +package com.contentstack.sdk; + +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.http.GET; +import retrofit2.http.HeaderMap; +import retrofit2.http.Url; + +import java.util.LinkedHashMap; + +public interface APIService { + + @GET + Call getRequest(@Url String url, @HeaderMap LinkedHashMap headers); +} diff --git a/src/main/java/com/contentstack/sdk/Asset.java b/src/main/java/com/contentstack/sdk/Asset.java index 0f8cd1f5..482da792 100644 --- a/src/main/java/com/contentstack/sdk/Asset.java +++ b/src/main/java/com/contentstack/sdk/Asset.java @@ -1,506 +1,562 @@ package com.contentstack.sdk; -import com.contentstack.sdk.utility.CSAppConstants; -import com.contentstack.sdk.utility.CSController; -import com.contentstack.sdk.utility.ContentstackUtil; + +import org.jetbrains.annotations.NotNull; import org.json.JSONObject; -import java.util.*; + +import java.util.Calendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; import java.util.logging.Logger; +import static com.contentstack.sdk.Constants.ENVIRONMENT; +import static com.contentstack.sdk.Constants.parseDate; /** - * Asset refer to the media file (images, videos, PDFs, audio files, and so on) - * uploaded to Contentstack. These files can be used in multiple entries. + * The type Asset. */ - public class Asset { - private static final Logger logger = Logger.getLogger(Asset.class.getSimpleName()); - protected String assetUid = null; - protected String contentType = null; - protected String fileSize = null; - protected String fileName = null; - protected String uploadUrl = null; - protected JSONObject json = null; - protected String[] tagsArray = null; - public JSONObject urlQueries = new JSONObject(); - protected LinkedHashMap headerGroup_app; - protected LinkedHashMap headerGroup_local; + protected final Logger logger = Logger.getLogger(Asset.class.getSimpleName()); + protected final JSONObject urlQueries = new JSONObject(); + protected String assetUid = null; + protected String contentType = null; + protected String fileSize = null; + protected String fileName = null; + protected String uploadUrl = null; + protected JSONObject json = null; + protected String[] tagsArray = null; + protected LinkedHashMap headers; protected Stack stackInstance; - protected Asset(){ - this.headerGroup_local = new LinkedHashMap<>(); - this.headerGroup_app = new LinkedHashMap<>(); - + protected Asset() { + this.headers = new LinkedHashMap<>(); } - protected Asset(String assetUid){ + protected Asset(@NotNull String assetUid) { this.assetUid = assetUid; - this.headerGroup_local = new LinkedHashMap<>(); - this.headerGroup_app = new LinkedHashMap<>(); + this.headers = new LinkedHashMap<>(); } - protected void setStackInstance(Stack stack) { + protected void setStackInstance(@NotNull Stack stack) { this.stackInstance = stack; - this.headerGroup_app = stack.localHeader; + this.headers = stack.headers; } - /** - * Creates new instance of {@link Asset} from valid {@link JSONObject}. - * If JSON object is not appropriate then it will return null. - * @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 JSONObject}.
- * - *

Example :
- *
1. Single Attachment :-
- *
-     *  //'blt5d4sample2633b' is a dummy Application API key
-     * Stack stack = Contentstack.stack("apiKey", "deliveryToken",  "environment");
-     * Asset assetObject = stack.asset("assetUid");
-     * assetObject.configure(entryObject.getJSONObject(attached_image_field_uid));
- * - *
2. Multiple Attachment :-
- *
-     * JSONArray array = entryObject.getJSONArray(Attach_Image_Field_Uid);
-     * {@code for (int i = 0; i < array.length(); i++)} {
-     *  	  Asset assetObject = stack.asset("assetUid");
-     *  	  assetObject.configure(entryObject.getJSONObject(attached_image_field_uid));
-     *    }
-     * 
- * @return {@link Asset} instance. + * Configure asset. + * + * @param jsonObject the json object + * @return the asset */ - public Asset configure(JSONObject jsonObject){ - AssetModel model = null; - model = new AssetModel(jsonObject, true, false); - this.contentType = model.contentType; - this.fileSize = model.fileSize; - this.uploadUrl = model.uploadUrl; - this.fileName = model.fileName; - this.json = model.json; + public Asset configure(JSONObject jsonObject) { + AssetModel model; + model = new AssetModel(jsonObject, true); + this.contentType = model.contentType; + this.fileSize = model.fileSize; + this.uploadUrl = model.uploadUrl; + this.fileName = model.fileName; + this.json = model.json; this.assetUid = model.uploadedUid; this.setTags(model.tags); - model = null; - return this; - } - - - protected Asset setTags(String[] tags){ - tagsArray = tags; return this; } /** - * To set headers for Contentstack rest calls. - *
- * Scope is limited to this object only. - * @param key header name. - * @param value header value against given header name. - *

Example :
- *
-     * Asset assetObject = Contentstack.stack( "blt5d4sample2633b", "bltdtsample_accessToken767vv",  config).asset("assetUid");
-     * assetObject.setHeader("custom_header_key", "custom_header_value");
-     * 
+ * Sets header. + * + * @param headerKey the header key + * @param headerValue the header value + * + *
+ *
+ * Example :
+ * + *
+     *                    Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *                    Asset asset = stack.asset(asset_uid);
+     *                    asset.setHeader();
+     *                    
*/ - public void setHeader(String key, String value){ - if(!key.isEmpty() && !value.isEmpty()){ - removeHeader(key); - headerGroup_local.put(key, value); - } + public void setHeader(@NotNull String headerKey, @NotNull String headerValue) { + headers.put(headerKey, headerValue); } - /** - * Remove a header for a given key from headers. - *
- * Scope is limited to this object only - * @param key header key. - *

Example :
- *
-     * //'blt5d4sample2633b' is a dummy Application API key
-     * Asset assetObject = Contentstack.stack("blt5d4sample2633b", "bltdtsample_accessToken767vv",  config).asset("assetUid");
-     * assetObject.removeHeader("custom_header_key");
-     * 
+ * Remove header. + * + * @param headerKey the header key + * + * + *
+ *
+ * Example :
+ * + *
+     *                  Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *                  Asset asset = stack.asset(asset_uid);
+     *                  asset.removeHeader();
+     *
+     *                  
*/ - public void removeHeader(String key){ - if(headerGroup_local != null){ - if(!key.isEmpty()){ - headerGroup_local.remove(key); - } - } + public void removeHeader(@NotNull String headerKey) { + headers.remove(headerKey); } - - - /** - * To set uid of media file which is uploaded on Contentstack server. - * @param assetUid - * upload uid. - *

Example :
- *
-     * //'blt5d4sample2633b' is a dummy Application API key
-     * Asset assetObject = Contentstack.stack("blt5d4sample2633b", "bltdtsample_accessToken767vv",  config).asset("assetUid");
-     * assetObject.setUid("upload_uid");
-     * 
- * - */ - protected void setUid(String assetUid) { - if(!assetUid.isEmpty()){ + protected void setUid(@NotNull String assetUid) { + if (!assetUid.isEmpty()) { this.assetUid = assetUid; } } - - - - /** + * Gets asset uid. + * + * @return the asset uid + * + *
+ *
+ * Example :
* - * @return String @assetUid - *

Example :
- *
-     * String uid = assetObject.getAssetUid();
-     * return String of @uid
-     * 
+ *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Asset asset = stack.asset(asset_uid);
+     *         asset.fetch(new FetchResultCallback() {
+     *             @Override
+     *             public void onCompletion(ResponseType responseType, Error error) {
+     *                 asset.getAssetUid();
+     *             }
+     *         });
+     *
+     *         
*/ public String getAssetUid() { return assetUid; } - /** - * @return String @contentType - *

Example :
- *
-     * String contentType = assetObject.getFileType();
-     * 
+ * Gets file type. + * + * @return the file type + * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Asset asset = stack.asset(asset_uid);
+     *         asset.fetch(new FetchResultCallback() {
+     *             @Override
+     *             public void onCompletion(ResponseType responseType, Error error) {
+     *                 asset.getFileType();
+     *             }
+     *         });
+     *
+     *         
*/ public String getFileType() { return contentType; } - - /** + * Gets file size. + * + * @return the file size + * + *
+ *
+ * Example :
* - * @return String @fileSize - *
Note :
file size will receive in bytes number. - *

Example :
- *
-     * String queueSize = assetObject.getFileSize();
-     * 
+ *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Asset asset = stack.asset(asset_uid);
+     *         asset.fetch(new FetchResultCallback() {
+     *             @Override
+     *             public void onCompletion(ResponseType responseType, Error error) {
+     *                 asset.getFileSize();
+     *             }
+     *         });
+     *
+     *         
*/ - - public String getFileSize(){ + public String getFileSize() { return fileSize; } - /** - * @return String @fileName - *

Example :
- *
-     * String fileName = assetObject.getFileName();
-     * 
+ * Gets file name. * + * @return the file name + * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Asset asset = stack.asset(asset_uid);
+     *         asset.fetch(new FetchResultCallback() {
+     *             @Override
+     *             public void onCompletion(ResponseType responseType, Error error) {
+     *                 asset.getFileName();
+     *             }
+     *         });
+     *
+     *         
*/ - public String getFileName(){ + public String getFileName() { return fileName; } - /** - * @return String @uploadUrl by which you can download media file uploaded on Contentstack server. - * You will get uploaded url after uploading media file on Contentstack server. - *

Example :
- *
-     * String url = assetObject.getUrl();
-     * 
+ * Gets url. + * + * @return the url + * + *
+ *
+ * Example :
* + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Asset asset = stack.asset(asset_uid);
+     *         asset.fetch(new FetchResultCallback() {
+     *             @Override
+     *             public void onCompletion(ResponseType responseType, Error error) {
+     *                 asset.getUrl();
+     *             }
+     *         });
+     *
+     *         
*/ - public String getUrl(){ + public String getUrl() { return uploadUrl; } - /** + * To json json object. + * + * @return the json object * - * @return JSON @json representation of this {@link Asset} instance data. - *

Example :
- *
-     *  JSONObject json = assetObject.toJSON();
-     * 
+ *
+ *
+ * Example :
* + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Asset asset = stack.asset(asset_uid);
+     *         asset.fetch(new FetchResultCallback() {
+     *             @Override
+     *             public void onCompletion(ResponseType responseType, Error error) {
+     *                 asset.toJSON();
+     *             }
+     *         });
+     *
+     *         
*/ public JSONObject toJSON() { return json; } - /** - * @return Calendar @{@link java.util.Date} - * Get {@link Calendar} value of creation time of entry. - *

Example :
- *
-     * Calendar createdAt = assetObject.getCreateAt("key");
-     * 
+ * Gets create at. + * + * @return the create at + * + * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Asset asset = stack.asset(asset_uid);
+     *         asset.fetch(new FetchResultCallback() {
+     *             @Override
+     *             public void onCompletion(ResponseType responseType, Error error) {
+     *                 asset.getCreateAt();
+     *             }
+     *         });
+     *
+     *         
*/ - - public Calendar getCreateAt(){ - - try { - String value = json.optString("created_at"); - return ContentstackUtil.parseDate(value, null); - } catch (Exception e) { - logger.severe(e.getLocalizedMessage()); - } - return null; + public Calendar getCreateAt() { + return parseDate(json.optString("created_at"), null); } - - public String getCreatedBy(){ + /** + * Gets created by. + * + * @return the created by + * + * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Asset asset = stack.asset(asset_uid);
+     *         asset.fetch(new FetchResultCallback() {
+     *             @Override
+     *             public void onCompletion(ResponseType responseType, Error error) {
+     *                 asset.getCreatedBy();
+     *             }
+     *         });
+     *
+     *         
+ */ + public String getCreatedBy() { return json.optString("created_by"); } - /** - * Get {@link Calendar} value of updating time of entry. - * @return Calendar @{@link java.util.Date} - *

Example :
- *
-     * Calendar updatedAt = assetObject.getUpdateAt("key");
-     * 
+ * Gets update at. + * + * @return the update at + * + * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Asset asset = stack.asset(asset_uid);
+     *         asset.fetch(new FetchResultCallback() {
+     *             @Override
+     *             public void onCompletion(ResponseType responseType, Error error) {
+     *                 asset.getUpdateAt();
+     *             }
+     *         });
+     *
+     *         
*/ - - public Calendar getUpdateAt(){ - - try { - String value = json.optString("updated_at"); - return ContentstackUtil.parseDate(value, null); - } catch (Exception e) { - logger.severe(e.getLocalizedMessage()); - } - return null; + public Calendar getUpdateAt() { + return parseDate(json.optString("updated_at"), null); } - /** - * Get uid who updated this entry. - * @return String @getUpdatedBy - *

Example :
- *
-     * String updatedBy_uid = assetObject.getUpdatedBy();
-     * 
+ * Gets updated by. + * + * @return the updated by + * + * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Asset asset = stack.asset(asset_uid);
+     *         asset.fetch(new FetchResultCallback() {
+     *             @Override
+     *             public void onCompletion(ResponseType responseType, Error error) {
+     *                 asset.getUpdatedBy();
+     *             }
+     *         });
+     *
+     *         
*/ - - public String getUpdatedBy(){ + public String getUpdatedBy() { return json.optString("updated_by"); } - - - /** - * Get {@link Calendar} value of deletion time of entry - * @return Calendar @{@link java.util.Date} + * Gets delete at. + * + * @return the delete at * - *

Example :
- *
-     * Calendar updatedAt = entry.getUpdateAt("key");
-     * 
+ *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Asset asset = stack.asset(asset_uid);
+     *         asset.fetch(new FetchResultCallback() {
+     *             @Override
+     *             public void onCompletion(ResponseType responseType, Error error) {
+     *                 asset.getDeleteAt();
+     *             }
+     *         });
+     *
+     *         
*/ - public Calendar getDeleteAt(){ - - try { - String value = json.optString("deleted_at"); - return ContentstackUtil.parseDate(value, null); - } catch (Exception e) { - logger.severe(e.getLocalizedMessage()); - } - return null; + public Calendar getDeleteAt() { + return parseDate(json.optString("deleted_at"), null); } - /** - * Get uid who deleted this entry. + * Gets deleted by. * - * @return String @getDeletedBy - *

Example :
- *
-     * String deletedBy_uid = assetObject.getDeletedBy();
-     * 
+ * @return the deleted by + * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Asset asset = stack.asset(asset_uid);
+     *         asset.fetch(new FetchResultCallback() {
+     *             @Override
+     *             public void onCompletion(ResponseType responseType, Error error) {
+     *                 asset.getDeletedBy();
+     *             }
+     *         });
+     *
+     *         
*/ - public String getDeletedBy(){ + public String getDeletedBy() { return json.optString("deleted_by"); } - /** - * Get tags. - * @return String @tagsArray - *

Example :
- *
-     * String[] tags = assetObject.getURL();
-     * 
+ * Get tags string [ ]. + * + * @return the string [ ] + * + * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Asset asset = stack.asset(asset_uid);
+     *         asset.fetch(new FetchResultCallback() {
+     *             @Override
+     *             public void onCompletion(ResponseType responseType, Error error) {
+     *                 asset.getTags();
+     *             }
+     *         });
+     *
+     *         
*/ public String[] getTags() { return tagsArray; } + protected Asset setTags(String[] tags) { + tagsArray = tags; + return this; + } /** - * Include the dimensions (height and width) of the image in the response. - * Supported image types: JPG, GIF, PNG, WebP, BMP, TIFF, SVG, and PSD - * @return Asset + * Include dimension asset. + * + * @return the asset + * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Asset asset = stack.asset(asset_uid);
+     *         asset.includeDimension();
+     *         
*/ - public Asset includeDimension(){ + public Asset includeDimension() { urlQueries.put("include_dimension", true); return this; } - /** - * Fetch a particular asset using uid. - * @param callback - * {@link FetchResultCallback} instance for success and failure result. - *

Example :
- *
-     *  Asset asset = stack.asset("blt5312f71416d6e2c8");
-     *  asset.fetch(new FetchResultCallback() {
-     *    @Override
-     *    public void onCompletion(ResponseType responseType, Error error) {
-     *          if(error == null){
-     *            //Success Block.
-     *          }else {
-     *            //Fail Block.
-     *          }
-     *    }
-     *  });
-     * 
+ * Add param asset. + * + * @param paramKey the param key + * @param paramValue the param value + * @return the asset + * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Asset asset = stack.asset(asset_uid);
+     *         asset.addParam();
+     *         
*/ + public Asset addParam(@NotNull String paramKey, @NotNull String paramValue) { + urlQueries.put(paramKey, paramValue); + return this; + } - public void fetch(FetchResultCallback callback){ - try { - String URL = "/" + stackInstance.VERSION + "/assets/" + assetUid; - LinkedHashMap headers = getHeader(headerGroup_local); - if (headers.containsKey("environment")) { - urlQueries.put("environment", headers.get("environment")); - } - fetchFromNetwork(URL, urlQueries, headers, callback); - }catch (Exception e){ - Error error = new Error(); - error.setErrorMessage(CSAppConstants.ErrorMessage_JsonNotProper); - callback.onRequestFail(ResponseType.UNKNOWN, error); - } + /** + * Include fallback asset. + * + * @return the asset + * + * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Asset asset = stack.asset(asset_uid);
+     *         asset.includeFallback();
+     *         
+ */ + public Asset includeFallback() { + urlQueries.put("include_fallback", true); + return this; } + /** + * Includes Branch in the asset response + * + * @return {@link Asset} object, so you can chain this call.
+ * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Asset asset = stack.asset(asset_uid);
+     *         asset.includeBranch();
+     *         
+ */ + public Asset includeBranch() { + urlQueries.put("include_branch", true); + return this; + } + /** + * Fetch. + * + * @param callback the callback + */ + public void fetch(FetchResultCallback callback) { + urlQueries.put(ENVIRONMENT, this.headers.get(ENVIRONMENT)); + fetchFromNetwork("assets/" + assetUid, urlQueries, this.headers, callback); + } - private void fetchFromNetwork(String URL, JSONObject urlQueries, LinkedHashMap headers, FetchResultCallback callback) { - if(callback != null) { + private void fetchFromNetwork(String url, JSONObject urlQueries, LinkedHashMap headers, + FetchResultCallback callback) { + if (callback != null) { HashMap urlParams = getUrlParams(urlQueries); - new CSBackgroundTask(this, stackInstance, CSController.FETCHASSETS, URL, headers, urlParams, new JSONObject(), CSAppConstants.callController.ASSET.toString(), false, CSAppConstants.RequestMethod.GET, callback); + new CSBackgroundTask(this, stackInstance, Constants.FETCHASSETS, url, headers, urlParams, + Constants.REQUEST_CONTROLLER.ASSET.toString(), 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) { - logger.severe(e.getLocalizedMessage()); - } + if (urlQueriesJSON != null && urlQueriesJSON.length() > 0) { + Iterator keyArrays = urlQueriesJSON.keys(); + while (keyArrays.hasNext()) { + String key = keyArrays.next(); + Object value = urlQueriesJSON.opt(key); + hashMap.put(key, value); } - return hashMap; } - return null; - } - - - - - private LinkedHashMap getHeader(LinkedHashMap localHeader) { - LinkedHashMap mainHeader = headerGroup_app; - LinkedHashMap classHeaders = new LinkedHashMap<>(); - - 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 headerGroup_app; - } - } - - - /** - * This method adds key and value to an Entry. - * @param key The key as string which needs to be added to an Asset - * @param value The value as string which needs to be added to an Asset - * @return {@link Asset} - * - *

Example :
- *
-     *  final Asset asset = stack.asset("blt5312f71416d6e2c8");
-     *  asset.addParam("key", "some_value");
-     *  asset.fetch(new FetchResultCallback() {
-     *    @Override
-     *    public void onCompletion(ResponseType responseType, Error error) {
-     *          if(error == null){
-     *            //Success Block.
-     *          }else {
-     *            //Fail Block.
-     *          }
-     *    }
-     *  });
-     * 
- * - * - */ - public Asset addParam(String key, String value){ - if(key != null && value != null){ - urlQueries.put(key, value); - } - return this; - } - - - /** - * Retrieve the published content of the fallback locale if an entry is not localized in specified locale - * @return {@link Asset} object, so you can chain this call. - *

Example :
- *
-     *     Stack stack = Contentstack.stack("ApiKey", "deliveryToken", "environment");
-     *     final Asset asset = stack.asset("asset_uid");
-     *     asset.includeFallback();
-     * 
- */ - public Asset includeFallback(){ - urlQueries.put("include_fallback", true); - return this; + return hashMap; } } diff --git a/src/main/java/com/contentstack/sdk/AssetLibrary.java b/src/main/java/com/contentstack/sdk/AssetLibrary.java index cf1f191c..50a11903 100644 --- a/src/main/java/com/contentstack/sdk/AssetLibrary.java +++ b/src/main/java/com/contentstack/sdk/AssetLibrary.java @@ -1,345 +1,191 @@ package com.contentstack.sdk; - -import com.contentstack.sdk.utility.CSAppConstants; -import com.contentstack.sdk.utility.CSController; +import org.jetbrains.annotations.NotNull; import org.json.JSONObject; import java.util.*; import java.util.logging.Logger; +import static com.contentstack.sdk.Constants.ENVIRONMENT; + /** - Assets refer to all the media files (images, videos, PDFs, audio files, and so on) uploaded to Contentstack. - These files can be used in multiple entries. - Read more about [Assets](https://www.contentstack.com/docs/guide/content-management#working-with-assets) + * The type Asset library. */ -public class AssetLibrary implements INotifyClass{ - - private static final Logger logger = Logger.getLogger(AssetLibrary.class.getSimpleName()); - private Stack stackInstance; - private LinkedHashMap stackHeader; - private LinkedHashMap localHeader; - public JSONObject urlQueries; - private FetchAssetsCallback assetsCallback; - private int count; - +public class AssetLibrary implements INotifyClass { - /** - * Sorting order enum for {@link AssetLibrary}. - * @author Contentstack.com, Inc - */ - public enum ORDERBY - { - ASCENDING, - DESCENDING - } + protected final Logger logger = Logger.getLogger(AssetLibrary.class.getSimpleName()); + protected final JSONObject urlQueries; + protected Stack stackInstance; + protected LinkedHashMap headers; + protected FetchAssetsCallback callback; + protected int count; - protected AssetLibrary(){ - this.localHeader = new LinkedHashMap(); - this.urlQueries = new JSONObject(); + protected AssetLibrary() { + this.urlQueries = new JSONObject(); } - protected void setStackInstance(Stack stack){ + protected void setStackInstance(@NotNull Stack stack) { this.stackInstance = stack; - this.stackHeader = stack.localHeader; + this.headers = stack.headers; } /** - * To set headers for Contentstack rest calls. - *
- * Scope is limited to this object only. - * @param key - * header name. - * @param value - * header value against given header name. + * Sets header. * - *

Example :
- *
-     * //'blt5d4sample2633b' is a dummy Application API key
-     * AssetLibrary assetLibObject = Contentstack.stack("blt5d4sample2633b", "bltdtsample_accessToken767vv",  config).assetLibrary();
-     * assetLibObject.setHeader("custom_header_key", "custom_header_value");
-     * 
+ * @param headerKey the header key + * @param headerValue the header value */ - public void setHeader(String key, String value) { - if (!key.isEmpty() && !value.isEmpty()) { - localHeader.put(key, value); - } + public void setHeader(@NotNull String headerKey, @NotNull String headerValue) { + this.headers.put(headerKey, headerValue); } - /** - * Remove a header for a given key from headers. - *
- * Scope is limited to this object only. - * @param key header key. - *

Example :
- *
-     * //'blt5d4sample2633b' is a dummy Application API key
-     * AssetLibrary assetLibObject = Contentstack.stack("blt5d4sample2633b", "bltdtsample_accessToken767vv",  config).assetLibrary();
+     * Remove header.
      *
-     * assetLibObject.removeHeader("custom_header_key");
-     * 
+ * @param headerKey the header key */ - public void removeHeader(String key){ - if(!key.isEmpty()){ - localHeader.remove(key); + public void removeHeader(@NotNull String headerKey) { + if (!headerKey.isEmpty()) { + this.headers.remove(headerKey); } } - /** - * Sort assets by fieldUid. - * @param key - * field Uid. - * @param orderby - * {@link ORDERBY} value for ascending or descending. - * @return - * {@link AssetLibrary} object, so you can chain this call. - *

Example :
- *
-     * //'blt5d4sample2633b' is a dummy Application API key
-     * AssetLibrary assetLibObject = Contentstack.stack("blt5d4sample2633b", "bltdtsample_accessToken767vv",  config).assetLibrary();
-     * assetLibObject.sort("fieldUid", AssetLibrary.ORDERBY.ASCENDING);
-     * 
+ * Sort asset library. * + * @param keyOrderBy the key order by + * @param orderby the orderby + * @return the asset library */ - public AssetLibrary sort(String key, ORDERBY orderby){ - try { - switch (orderby){ - case ASCENDING: - urlQueries.put("asc",key); - break; - - case DESCENDING: - urlQueries.put("desc",key); - break; - } - }catch(Exception e) { - throwException("sort", CSAppConstants.ErrorMessage_QueryFilterException, e); + public AssetLibrary sort(String keyOrderBy, ORDERBY orderby) { + if (orderby == ORDERBY.ASCENDING) { + urlQueries.put("asc", keyOrderBy); + } else { + urlQueries.put("desc", keyOrderBy); } - return this; } /** - * Retrieve count and data of assets in result. - * @return {@link AssetLibrary} object, so you can chain this call. + * Include count asset library. * - *

Example :
- *
-     * //'blt5d4sample2633b' is a dummy Stack API key
-     * //'bltdtsample_accessToken767vv' is dummy access token.
-     * AssetLibrary assetLibObject = Contentstack.stack( "blt5d4sample2633b", "bltdtsample_accessToken767vv",  config).assetLibrary();
-     * assetLibObject.includeCount();
-     * 
+ * @return the asset library */ - public AssetLibrary includeCount(){ - try { - urlQueries.put("include_count","true"); - } catch (Exception e) { - throwException("includeCount", CSAppConstants.ErrorMessage_QueryFilterException, e); - } + public AssetLibrary includeCount() { + urlQueries.put("include_count", "true"); return this; } + /** + * Include relative url asset library. + * + * @return the asset library + */ + public AssetLibrary includeRelativeUrl() { + urlQueries.put("relative_urls", "true"); + return this; + } /** - * Retrieve relative urls objects in result. - * @return - * {@link AssetLibrary} object, so you can chain this call. - *

Example :
- *
-     * //'blt5d4sample2633b' is a dummy Stack API key
-     * //'bltdtsample_accessToken767vv' is dummy access token.
-     * AssetLibrary assetLibObject = Contentstack.stack( "blt5d4sample2633b", "bltdtsample_accessToken767vv",  config).assetLibrary();
-     * assetLibObject.includeRelativeUrl();
-     * 
+ * Retrieve the published content of the fallback locale if an entry is not + * localized in specified locale + * + * @return {@link AssetLibrary} object, so you can chain this call.
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         AssetLibrary assetLibObject = stack.assetLibrary();
+     *         AssetLibrary.includeFallback();
+     *         
*/ - public AssetLibrary includeRelativeUrl(){ - try { - urlQueries.put("relative_urls","true"); - } catch (Exception e) { - throwException("relative_urls", CSAppConstants.ErrorMessage_QueryFilterException, e); - } + public AssetLibrary includeFallback() { + urlQueries.put("include_fallback", true); return this; } /** - * Get a count of assets in success callback of {@link FetchAssetsCallback}. - * @return int @count + * Gets count. + * + * @return the count */ - public int getCount(){ + public int getCount() { return count; } - - /** - * Fetch a all asset. - * @param assetsCallback - * {@link FetchAssetsCallback} instance for success and failure result. - * - *

Example :
- *
-     *   AssetLibrary assetLibObject = Contentstack.stack("blt5d4sample2633b", "bltdtsample_accessToken767vv",  config).assetLibrary();
-     *   assetLibObject.fetchAll(new FetchAssetsCallback() {
-     *   {@code public void onCompletion(ResponseType responseType, List assets, Error error) }{
-     *      if (error == null) {
-     *         //Success Block.
-     *      } else {
-     *         //Error Block.
-     *      }
-     *   }
-     *  });
-     *
-     * 
+ * Fetch all. * + * @param callback the callback */ - public void fetchAll(FetchAssetsCallback assetsCallback){ - try { - this.assetsCallback = assetsCallback; - String URL = "/" + stackInstance.VERSION + "/assets"; - LinkedHashMap headers = getHeader(localHeader); - if (headers.containsKey("environment")) { - urlQueries.put("environment", headers.get("environment")); - } - - fetchFromNetwork(URL, urlQueries, headers, assetsCallback); - - } catch (Exception e){ - logger.severe(e.getLocalizedMessage()); - } - + public void fetchAll(FetchAssetsCallback callback) { + this.callback = callback; + urlQueries.put(ENVIRONMENT, headers.get(ENVIRONMENT)); + fetchFromNetwork("assets", urlQueries, headers, callback); } - - - private void fetchFromNetwork(String URL, JSONObject urlQueries, LinkedHashMap headers, FetchAssetsCallback assetsCallback) { - if(assetsCallback != null) { + private void fetchFromNetwork(String url, JSONObject urlQueries, LinkedHashMap headers, + FetchAssetsCallback callback) { + if (callback != null) { HashMap urlParams = getUrlParams(urlQueries); - new CSBackgroundTask(this, stackInstance, CSController.FETCHALLASSETS, URL, headers, urlParams, new JSONObject(), CSAppConstants.callController.ASSETLIBRARY.toString(), false, CSAppConstants.RequestMethod.GET, assetsCallback); + new CSBackgroundTask(this, stackInstance, Constants.FETCHALLASSETS, url, headers, urlParams, + Constants.REQUEST_CONTROLLER.ASSETLIBRARY.toString(), callback); } } - - - - /** - * @param urlQueriesJSON takes {@link JSONObject} object as argeument - * @return - */ - private HashMap getUrlParams(JSONObject urlQueriesJSON) { - HashMap hashMap = new HashMap<>(); - if(urlQueriesJSON != null && urlQueriesJSON.length() > 0){ + 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) { - logger.severe(e.getLocalizedMessage()); - } - } - - return hashMap; - } - - return null; - } - - - /** - * @param tag String to which Class belong - * @param messageString takes as Message - * @param e Exception - */ - private void throwException(String tag, String messageString, Exception e){ - Error error = new Error(); - error.setErrorMessage(messageString); - } - - private LinkedHashMap getHeader(LinkedHashMap localHeader) { - LinkedHashMap mainHeader = stackHeader; - LinkedHashMap classHeaders = new LinkedHashMap<>(); - - 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; + Object value = urlQueriesJSON.opt(key); + hashMap.put(key, value); } - - }else{ - return stackHeader; } + return hashMap; } @Override - public void getResult(Object object, String controller) {} + public void getResult(Object object, String controller) { + logger.warning("No implementation required"); + } @Override public void getResultObject(List objects, JSONObject jsonObject, boolean isSingleEntry) { - if(jsonObject != null && jsonObject.has("count")){ + if (jsonObject != null && jsonObject.has("count")) { count = jsonObject.optInt("count"); } - List assets = new ArrayList(); + List assets = new ArrayList<>(); - if(objects != null && objects.size() > 0){ + if (objects != null && !objects.isEmpty()) { for (Object object : objects) { AssetModel model = (AssetModel) object; - Asset asset = stackInstance.asset(); - - asset.contentType = model.contentType; - asset.fileSize = model.fileSize; - asset.uploadUrl = model.uploadUrl; - asset.fileName = model.fileName; - asset.json = model.json; + Asset asset = stackInstance.asset(); + asset.contentType = model.contentType; + asset.fileSize = model.fileSize; + asset.uploadUrl = model.uploadUrl; + asset.fileName = model.fileName; + asset.json = model.json; asset.assetUid = model.uploadedUid; asset.setTags(model.tags); - model = null; - assets.add(asset); } } - if(assetsCallback != null) { - assetsCallback.onRequestFinish(ResponseType.NETWORK, assets); + if (callback != null) { + callback.onRequestFinish(ResponseType.NETWORK, assets); } } - - /** - * Retrieve the published content of the fallback locale if an entry is not localized in specified locale - * @return {@link AssetLibrary} object, so you can chain this call. - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "ApiKey", "deliveryToken",  environment_name);
-     *     AssetLibrary assetLibObject = stack.assetLibrary();
-     *     assetLibObject.includeFallback();
-     * 
+ * The enum Orderby. */ - public AssetLibrary includeFallback(){ - urlQueries.put("include_fallback", true); - return this; + public enum ORDERBY { + ASCENDING, DESCENDING } } diff --git a/src/main/java/com/contentstack/sdk/AssetModel.java b/src/main/java/com/contentstack/sdk/AssetModel.java index 7ff1e466..15c4ffb3 100644 --- a/src/main/java/com/contentstack/sdk/AssetModel.java +++ b/src/main/java/com/contentstack/sdk/AssetModel.java @@ -2,15 +2,10 @@ import org.json.JSONArray; import org.json.JSONObject; -import java.util.Iterator; -import java.util.WeakHashMap; - /** - * @Author Shailesh Mishra - * Asset Object Model + * The type Asset model. */ - class AssetModel { String uploadedUid; @@ -20,59 +15,53 @@ class AssetModel { String uploadUrl; String[] tags; JSONObject json; - private int totalCount = 0; int count = 0; + int totalCount = 0; - public AssetModel(JSONObject responseJSON, boolean isArray, boolean isFromCache) { - - if(isFromCache){ - json = responseJSON.opt("response") == null ? responseJSON : responseJSON.optJSONObject("response"); - }else{ - json = responseJSON; - } + /** + * Instantiates a new Asset model. + * + * @param response the response + * @param isArray the is array + */ + public AssetModel(JSONObject response, boolean isArray) { - if(isArray){ - json = responseJSON; - }else{ - json = responseJSON.optJSONObject("asset"); + if (isArray) { + json = response; + } else { + json = response.optJSONObject("asset"); } - uploadedUid = (String) json.opt("uid"); - contentType = (String) json.opt("content_type"); - fileSize = (String) json.opt("file_size"); - fileName = (String) json.opt("filename"); - uploadUrl = (String) json.opt("url"); - - 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(); - tags = new String[count]; - for(int i = 0; i < count; i++){ - tags[i] = (String) tagsArray.opt(i); - } - } + if (json != null) { + uploadedUid = (String) json.opt("uid"); + contentType = (String) json.opt("content_type"); + fileSize = (String) json.opt("file_size"); + fileName = (String) json.opt("filename"); + uploadUrl = (String) json.opt("url"); + if (json.opt("tags") instanceof JSONArray) { + extractTags(); } - } - - if(json != null && json.has("_metadata")){ - JSONObject _metadataJSON = json.optJSONObject("_metadata"); - Iterator iterator = _metadataJSON.keys(); - WeakHashMap _metadata = new WeakHashMap(); - while (iterator.hasNext()) { - String key = iterator.next(); - _metadata.put(key, _metadataJSON.optString(key)); + if (response.has("count")) { + count = response.optInt("count"); } - } - if(responseJSON.has("count")){ - count = responseJSON.optInt("count"); + if (response.has("objects")) { + totalCount = response.optInt("objects"); + } } + } - if(responseJSON.has("objects")){ - totalCount = responseJSON.optInt("objects"); + private void extractTags() { + JSONArray tagArray = json.optJSONArray("tags"); + if (tagArray != null && !tagArray.isEmpty()) { + JSONArray tagsArray = (JSONArray) json.opt("tags"); + if (tagsArray.length() > 0) { + int counter = tagsArray.length(); + tags = new String[counter]; + for (int i = 0; i < counter; i++) { + tags[i] = (String) tagsArray.opt(i); + } + } } } diff --git a/src/main/java/com/contentstack/sdk/AssetsModel.java b/src/main/java/com/contentstack/sdk/AssetsModel.java index 97f77c5b..9811ebe4 100644 --- a/src/main/java/com/contentstack/sdk/AssetsModel.java +++ b/src/main/java/com/contentstack/sdk/AssetsModel.java @@ -2,21 +2,30 @@ import org.json.JSONArray; import org.json.JSONObject; + import java.util.ArrayList; import java.util.List; +/** + * The type Assets model. + */ 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; - } + List objects = new ArrayList<>(); + + /** + * Instantiates a new Assets model. + * + * @param response the response + */ + public AssetsModel(JSONObject response) { + JSONArray listResponse = response != null && response.has("assets") ? response.optJSONArray("assets") : null; + if (listResponse != null) { + listResponse.forEach(model -> { + JSONObject modelObj = (JSONObject) model; + AssetModel newModel = new AssetModel(modelObj, true); + objects.add(newModel); + }); } } } diff --git a/src/main/java/com/contentstack/sdk/CSBackgroundTask.java b/src/main/java/com/contentstack/sdk/CSBackgroundTask.java index 60a56af8..ad5cdd51 100644 --- a/src/main/java/com/contentstack/sdk/CSBackgroundTask.java +++ b/src/main/java/com/contentstack/sdk/CSBackgroundTask.java @@ -1,92 +1,90 @@ package com.contentstack.sdk; -import com.contentstack.sdk.utility.CSAppConstants; -import org.json.JSONObject; + +import org.jetbrains.annotations.NotNull; + import java.util.HashMap; import java.util.LinkedHashMap; - +import java.util.Map; +import java.util.logging.Logger; class CSBackgroundTask { - public CSBackgroundTask(Query queryInstance, Stack stackInstance, String controller, String url, LinkedHashMap headers, LinkedHashMap urlQueries, JSONObject jsonMain, String requestInfo, CSAppConstants.RequestMethod method, ResultCallBack callback) { - if (headers != null && headers.size() > 0) { - String URL = stackInstance.URLSCHEMA + stackInstance.URL + url; - CSConnectionRequest csConnectionRequest = new CSConnectionRequest(queryInstance); - csConnectionRequest.setQueryInstance(queryInstance); - csConnectionRequest.setURLQueries(urlQueries); - csConnectionRequest.setParams(URL, method, controller, jsonMain, headers, requestInfo, callback); - } else { - sendErrorForHeader(callback); - } + protected CSBackgroundTask() { } + protected CSBackgroundTask(Stack stackInstance, String controller, String url, HashMap headers, + HashMap urlParams, String requestInfo, ResultCallBack callback) { + checkHeader(headers); + String completeUrl = stackInstance.config.getEndpoint() + url; + CSConnectionRequest csConnectionRequest = new CSConnectionRequest(stackInstance); + csConnectionRequest.setStackInstance(stackInstance); + csConnectionRequest.setURLQueries(urlParams); + csConnectionRequest.setParams(completeUrl, headers, controller, requestInfo, callback); - public CSBackgroundTask(Entry entryInstance, Stack stackInstance, String controller, String url, LinkedHashMap headers, HashMap urlQueries, JSONObject jsonMain, String requestInfo, boolean isOffline, CSAppConstants.RequestMethod method, ResultCallBack callBack) { - if (headers != null && headers.size() > 0) { - String URL = stackInstance.URLSCHEMA + stackInstance.URL + url; - CSConnectionRequest csConnectionRequest = new CSConnectionRequest(entryInstance); - csConnectionRequest.setURLQueries(urlQueries); - csConnectionRequest.setParams(URL, method, controller, jsonMain, headers, requestInfo, callBack); - } else { - sendErrorForHeader(callBack); - } } + protected CSBackgroundTask(Query queryInstance, Stack stackInstance, String controller, String url, + LinkedHashMap headers, HashMap urlQueries, String requestInfo, + ResultCallBack callback) { + checkHeader(headers); + String completeUrl = stackInstance.config.getEndpoint() + url; + CSConnectionRequest csConnectionRequest = new CSConnectionRequest(queryInstance); + csConnectionRequest.setQueryInstance(queryInstance); + csConnectionRequest.setURLQueries(urlQueries); + csConnectionRequest.setParams(completeUrl, headers, controller, requestInfo, callback); - - public CSBackgroundTask(AssetLibrary assetLibrary, Stack stackInstance, String controller, String url, LinkedHashMap headers, HashMap urlQueries, JSONObject jsonMain, String requestInfo, boolean isOffline, CSAppConstants.RequestMethod method, ResultCallBack callback) { - if (headers != null && headers.size() > 0) { - String URL = stackInstance.URLSCHEMA + stackInstance.URL + url; - CSConnectionRequest csConnectionRequest = new CSConnectionRequest(assetLibrary); - csConnectionRequest.setURLQueries(urlQueries); - csConnectionRequest.setParams(URL, method, controller, jsonMain, headers, requestInfo, callback); - } else { - sendErrorForHeader(callback); - } } - - public CSBackgroundTask(Asset asset, Stack stackInstance, String controller, String url, LinkedHashMap headers, HashMap urlQueries, JSONObject jsonMain, String requestInfo, boolean isOffline, CSAppConstants.RequestMethod method, ResultCallBack callback) { - if (headers != null && headers.size() > 0) { - String URL = stackInstance.URLSCHEMA + stackInstance.URL + url; - CSConnectionRequest csConnectionRequest = new CSConnectionRequest(asset); - csConnectionRequest.setURLQueries(urlQueries); - csConnectionRequest.setParams(URL, method, controller, jsonMain, headers, requestInfo, callback); - } else { - sendErrorForHeader(callback); - } - + protected CSBackgroundTask(Entry entryInstance, Stack stackInstance, String controller, String url, + LinkedHashMap headers, HashMap urlQueries, String requestInfo, + ResultCallBack callBack) { + checkHeader(headers); + String completeUrl = stackInstance.config.getEndpoint() + url; + CSConnectionRequest csConnectionRequest = new CSConnectionRequest(entryInstance); + csConnectionRequest.setURLQueries(urlQueries); + csConnectionRequest.setParams(completeUrl, headers, controller, requestInfo, callBack); } + protected CSBackgroundTask(AssetLibrary assetLibrary, Stack stackInstance, String controller, String url, + LinkedHashMap headers, HashMap urlQueries, String requestInfo, + ResultCallBack callback) { + checkHeader(headers); + String completeUrl = stackInstance.config.getEndpoint() + url; + CSConnectionRequest csConnectionRequest = new CSConnectionRequest(assetLibrary); + csConnectionRequest.setURLQueries(urlQueries); + csConnectionRequest.setParams(completeUrl, headers, controller, requestInfo, callback); - public CSBackgroundTask(Stack stackInstance, String controller, String url, HashMap headers, HashMap urlParams, JSONObject jsonMain, String requestInfo, boolean b, CSAppConstants.RequestMethod method, ResultCallBack callback) { - if (headers != null && headers.size() > 0) { - String URL = stackInstance.URLSCHEMA + stackInstance.URL + url; - CSConnectionRequest csConnectionRequest = new CSConnectionRequest(stackInstance); - csConnectionRequest.setStackInstance(stackInstance); - csConnectionRequest.setURLQueries(urlParams); - csConnectionRequest.setParams(URL, method, controller, jsonMain, headers, requestInfo, callback); - } else { - sendErrorForHeader(callback); - } } + protected CSBackgroundTask(Asset asset, Stack stackInstance, String controller, String url, + LinkedHashMap headers, HashMap urlQueries, String requestInfo, + ResultCallBack callback) { + checkHeader(headers); + String completeUrl = stackInstance.config.getEndpoint() + url; + CSConnectionRequest csConnectionRequest = new CSConnectionRequest(asset); + csConnectionRequest.setURLQueries(urlQueries); + csConnectionRequest.setParams(completeUrl, headers, controller, requestInfo, callback); + } - public CSBackgroundTask(ContentType contentTypeInstance, Stack stackInstance, String controller, String url, HashMap headers, HashMap urlParams, JSONObject jsonMain, String requestInfo, boolean b, CSAppConstants.RequestMethod method, ResultCallBack callback) { - if (headers != null && headers.size() > 0) { - String URL = stackInstance.URLSCHEMA + stackInstance.URL + url; - CSConnectionRequest csConnectionRequest = new CSConnectionRequest(contentTypeInstance); - csConnectionRequest.setURLQueries(urlParams); - csConnectionRequest.setParams(URL, method, controller, jsonMain, headers, requestInfo, callback); - } else { - sendErrorForHeader(callback); - } + protected CSBackgroundTask(ContentType contentType, Stack stackInstance, String controller, String url, + HashMap headers, HashMap urlParams, String requestInfo, + ResultCallBack callback) { + checkHeader(headers); + String completeUrl = stackInstance.config.getEndpoint() + url; + CSConnectionRequest csConnectionRequest = new CSConnectionRequest(contentType); + csConnectionRequest.setURLQueries(urlParams); + csConnectionRequest.setParams(completeUrl, headers, controller, requestInfo, callback); } - private void sendErrorForHeader(ResultCallBack callbackObject) { - Error error = new Error(); - error.setErrorMessage(CSAppConstants.ErrorMessage_CalledDefaultMethod); - if (callbackObject != null) { - callbackObject.onRequestFail(ResponseType.UNKNOWN, error); + protected void checkHeader(@NotNull Map headers) { + final Logger logger = Logger.getLogger("CSBackgroundTask"); + if (headers.size() == 0) { + try { + throw new IllegalAccessException("CSBackgroundTask Header Exception"); + } catch (IllegalAccessException e) { + logger.severe(e.getLocalizedMessage()); + } } } + } diff --git a/src/main/java/com/contentstack/sdk/CSConnectionRequest.java b/src/main/java/com/contentstack/sdk/CSConnectionRequest.java index f5ee50ed..74146e5b 100644 --- a/src/main/java/com/contentstack/sdk/CSConnectionRequest.java +++ b/src/main/java/com/contentstack/sdk/CSConnectionRequest.java @@ -1,53 +1,47 @@ package com.contentstack.sdk; -import com.contentstack.sdk.utility.CSAppConstants; -import com.contentstack.sdk.utility.CSController; import org.json.JSONObject; -import java.util.*; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import static com.contentstack.sdk.Constants.*; class CSConnectionRequest implements IRequestModelHTTP { + protected String endpoint; private String urlToCall; - private CSAppConstants.RequestMethod method; private String controller; - private JSONObject paramsJSON; + private String requestInfo; private LinkedHashMap header; private HashMap urlQueries; - private String requestInfo; - private ResultCallBack callBackObject; - private CSHttpConnection connection; - private JSONObject responseJSON; + private ResultCallBack resultCallBack; private INotifyClass notifyClass; - private INotifyClass assetLibrary; + private AssetLibrary assetLibrary; private Entry entryInstance; - private Query queryInstance; private Asset assetInstance; private Stack stackInstance; - private ContentType contentType; - private JSONObject errorJObject; - private Error errorObject = new Error(); - - - public CSConnectionRequest() { - } public CSConnectionRequest(Query queryInstance) { notifyClass = queryInstance; + this.endpoint = queryInstance.contentTypeInstance.stackInstance.config.getEndpoint(); } public CSConnectionRequest(Entry entryInstance) { this.entryInstance = entryInstance; + this.endpoint = this.entryInstance.contentType.stackInstance.config.getEndpoint(); } - public CSConnectionRequest(INotifyClass assetLibrary) { + public CSConnectionRequest(AssetLibrary assetLibrary) { this.assetLibrary = assetLibrary; + this.endpoint = this.assetLibrary.stackInstance.config.getEndpoint(); } public CSConnectionRequest(Asset asset) { this.assetInstance = asset; + this.endpoint = this.assetInstance.stackInstance.config.getEndpoint(); } public CSConnectionRequest(Stack stack) { @@ -55,11 +49,11 @@ public CSConnectionRequest(Stack stack) { } public CSConnectionRequest(ContentType contentType) { - this.contentType = contentType; + this.endpoint = contentType.stackInstance.config.getEndpoint(); } public void setQueryInstance(Query queryInstance) { - this.queryInstance = queryInstance; + this.endpoint = queryInstance.contentTypeInstance.stackInstance.config.getEndpoint(); } public void setURLQueries(HashMap urlQueries) { @@ -67,134 +61,81 @@ public void setURLQueries(HashMap urlQueries) { } public void setStackInstance(Stack stackInstance) { + this.endpoint = this.stackInstance.config.getEndpoint(); this.stackInstance = stackInstance; } - public void setParams(Object... objects) { - - this.urlToCall = (String) objects[0]; - this.method = (CSAppConstants.RequestMethod) objects[1]; + this.header = (LinkedHashMap) objects[1]; this.controller = (String) objects[2]; - paramsJSON = (JSONObject) objects[3]; - this.header = (LinkedHashMap) objects[4]; - - if (objects[5] != null) { - requestInfo = (String) objects[5]; - } - if (objects[6] != null) { - callBackObject = (ResultCallBack) objects[6]; + this.requestInfo = (String) objects[3]; + if (objects[4] != null) { + resultCallBack = (ResultCallBack) objects[4]; } sendRequest(); } - @Override public void sendRequest() { - - connection = new CSHttpConnection(urlToCall, this); + CSHttpConnection connection = new CSHttpConnection(urlToCall, this); connection.setController(controller); connection.setHeaders(header); connection.setInfo(requestInfo); - connection.setFormParamsPOST(paramsJSON); - connection.setCallBackObject(callBackObject); - + connection.setEndpoint(this.endpoint); + connection.setCallBackObject(resultCallBack); if (urlQueries != null && urlQueries.size() > 0) { connection.setFormParams(urlQueries); } - - connection.setRequestMethod(method); connection.send(); - } - @Override public void onRequestFailed(JSONObject error, int statusCode, ResultCallBack callBackObject) { - - String errMsg = ""; - int errCode = 0; - JSONObject errors = null; - if (error != null && !error.isEmpty()) { - if (error.has("error_message")) { - errMsg = error.optString("error_message"); - } - if (error.has("error_code")) { - errCode = error.optInt("error_code"); - } - if (error.has("errors")) { - if (error.opt("errors") instanceof JSONObject) { - JSONObject errorsJsonObj = error.optJSONObject("errors"); - Iterator iterator = errorsJsonObj.keys(); - while (iterator.hasNext()) { - String key = iterator.next(); - Object value = errorsJsonObj.opt(key); - errorObject.setErrorDetail(error.get("errors").toString()); - } - } - } + Error errResp = new Error(); + if (error.has(ERROR_MESSAGE)) { + String errMsg = error.optString(ERROR_MESSAGE); + errResp.setErrorMessage(errMsg); } - errorObject.setErrorCode(errCode); - errorObject.setErrorMessage(errMsg); - errorObject.setErrorDetail(error.get("errors").toString()); - if (this.callBackObject != null) { - this.callBackObject.onRequestFail(ResponseType.NETWORK, errorObject); + if (error.has(ERROR_CODE)) { + int errCode = error.optInt(ERROR_CODE); + errResp.setErrorCode(errCode); + } + if (error.has(ERRORS)) { + String errorDetail = (String) error.opt(ERRORS); + errResp.setErrorDetail(errorDetail); + } + if (this.resultCallBack != null) { + this.resultCallBack.onRequestFail(ResponseType.NETWORK, errResp); } - } - @Override public void onRequestFinished(CSHttpConnection request) { - responseJSON = request.getResponse(); - String controller = request.getController(); - if (controller.equalsIgnoreCase(CSController.QUERYOBJECT)) { - 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)) { - - 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)) { - - EntryModel model = new EntryModel(responseJSON, null, false, false, false); + JSONObject jsonResponse = request.getResponse(); + if (request.getController().equalsIgnoreCase(Constants.QUERYOBJECT)) { + EntriesModel model = new EntriesModel(jsonResponse); + notifyClass.getResultObject(model.objectList, jsonResponse, false); + } else if (request.getController().equalsIgnoreCase(Constants.SINGLEQUERYOBJECT)) { + EntriesModel model = new EntriesModel(jsonResponse); + notifyClass.getResultObject(model.objectList, jsonResponse, true); + } else if (request.getController().equalsIgnoreCase(Constants.FETCHENTRY)) { + EntryModel model = new EntryModel(jsonResponse); entryInstance.resultJson = model.jsonObject; - entryInstance.ownerEmailId = model.ownerEmailId; - entryInstance.ownerUid = model.ownerUid; entryInstance.title = model.title; entryInstance.url = model.url; entryInstance.language = model.language; - - if (model.ownerMap != null) { - entryInstance.owner = new HashMap<>(model.ownerMap); - } - if (model._metadata != null) { - entryInstance._metadata = new HashMap<>(model._metadata); - } - entryInstance.uid = model.entryUid; + entryInstance.uid = model.uid; entryInstance.setTags(model.tags); - model = null; - if (request.getCallBackObject() != null) { ((EntryResultCallBack) request.getCallBackObject()).onRequestFinish(ResponseType.NETWORK); } - - } else if (controller.equalsIgnoreCase(CSController.FETCHALLASSETS)) { - AssetsModel assetsModel = new AssetsModel(responseJSON, false); + } else if (request.getController().equalsIgnoreCase(Constants.FETCHALLASSETS)) { + AssetsModel assetsModel = new AssetsModel(jsonResponse); List objectList = assetsModel.objects; - assetsModel = null; - - assetLibrary.getResultObject(objectList, responseJSON, false); - - } else if (controller.equalsIgnoreCase(CSController.FETCHASSETS)) { - AssetModel model = new AssetModel(responseJSON, false, false); - + assetLibrary.getResultObject(objectList, jsonResponse, false); + } else if (request.getController().equalsIgnoreCase(Constants.FETCHASSETS)) { + AssetModel model = new AssetModel(jsonResponse, false); assetInstance.contentType = model.contentType; assetInstance.fileSize = model.fileSize; assetInstance.uploadUrl = model.uploadUrl; @@ -202,29 +143,22 @@ public void onRequestFinished(CSHttpConnection request) { assetInstance.json = model.json; assetInstance.assetUid = model.uploadedUid; assetInstance.setTags(model.tags); - - model = null; if (request.getCallBackObject() != null) { ((FetchResultCallback) request.getCallBackObject()).onRequestFinish(ResponseType.NETWORK); } - } else if (controller.equalsIgnoreCase(CSController.FETCHSYNC)) { - + } else if (request.getController().equalsIgnoreCase(Constants.FETCHSYNC)) { SyncStack model = new SyncStack(); - model.setJSON(responseJSON); + model.setJSON(jsonResponse); if (request.getCallBackObject() != null) { ((SyncResultCallBack) request.getCallBackObject()).onRequestFinish(model); } - - } else if (controller.equalsIgnoreCase(CSController.FETCHCONTENTTYPES)) { - + } else if (request.getController().equalsIgnoreCase(Constants.FETCHCONTENTTYPES)) { ContentTypesModel model = new ContentTypesModel(); - model.setJSON(responseJSON); + model.setJSON(jsonResponse); if (request.getCallBackObject() != null) { ((ContentTypesCallback) request.getCallBackObject()).onRequestFinish(model); } - } } - } diff --git a/src/main/java/com/contentstack/sdk/CSHttpConnection.java b/src/main/java/com/contentstack/sdk/CSHttpConnection.java index 2673a4cc..a82393ed 100644 --- a/src/main/java/com/contentstack/sdk/CSHttpConnection.java +++ b/src/main/java/com/contentstack/sdk/CSHttpConnection.java @@ -1,51 +1,46 @@ package com.contentstack.sdk; -import com.contentstack.sdk.utility.CSAppConstants; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; +import retrofit2.Response; +import retrofit2.Retrofit; -import java.io.BufferedReader; import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; +import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; +import java.util.logging.Logger; -public class CSHttpConnection implements IURLRequestHTTP{ +import static com.contentstack.sdk.Constants.*; +public class CSHttpConnection implements IURLRequestHTTP { + + private final Logger logger = Logger.getLogger(CSHttpConnection.class.getName()); private final String urlPath; + private final IRequestModelHTTP connectionRequest; private String controller; private LinkedHashMap headers; private String info; - private JSONObject requestJSON; - private final IRequestModelHTTP connectionRequest; + private String endpoint; private ResultCallBack callBackObject; - private CSAppConstants.RequestMethod requestMethod; private JSONObject responseJSON; - - public HashMap getFormParams() { - return formParams; - } - public void setFormParams(HashMap formParams) { - this.formParams = formParams; - } private HashMap formParams; - private boolean treatDuplicateKeysAsArrayItems; + private final String utfType = String.valueOf(StandardCharsets.UTF_8); public CSHttpConnection(String urlToCall, IRequestModelHTTP csConnectionRequest) { this.urlPath = urlToCall; this.connectionRequest = csConnectionRequest; } - @Override - public void setController(String controller) { - this.controller = controller; + public void setFormParams(HashMap formParams) { + this.formParams = formParams; } @Override @@ -54,18 +49,18 @@ public String getController() { } @Override - public void setHeaders(LinkedHashMap headers) { - this.headers = headers; + public void setController(String controller) { + this.controller = controller; } @Override - public LinkedHashMap getHeaders() { - return headers; + public void setHeaders(LinkedHashMap headers) { + this.headers = headers; } @Override - public void setInfo(String info) { - this.info = info; + public LinkedHashMap getHeaders() { + return this.headers; } @Override @@ -73,14 +68,9 @@ public String getInfo() { return info; } - public void setFormParamsPOST(JSONObject requestJSON) { - this.requestJSON = null; - this.requestJSON = requestJSON; - } - @Override - public void setCallBackObject(ResultCallBack callBackObject) { - this.callBackObject = callBackObject; + public void setInfo(String info) { + this.info = info; } @Override @@ -89,23 +79,8 @@ public ResultCallBack getCallBackObject() { } @Override - public void setTreatDuplicateKeysAsArrayItems(boolean treatDuplicateKeysAsArrayItems) { - this.treatDuplicateKeysAsArrayItems = treatDuplicateKeysAsArrayItems; - } - - @Override - public boolean getTreatDuplicateKeysAsArrayItems() { - return treatDuplicateKeysAsArrayItems; - } - - @Override - public void setRequestMethod(CSAppConstants.RequestMethod requestMethod) { - this.requestMethod = requestMethod; - } - - @Override - public CSAppConstants.RequestMethod getRequestMethod() { - return requestMethod; + public void setCallBackObject(ResultCallBack callBackObject) { + this.callBackObject = callBackObject; } @Override @@ -113,11 +88,12 @@ public JSONObject getResponse() { return responseJSON; } - public String setFormParamsGET(HashMap params){ - if(params != null && params.size() > 0){ + 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; - if(urlParams==null) { + urlParams = info.equalsIgnoreCase(Constants.REQUEST_CONTROLLER.QUERY.name()) + || info.equalsIgnoreCase(Constants.REQUEST_CONTROLLER.ENTRY.name()) ? getParams(params) : null; + if (urlParams == null) { for (Map.Entry e : params.entrySet()) { if (urlParams == null) { urlParams = "?" + e.getKey() + "=" + e.getValue(); @@ -131,148 +107,110 @@ public String setFormParamsGET(HashMap params){ return null; } - - private String getParams(HashMap params) { String urlParams = "?"; for (Map.Entry e : params.entrySet()) { - String key = e.getKey(); + String key = e.getKey(); Object value = e.getValue(); try { - if (key.equalsIgnoreCase("include[]")) { - key = URLEncoder.encode(key, "UTF-8"); - JSONArray array = (JSONArray) value; - for (int i = 0; i < array.length(); i++) { - urlParams += urlParams.equals("?") ? key + "=" + array.opt(i) : "&" + key + "=" + array.opt(i); - } - } else if(key.equalsIgnoreCase("only[BASE][]")){ - key = URLEncoder.encode(key, "UTF-8"); - JSONArray array = (JSONArray) value; - for (int i = 0; i < array.length(); i++) { - urlParams += urlParams.equals("?") ? key + "=" + array.opt(i) : "&" + key + "=" + array.opt(i); - } - } else if(key.equalsIgnoreCase("except[BASE][]")){ - key = URLEncoder.encode(key, "UTF-8"); - JSONArray array = (JSONArray) value; - for (int i = 0; i < array.length(); i++) { - urlParams += urlParams.equals("?") ? key + "=" + array.opt(i) : "&" + key + "=" + array.opt(i); - } - } else if(key.equalsIgnoreCase("only")){ + if (key.equalsIgnoreCase("include[]") || key.equalsIgnoreCase("only[BASE][]") + || key.equalsIgnoreCase("except[BASE][]")) { + urlParams = convertUrlParam(urlParams, value, key); + } else if (key.equalsIgnoreCase("only")) { JSONObject onlyJSON = (JSONObject) value; - Iterator iter = onlyJSON.keys(); - while (iter.hasNext()) { - String innerKey = iter.next(); + Iterator itrString = onlyJSON.keys(); + while (itrString.hasNext()) { + String innerKey = itrString.next(); JSONArray array = onlyJSON.optJSONArray(innerKey); - innerKey = URLEncoder.encode("only["+innerKey+"][]", "UTF-8"); + innerKey = URLEncoder.encode("only[" + innerKey + "][]", utfType); for (int i = 0; i < array.length(); i++) { - urlParams += urlParams.equals("?") ? innerKey + "=" + array.opt(i) : "&" + innerKey + "=" + array.opt(i); + urlParams += urlParams.equals("?") ? innerKey + "=" + array.opt(i) + : "&" + innerKey + "=" + array.opt(i); } } - } else if(key.equalsIgnoreCase("except")){ + } else if (key.equalsIgnoreCase("except")) { JSONObject onlyJSON = (JSONObject) value; Iterator iter = onlyJSON.keys(); while (iter.hasNext()) { String innerKey = iter.next(); JSONArray array = onlyJSON.optJSONArray(innerKey); - innerKey = URLEncoder.encode("except["+innerKey+"][]", "UTF-8"); + innerKey = URLEncoder.encode("except[" + innerKey + "][]", utfType); for (int i = 0; i < array.length(); i++) { - urlParams += urlParams.equals("?") ? innerKey + "=" + array.opt(i) : "&" + innerKey + "=" + array.opt(i); + urlParams += urlParams.equals("?") ? innerKey + "=" + array.opt(i) + : "&" + innerKey + "=" + array.opt(i); } } - } else if(key.equalsIgnoreCase("query")){ - JSONObject queryJSON = (JSONObject) value; - urlParams += urlParams.equals("?") ? key + "=" + URLEncoder.encode(queryJSON.toString(), "UTF-8") : "&" + key + "=" + URLEncoder.encode(queryJSON.toString(), "UTF-8"); - }else{ + } else if (key.equalsIgnoreCase("query")) { + JSONObject queryJSON = (JSONObject) value; + urlParams += urlParams.equals("?") ? key + "=" + URLEncoder.encode(queryJSON.toString(), utfType) + : "&" + key + "=" + URLEncoder.encode(queryJSON.toString(), utfType); + } else { urlParams += urlParams.equals("?") ? key + "=" + value : "&" + key + "=" + value; } - }catch (Exception e1){ + } catch (Exception e1) { e1.printStackTrace(); } } return urlParams; } - - + private String convertUrlParam(String urlParams, Object value, String key) throws UnsupportedEncodingException { + key = URLEncoder.encode(key, utfType); + JSONArray array = (JSONArray) value; + for (int i = 0; i < array.length(); i++) { + urlParams += urlParams.equals("?") ? key + "=" + array.opt(i) : "&" + key + "=" + array.opt(i); + } + return urlParams; + } @Override public void send() { - String url = null; - if(requestMethod == CSAppConstants.RequestMethod.GET){ - String params = setFormParamsGET(formParams); - if( params != null) { - url = urlPath + params; - } - else { - url = urlPath; - } - }else{ + String url = ""; + String params = setFormParamsGET(formParams); + if (params != null) { + url = urlPath + params; + } else { url = urlPath; } + try { - sendGET(url); + getService(url); } catch (IOException | JSONException e) { e.printStackTrace(); } } - - - - private void sendGET(String GET_URL) throws IOException, JSONException { - URL obj = new URL(GET_URL); - HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); - conn.setRequestMethod("GET"); - if (this.headers.containsKey("api_key")){ - conn.setRequestProperty("api_key", headers.get("api_key").toString()); - } - if (this.headers.containsKey("access_token")){ - conn.setRequestProperty("access_token", headers.get("access_token").toString()); - } - if (this.headers.containsKey("environment")){ - conn.setRequestProperty("environment", headers.get("environment").toString()); - } - conn.setRequestProperty("X-User-Agent", defaultUserAgent()+"/"+ CSAppConstants.SDK_VERSION); - conn.setRequestProperty("Content-Type", "application/json"); - int responseCode = conn.getResponseCode(); - if (responseCode == HttpURLConnection.HTTP_OK) { // success - BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); - String inputLine; - StringBuilder response = new StringBuilder(); - while ((inputLine = in.readLine()) != null) { - StringBuilder append = response.append(inputLine); - } - in.close(); - responseJSON = new JSONObject(response.toString()); + private void getService(String requestUrl) throws IOException { + Retrofit retrofit = new Retrofit.Builder().baseUrl(this.endpoint).build(); + APIService service = retrofit.create(APIService.class); + this.headers.remove(Constants.ENVIRONMENT); + this.headers.put(X_USER_AGENT, CLIENT_USER_AGENT); + this.headers.put(CONTENT_TYPE, APPLICATION_JSON); + Response response = service.getRequest(requestUrl, this.headers).execute(); + if (response.isSuccessful()) { + assert response.body() != null; + String resp = response.body().string(); + responseJSON = new JSONObject(resp); connectionRequest.onRequestFinished(CSHttpConnection.this); } else { - // Setting up error details, like error_message, error_code, error_details - settingErrorInfo(conn); + assert response.errorBody() != null; + setError(response.errorBody().string()); } } - private void settingErrorInfo(HttpURLConnection con) throws IOException { - BufferedReader in = new BufferedReader(new InputStreamReader(con.getErrorStream(), StandardCharsets.UTF_8)); - String inputLine; - StringBuilder response = new StringBuilder(); - while ((inputLine = in.readLine()) != null) { response.append(inputLine); } - in.close(); - responseJSON = new JSONObject(response.toString()); - String errorMsg = responseJSON.optString("error_message"); - String errorCode = responseJSON.optString("error_code"); - String errorDetails = responseJSON.optString("errors"); - responseJSON.put("error_message", errorMsg); - responseJSON.put("error_code", errorCode); - responseJSON.put("errors", errorDetails); - int errorCodeInt = Integer.parseInt(errorCode); - connectionRequest.onRequestFailed(responseJSON, errorCodeInt, callBackObject); + void setError(String errResp) { + logger.info(errResp); + responseJSON = new JSONObject(errResp); // Parse error string to JSONObject + responseJSON.put(ERROR_MESSAGE, responseJSON.optString(ERROR_MESSAGE)); + responseJSON.put(ERROR_CODE, responseJSON.optString(ERROR_CODE)); + responseJSON.put(ERRORS, responseJSON.optString(ERRORS)); + int errCode = Integer.parseInt(responseJSON.optString(ERROR_CODE)); + connectionRequest.onRequestFailed(responseJSON, errCode, callBackObject); } - private String defaultUserAgent() { - String agent = System.getProperty("http.agent"); - return agent != null ? agent : ("Java" + System.getProperty("java.version")); + protected void setEndpoint(@NotNull String endpoint) { + this.endpoint = endpoint; } - } \ No newline at end of file diff --git a/src/main/java/com/contentstack/sdk/Config.java b/src/main/java/com/contentstack/sdk/Config.java index cfe6fdfc..d619d6be 100644 --- a/src/main/java/com/contentstack/sdk/Config.java +++ b/src/main/java/com/contentstack/sdk/Config.java @@ -1,147 +1,128 @@ package com.contentstack.sdk; +import org.jetbrains.annotations.NotNull; + /** - Configuration Support for contentstack + * The type Config. enables optional parameters while passing from stack */ - public class Config { - protected String URLSCHEMA = "https://"; - protected String URL = "cdn.contentstack.io"; - protected String VERSION = "v3"; - protected String environment = null; + protected String livePreviewHash = null; + protected String livePreviewContentType = null; + protected String host = "cdn.contentstack.io"; + protected String version = "v3"; + protected String scheme = "https://"; + protected String endpoint; + protected boolean enableLivePreview = false; + protected String livePreviewHost; protected ContentstackRegion region = ContentstackRegion.US; + protected String managementToken; + protected String branch; - public enum ContentstackRegion { US, EU } + public String getBranch() { + return branch; + } - public ContentstackRegion getRegion() { return this.region; } + public void setBranch(String branch) { + this.branch = branch; + } /** - * Sets region allow you to set your region for the Contentstack server. - * @param region type {@link ContentstackRegion} - * @return ContentstackRegion + * Gets region. * - *

- * Note: - * Default region sets to us - * - *

Example :
- *

-     * config.setRegion(ContentstackRegion.US);
-     * 
- + * @return the region */ + public ContentstackRegion getRegion() { + return this.region; + } + /** + * Sets region. + * + * @param region the region + * @return the region + */ public ContentstackRegion setRegion(ContentstackRegion region) { this.region = region; return this.region; } + protected String getEndpoint() { + return endpoint + "/" + getVersion() + "/"; + } + protected String setEndpoint(@NotNull String endpoint) { + this.endpoint = endpoint; + return this.endpoint; + } /** - * Config constructor + * Gets host. * - *

Example :
- *
-     * Config config = new Config();
-     * 
+ * @return the host */ - - public Config(){} + public String getHost() { + return host; + } /** - * Sets host name of the Contentstack server. - * - * @param hostName - * host name. + * Sets host. * - *

- * Note: Default hostname sets to cdn.contentstack.io - * and default protocol is HTTPS. - *

Example :
- *

-     * config.setHost("cdn.contentstack.io");
-     * 
+ * @param hostName the host name */ - - public void setHost(String hostName){ - if(hostName != null && !hostName.isEmpty()) { - URL = hostName; + public void setHost(String hostName) { + if (hostName != null && !hostName.isEmpty()) { + host = hostName; } } - - /** + * Gets version. * - * @return URL String - *

Example :
- *
-     * String url = config.getHost();
-     * 
+ * @return the version */ - public String getHost(){ - return URL; + public String getVersion() { + return version; } - /** - * Get version of the Contentstack server. - * @return VERSION String - *

Example :
- *
-     * String version = config.getVersion();
-     * 
+ * Enable live preview config. + * + * @param enableLivePreview to enable live preview + * @return the config */ - public String getVersion(){ - return VERSION; + public Config enableLivePreview(boolean enableLivePreview) { + this.enableLivePreview = enableLivePreview; + return this; } /** - * Changes the Contentstack version to be used in the final URL. + * Sets live preview host. * - * @param version version string. - * - *

Example :
- *
-     *      config.setVersion("v3");
-     * 
+ * @param livePreviewHost the live preview host + * @return the live preview host */ - private void setVersion(String version){ - if(version != null && !version.isEmpty()) { - VERSION = version; - } + public Config setLivePreviewHost(@NotNull String livePreviewHost) { + this.livePreviewHost = livePreviewHost; + return this; } /** - * set environment. - * - * @param environment uid/name + * Sets management token. * - *

Example :
- *
-     *  config.setEnvironment("stag", false);
-     * 
+ * @param managementToken the management token + * @return the management token */ - protected void setEnvironment(String environment){ - if(environment != null && !environment.isEmpty()) { - this.environment = environment; - } - + public Config setManagementToken(@NotNull String managementToken) { + this.managementToken = managementToken; + return this; } /** - * Get environment. - * @return param environment string - *

Example :
- *
-     *  String environment = config.getEnvironment();
-     * 
+ * The enum Contentstack region. */ - public String getEnvironment(){ - return environment; + public enum ContentstackRegion { + US, EU } } - diff --git a/src/main/java/com/contentstack/sdk/Constants.java b/src/main/java/com/contentstack/sdk/Constants.java new file mode 100644 index 00000000..0c3f69cf --- /dev/null +++ b/src/main/java/com/contentstack/sdk/Constants.java @@ -0,0 +1,134 @@ +package com.contentstack.sdk; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; +import java.util.logging.Logger; + +/** + * The type Constants. + */ +public class Constants { + + private static final Logger logger = Logger.getLogger(Constants.class.getSimpleName()); + protected static final String SDK_VERSION = "1.8.0"; + protected static final String ENVIRONMENT = "environment"; + protected static final String CONTENT_TYPE_UID = "content_type_uid"; + protected static final String SYNCHRONISATION = "stacks/sync"; + // Errors + protected static final String ERROR_CODE = "error_code"; + protected static final String ERROR_MESSAGE = "error_message"; + protected static final String ERRORS = "errors"; + // User-Agents + protected static final String X_USER_AGENT = "X-User-Agent"; + protected static final String CONTENT_TYPE = "Content-Type"; + protected static final String APPLICATION_JSON = "application/json"; + protected static final String CLIENT_USER_AGENT = userAgent(); + // Query + protected static final String QUERY = "query"; + protected static final String EXCEPT = "except"; + protected static final String EXISTS = "$exists"; + protected static final String REGEX = "$regex"; + protected static final String LIMIT = "limit"; + protected static final String OPTIONS = "$options"; + + + + protected Constants() { + logger.warning("Not Allowed"); + } + + /** + * The enum Request controller. + */ + // REQUEST_CONTROLLER + public enum REQUEST_CONTROLLER { + QUERY, ENTRY, ASSET, SYNC, CONTENTTYPES, ASSETLIBRARY + } + + // GET REQUEST TYPE + 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"; + + // ERROR MESSAGE BLOCK + public static final String JSON_NOT_PROPER = "Please provide valid JSON."; + public static final String CONTENT_TYPE_NAME = "Please set contentType name."; + public static final String HEADER_IS_MISSING_TO_PROCESS_THE_DATA = "Header is missing to process the data"; + public static final String QUERY_EXCEPTION = "Please provide valid params."; + + /** + * Parse date calendar. + * + * @param date the date + * @param timeZone the time zone + * @return the calendar + */ + 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'"); + knownPatterns.add("yyyy-MM-dd'T'HH:mmZ"); + knownPatterns.add("yyyy-MM-dd'T'HH:mm'Z'"); + knownPatterns.add("yyyy-MM-dd'T'HH:mm'Z'"); + knownPatterns.add("yyyy-MM-dd'T'HH:mm:ss"); + knownPatterns.add("yyyy-MM-dd' 'HH:mm:ss"); + knownPatterns.add("yyyy-MM-dd"); + knownPatterns.add("HH:mm:ssZ"); + knownPatterns.add("HH:mm:ss'Z'"); + + for (String formatString : knownPatterns) { + try { + return parseDate(date, formatString, timeZone); + } catch (ParseException e) { + logger.warning(e.getLocalizedMessage()); + } + } + return null; + } + + /** + * Parse date calendar. + * + * @param date the date + * @param dateFormat the date format + * @param timeZone the time zone + * @return the calendar + * @throws ParseException the parse exception + */ + public static Calendar parseDate(String date, String dateFormat, TimeZone timeZone) throws ParseException { + Calendar cal = Calendar.getInstance(); + SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormat); + Date dateObject = dateFormatter.parse(date); + String month = new SimpleDateFormat("MM").format(dateObject); + String day = new SimpleDateFormat("dd").format(dateObject); + String year = new SimpleDateFormat("yyyy").format(dateObject); + String hourOfDay = new SimpleDateFormat("HH").format(dateObject); + String min = new SimpleDateFormat("mm").format(dateObject); + String sec = new SimpleDateFormat("ss").format(dateObject); + + if (timeZone != null) { + cal.setTimeZone(timeZone); + } else { + cal.setTimeZone(TimeZone.getDefault()); + } + cal.set(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day), Integer.parseInt(hourOfDay), + Integer.parseInt(min), Integer.parseInt(sec)); + return cal; + } + + protected static String userAgent() { + String agent = System.getProperty("http.agent"); + String agentStr = agent != null ? agent : ("Java" + System.getProperty("java.version")); + agentStr = agentStr + "/" + SDK_VERSION; + return agentStr; + } +} diff --git a/src/main/java/com/contentstack/sdk/ContentType.java b/src/main/java/com/contentstack/sdk/ContentType.java index fd1140d4..8188145d 100644 --- a/src/main/java/com/contentstack/sdk/ContentType.java +++ b/src/main/java/com/contentstack/sdk/ContentType.java @@ -1,282 +1,158 @@ package com.contentstack.sdk; -import com.contentstack.sdk.utility.CSAppConstants; -import com.contentstack.sdk.utility.CSController; + +import org.jetbrains.annotations.NotNull; import org.json.JSONObject; + import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; -import java.util.Map; import java.util.logging.Logger; /** - * - * A Content Type is the structure or blueprint of a page or a section that your web or mobile - * property will display. It lets you define the overall schema of this blueprint by adding fields - * and setting its properties. + * The type Content type. */ - public class ContentType { - private static final Logger logger = Logger.getLogger(ContentType.class.getSimpleName()); - protected String contentTypeName = null; + private final Logger logger = Logger.getLogger(ContentType.class.getSimpleName()); + protected String contentTypeUid = null; protected Stack stackInstance = null; - private LinkedHashMap localHeader = null; - private LinkedHashMap stackHeader = null; + protected LinkedHashMap headers = null; - private ContentType(){} + protected ContentType() throws IllegalAccessException { + throw new IllegalAccessException("Can Not Access Private Modifier"); + } - protected ContentType(String contentTypeName) { - this.contentTypeName = contentTypeName; - this.localHeader = new LinkedHashMap<>(); + protected ContentType(String contentTypeUid) { + this.contentTypeUid = contentTypeUid; } - protected void setStackInstance(Stack stack){ + protected void setStackInstance(Stack stack) { this.stackInstance = stack; - this.stackHeader = stack.localHeader; + this.headers = stack.headers; } - /** - * To set headers for Built.io Contentstack rest calls. - *
- * Scope is limited to this object and followed classes. - * @param key - * header name. - * @param value - * header value against given header name. - *

Example :
- *
-     * //'blt5d4sample2633b' is a dummy Stack API key
-     * //'blt6d0240b5sample254090d' is dummy access token.
-     * Stack stack = Contentstack.stack("blt5d4sample2633b", "blt6d0240b5sample254090d", "stag", false);
-     * ContentType contentType = stack.contentType("form_name");
- * contentType.setHeader("custom_key", "custom_value"); - *
+ * Sets header on {@link Stack}. + * + * @param headerKey the header key + * @param headerValue the header value */ - - public void setHeader(String key, String value){ - if(!key.isEmpty() && !value.isEmpty()){ - localHeader.put(key, value); + public void setHeader(String headerKey, String headerValue) { + if (!headerKey.isEmpty() && !headerValue.isEmpty()) { + this.headers.put(headerKey, headerValue); } } - /** - * Remove header key. - * @param key - * custom_header_key - *

Example :
- *
-     * //'blt5d4sample2633b' is a dummy Stack API key
-     * //'blt6d0240b5sample254090d' is dummy access token.
-     *  Stack stack = Contentstack.stack( "blt5d4sample2633b", "blt6d0240b5sample254090d", "stag", false);
-     *  ContentType contentType = stack.contentType("form_name");
- * contentType.removeHeader("custom_header_key"); - *
+ * Remove header from {@link Stack} + * + * @param headerKey the header key */ - - public void removeHeader(String key){ - if(!key.isEmpty()){ - localHeader.remove(key); + public void removeHeader(String headerKey) { + if (!headerKey.isEmpty()) { + this.headers.remove(headerKey); } } - - /** - * Represents a {@link Entry}. - * Create {@link Entry} instance - * @param entryUid - * Set entry uid. - * @return - * {@link Entry} instance. - *

Example :
- *
-     *  //'blt5d4sample2633b' is a dummy Stack API key
-     *  //'blt6d0240b5sample254090d' is dummy access token.
-     *  Stack stack = Contentstack.stack( "blt5d4sample2633b", "blt6d0240b5sample254090d", "stag", false);
-     *  ContentType contentType = stack.contentType("form_name");
- * // setUid will identify the object, and calling save will update it - * ENTRY entry = contentType.entry("bltf4fbbc94e8c851db"); - *
+ * An entry is the actual piece of content created using one of the defined + * content types. + *

+ * The Get a single entry request fetches a particular entry of a content type. + * + * @param entryUid the entry unique ID of the entry that you want to fetch. + * @return the {@link Entry} entry. */ public Entry entry(String entryUid) { - Entry entry = new Entry(contentTypeName); - entry.formHeader = getHeader(localHeader); - entry.setContentTypeInstance(this); + Entry entry = new Entry(contentTypeUid); + entry.setContentType(this, this.headers); entry.setUid(entryUid); - return entry; } - - - protected Entry entry(){ - Entry entry = new Entry(contentTypeName); - entry.formHeader = getHeader(localHeader); - entry.setContentTypeInstance(this); - + protected Entry entry() { + Entry entry = new Entry(contentTypeUid); + entry.headers = this.headers; + entry.setContentType(this, this.headers); return entry; } - - /** - * Represents a {@link Query}. - * Create {@link Query} instance. - * @return - * {@link Query} instance. - *

Example :
- *

-     *  //'blt5d4sample2633b' is a dummy Stack API key
-     *  //'blt6d0240b5sample254090d' is dummy access token.
-     *  Stack stack = Contentstack.stack("blt5d4sample2633b", "blt6d0240b5sample254090d", "stag", false);
-     *  ContentType contentType = stack.contentType("form_name");
- * Query csQuery = contentType.query(); - *
+ * Query. The Get all entries request fetches the list of all the entries of a + * particular content type. It returns the content of each entry in JSON format. + * You need to specify the environment and locale of which you want to get the + * entries. + * + *

+ * If an entry is not published in a specific locale, make use of the + * include_fallback=true query parameter to fetch the published content + * from its fallback locale. + *

+ * Note:If the fallback language of the specified locale is the master + * language itself, this parameter would not be applicable. + * + *

+ * To include the publishing details in the response, make use of the + * include_publish_details=true parameter. This will return the publishing + * details of the entry in every environment along with the version number that + * is published in each of the environments. You can add other Queries to extend + * the functionality of this API call. Add a query parameter named query and + * provide your query (in JSON format) as the value. + * + * @return the {@link Query} */ - - public Query query(){ - Query query = new Query(contentTypeName); - query.formHeader = getHeader(localHeader); + public Query query() { + Query query = new Query(contentTypeUid); + query.headers = this.headers; query.setContentTypeInstance(this); return query; } - - - /** + * Fetch. * - * This call returns information of a specific content type. It returns the content type schema, but does not include its entries. - * @param params query parameters - * @param callback {@link ContentTypesCallback} - *

Example :
- *

-     * ContentType  contentType = stack.contentType("content_type_uid");
-     * JSONObject params = new JSONObject();
-     * params.put("include_snippet_schema", true);
-     * params.put("limit", 3);
-     * contentType.fetch(params, new ContentTypesCallback() {
-     *
-     * public void onCompletion(ContentTypesModel contentTypesModel, Error error) {
-     * if (error==null){
-     *
-     * }else {
-     *
-     * }
-     * }
-     * });
-     *
+ * @param params the params + * @param callback the callback */ - - - public void fetch(JSONObject params, final ContentTypesCallback callback) { - - try { - - String URL = "/" + stackInstance.VERSION + "/content_types/"+contentTypeName; - HashMap 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, callback ); - }else { - Error error = new Error(); - error.setErrorMessage(CSAppConstants.ErrorMessage_JsonNotProper); - callback.onRequestFail(ResponseType.UNKNOWN, error); + public void fetch(@NotNull JSONObject params, final ContentTypesCallback callback) { + String urlString = "content_types/" + contentTypeUid; + Iterator keys = params.keys(); + while (keys.hasNext()) { + String key = keys.next(); + Object value = params.opt(key); + params.put(key, value); + } + params.put("environment", headers.get("environment")); + if (contentTypeUid != null && !contentTypeUid.isEmpty()) { + try { + throw new IllegalAccessException("contentTypeUid is required"); + } catch (Exception e) { + logger.warning("contentTypeUid is required"); } - - - }catch (Exception e){ - - Error error = new Error(); - error.setErrorMessage(CSAppConstants.ErrorMessage_JsonNotProper); - callback.onRequestFail(ResponseType.UNKNOWN, error); } - + fetchContentTypes(urlString, params, headers, callback); } - - - private void fetchContentTypes(String urlString, JSONObject content_type_param, HashMap headers, ContentTypesCallback callback) { - - if(callback != null) { - - HashMap urlParams = getUrlParams(content_type_param); - new CSBackgroundTask(this, stackInstance, CSController.FETCHCONTENTTYPES, urlString, headers, urlParams, new JSONObject(), CSAppConstants.callController.CONTENTTYPES.toString(), false, CSAppConstants.RequestMethod.GET, callback); + private void fetchContentTypes(String urlString, JSONObject params, HashMap headers, + ContentTypesCallback callback) { + if (callback != null) { + HashMap urlParams = getUrlParams(params); + new CSBackgroundTask(this, stackInstance, Constants.FETCHCONTENTTYPES, urlString, headers, urlParams, + Constants.REQUEST_CONTROLLER.CONTENTTYPES.toString(), callback); } } - - - /** - * - */ - private LinkedHashMap getHeader(LinkedHashMap localHeader) { - LinkedHashMap mainHeader = stackHeader; - LinkedHashMap classHeaders = new LinkedHashMap<>(); - - 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; - } - } - - - 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) { - logger.severe(e.getLocalizedMessage()); - } + if (urlQueriesJSON != null && urlQueriesJSON.length() > 0) { + Iterator itStr = urlQueriesJSON.keys(); + while (itStr.hasNext()) { + String key = itStr.next(); + Object value = urlQueriesJSON.opt(key); + hashMap.put(key, value); } - - return hashMap; } - - return null; + return hashMap; } } - diff --git a/src/main/java/com/contentstack/sdk/ContentTypesCallback.java b/src/main/java/com/contentstack/sdk/ContentTypesCallback.java index d831bcaa..ebd294c6 100755 --- a/src/main/java/com/contentstack/sdk/ContentTypesCallback.java +++ b/src/main/java/com/contentstack/sdk/ContentTypesCallback.java @@ -1,21 +1,15 @@ package com.contentstack.sdk; -public abstract class ContentTypesCallback extends ResultCallBack { +public abstract class ContentTypesCallback implements ResultCallBack { - public abstract void onCompletion(ContentTypesModel contentTypesModel, Error error); + public abstract void onCompletion(ContentTypesModel contentTypesModel, Error error); - void onRequestFinish(ContentTypesModel contentTypesModel){ - onCompletion(contentTypesModel, null); - } - - @Override - void onRequestFail(ResponseType responseType, Error error) { - onCompletion(null, error); - } - - @Override - public void always() { - - } + void onRequestFinish(ContentTypesModel contentTypesModel) { + onCompletion(contentTypesModel, null); + } + @Override + public void onRequestFail(ResponseType responseType, Error error) { + onCompletion(null, error); + } } diff --git a/src/main/java/com/contentstack/sdk/ContentTypesModel.java b/src/main/java/com/contentstack/sdk/ContentTypesModel.java index 2373818e..5df5d336 100644 --- a/src/main/java/com/contentstack/sdk/ContentTypesModel.java +++ b/src/main/java/com/contentstack/sdk/ContentTypesModel.java @@ -1,40 +1,30 @@ package com.contentstack.sdk; + import org.json.JSONArray; -import org.json.JSONException; import org.json.JSONObject; -import java.util.logging.Logger; - public class ContentTypesModel { - private static final Logger logger = Logger.getLogger(ContentTypesModel.class.getSimpleName()); - private JSONObject responseJSON = new JSONObject(); + private Object response; private JSONArray responseJSONArray = new JSONArray(); public void setJSON(JSONObject responseJSON) { - if (responseJSON!=null){ - if (responseJSON.has("content_type")){ - try { - this.responseJSON = responseJSON.getJSONObject("content_type"); - } catch (JSONException e) { - logger.severe(e.getLocalizedMessage()); - } + if (responseJSON != null) { + String ctKey = "content_type"; + if (responseJSON.has(ctKey) && responseJSON.opt(ctKey) instanceof JSONObject) { + this.response = responseJSON.optJSONObject(ctKey); } - - if (responseJSON.has("content_types")){ - try { - this.responseJSONArray = responseJSON.getJSONArray("content_types"); - } catch (JSONException e) { - logger.severe(e.getLocalizedMessage()); - } + String ctListKey = "content_types"; + if (responseJSON.has(ctListKey) && responseJSON.opt(ctListKey) instanceof JSONArray) { + this.response = responseJSON.optJSONArray(ctListKey); + this.responseJSONArray = (JSONArray) this.response; } - } } - public JSONObject getResponse() { - return responseJSON; + public Object getResponse() { + return this.response; } public JSONArray getResultArray() { diff --git a/src/main/java/com/contentstack/sdk/Contentstack.java b/src/main/java/com/contentstack/sdk/Contentstack.java index 6f5375f4..443cec45 100644 --- a/src/main/java/com/contentstack/sdk/Contentstack.java +++ b/src/main/java/com/contentstack/sdk/Contentstack.java @@ -1,143 +1,106 @@ package com.contentstack.sdk; -import com.contentstack.sdk.utility.CSAppConstants; + +import java.util.Objects; /** - Contentstack class that exposes Stack instance + * The Content Delivery API is used to retrieve content from your Contentstack + * account and deliver it to your web or mobile properties. If you are looking + * for APIs to manage content, you should use the Content Management API + *

+ * Our APIs serve content via a powerful and robust content delivery network + * (CDN). Multiple datacenters around the world store a cached copy of your + * content. When a page request is made, the content is delivered to the user + * from the nearest server. This greatly accelerates content delivery and + * reduces latency. */ - public class Contentstack { - - private Contentstack(){ } - - - /** - * 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 stackApiKey - * application api Key of your application on Contentstack. - * @param accessToken - * access token - * @param environment - * environment name - * @return - * {@link Stack} instance. - * @throws Exception - *

Example :
- *

-     * Stack stack = Contentstack.stack("blt5d4sample2633b", "blt6d0240b5sample254090d", "stag");
-     * 
- */ - - public static Stack stack( String stackApiKey, String accessToken, String environment) throws Exception{ - - if(!stackApiKey.isEmpty()) { - if(!accessToken.isEmpty()) { - if(!environment.isEmpty()) { - Config config = new Config(); - config.setEnvironment(environment); - //Configurator.initialize(new DefaultConfiguration()); - return initializeStack(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); - } - + // Modifier Protected + protected Contentstack() throws IllegalAccessException { + throw new IllegalAccessException("Can Not Access Private Modifier"); } - - /** + * A stack is a space that stores the content of a project (a web or mobile + * property). Within a stack, you can create content structures, content + * entries, users, etc. related to the project.
+ * Authenticates the stack api key of your stack.
+ * Find Your Stack Credentials from Contentstack . + * + * @param stackApiKey The API Key is a unique key assigned to each stack. + * @param deliveryToken The Delivery Token is a read-only credential that you + * can create for different environments of your stack + * @param environment the environment for the stack + * @return the stack + * @throws IllegalAccessException the illegal access exception * - * 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 stackApiKey - * application api Key of your application on Contentstack. - * @param accessToken - * access token - * @param environment - * environment name - * @param config - * {@link Config} instance to set environment and other configuration details. - * @return - * {@link Stack} instance. - * @throws Exception - *

Example :
- *
-     * Stack stack = Contentstack.stack("blt5d4sample2633b", "blt6d0240b5sample254090d", "stag");
-     * 
+ * Example + * + *
+     *                                {
+     *                                    @Code
+     *                                    Stack stack = contentstack.Stack("apiKey", "deliveryToken", "environment");
+     *                                }
+     *
+     *                                
*/ - - public static Stack stack(String stackApiKey, String accessToken, String environment, Config config) throws Exception{ - - if(!stackApiKey.isEmpty()) { - if(!accessToken.isEmpty()) { - if(!environment.isEmpty()) { - if(config != null){ - config.setEnvironment(environment); - }else { - config = new Config(); - config.setEnvironment(environment); - } - //Configurator.initialize(new DefaultConfiguration()); - return initializeStack(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(String stackApiKey, String deliveryToken, String environment) + throws IllegalAccessException { + validateCredentials(stackApiKey, deliveryToken, environment); + Config config = new Config(); + return initializeStack(stackApiKey, deliveryToken, environment, config); } - - - /** + * A stack is a space that stores the content of a project (a web or mobile + * property). Within a stack, you can create content structures, content + * entries, users, etc. related to the project. * - * Initialise the stack api key of your stack. - * This must be called to initialise Contentstack sdk. - *
- * You can find your stack api key from web. - * @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. - * @throws Exception - *

Example :
- *
-     * //'blt5d4sample2633b' is a dummy Stack API key
-     * //'blt6d0240b5sample254090d' is dummy access token.
-     * Stack stack = Contentstack.stack("blt5d4sample2633b", "blt6d0240b5sample254090d", "stag");
-     * 
+ * @param stackApiKey The API Key is a unique key assigned to each stack. + * @param deliveryToken The Delivery Token is a read-only credential that you + * can create for different environments of your stack + * @param environment the environment for the stack + * @param config the config + * @return the stack + * @throws IllegalAccessException the illegal access exception Example + * + * { @Code Stack stack = + * contentstack.Stack("apiKey", "deliveryToken", + * "environment"); } */ + public static Stack stack(String stackApiKey, String deliveryToken, String environment, Config config) + throws IllegalAccessException { + validateCredentials(stackApiKey, deliveryToken, environment); + return initializeStack(stackApiKey, deliveryToken, environment, config); + } - private static Stack initializeStack(String stackApiKey, String accessToken, Config config){ + private static void validateCredentials(String stackApiKey, String deliveryToken, String environment) + throws IllegalAccessException { + Objects.requireNonNull(stackApiKey, "API Key can not be null"); + Objects.requireNonNull(deliveryToken, "Delivery Token can not be null"); + Objects.requireNonNull(environment, "Environment can not be null"); + + if (stackApiKey.isEmpty()) { + throw new IllegalAccessException("API Key can not be empty"); + } + if (deliveryToken.isEmpty()) { + throw new IllegalAccessException("Delivery Token can not be empty"); + } + if (environment.isEmpty()) { + throw new IllegalAccessException("Environment can not be empty"); + } + } + private static Stack initializeStack(String stackApiKey, String deliveryToken, String environment, Config config) { Stack stack = new Stack(stackApiKey.trim()); stack.setHeader("api_key", stackApiKey); - stack.setHeader("access_token", accessToken); + stack.setHeader("access_token", deliveryToken); + stack.setHeader("environment", environment); + if (config.getBranch() != null && !config.getBranch().isEmpty()) { + stack.setHeader("branch", config.getBranch()); + } stack.setConfig(config); return stack; } - - - - } diff --git a/src/main/java/com/contentstack/sdk/ContentstackResultCallback.java b/src/main/java/com/contentstack/sdk/ContentstackResultCallback.java deleted file mode 100644 index f3993b52..00000000 --- a/src/main/java/com/contentstack/sdk/ContentstackResultCallback.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.contentstack.sdk; - -public abstract class ContentstackResultCallback extends ResultCallBack { - public abstract void onCompletion(ResponseType responseType, Error error); - public void onRequestFinish(ResponseType responseType){ - onCompletion(responseType, null); - } - @Override - void onRequestFail(ResponseType responseType, Error error) { - onCompletion(responseType, error); - } - @Override - public void always() { } -} diff --git a/src/main/java/com/contentstack/sdk/EntriesModel.java b/src/main/java/com/contentstack/sdk/EntriesModel.java index b678dc33..32d39b9e 100644 --- a/src/main/java/com/contentstack/sdk/EntriesModel.java +++ b/src/main/java/com/contentstack/sdk/EntriesModel.java @@ -1,39 +1,36 @@ package com.contentstack.sdk; + import org.json.JSONArray; import org.json.JSONObject; + import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; class EntriesModel { - private static final Logger logger = Logger.getLogger(EntriesModel.class.getSimpleName()); protected JSONObject jsonObject; - protected String formName; protected List objectList; - protected EntriesModel(JSONObject responseJSON, String formName, boolean isFromCache) { + protected EntriesModel(JSONObject responseJSON) { try { - if (isFromCache){ - this.jsonObject = (responseJSON.opt("response") == null ? null : responseJSON.optJSONObject("response")); - }else{ - this.jsonObject = responseJSON; - } - - this.formName = formName; - objectList = new ArrayList<>(); - JSONArray entriesArray = jsonObject.opt("entries") == null ? null : jsonObject.optJSONArray("entries"); - - if(entriesArray != null && entriesArray.length() > 0){ - int count = entriesArray.length(); - for(int i = 0; i < count; i++){ - if(entriesArray.opt(i) != null && entriesArray.opt(i) instanceof JSONObject) { - EntryModel entry = new EntryModel(entriesArray.optJSONObject(i), null, true, isFromCache, false); - objectList.add(entry); - } + this.jsonObject = responseJSON; + objectList = new ArrayList<>(); + Object entryList = jsonObject.opt("entries"); + if (entryList instanceof JSONArray) { + JSONArray entries = (JSONArray) entryList; + if (entries.length() > 0) { + entries.forEach(model -> { + if (model instanceof JSONObject) { + JSONObject newModel = (JSONObject) model; + EntryModel entry = new EntryModel(newModel); + objectList.add(entry); + } + }); } } - }catch (Exception e){ + } catch (Exception e) { + Logger logger = Logger.getLogger(EntriesModel.class.getSimpleName()); logger.severe(e.getLocalizedMessage()); } diff --git a/src/main/java/com/contentstack/sdk/Entry.java b/src/main/java/com/contentstack/sdk/Entry.java index af89e7c8..09af9a33 100644 --- a/src/main/java/com/contentstack/sdk/Entry.java +++ b/src/main/java/com/contentstack/sdk/Entry.java @@ -1,160 +1,146 @@ package com.contentstack.sdk; -import com.contentstack.sdk.utility.CSAppConstants; -import com.contentstack.sdk.utility.CSController; -import com.contentstack.sdk.utility.ContentstackUtil; +import org.jetbrains.annotations.NotNull; import org.json.JSONArray; -import org.json.JSONException; import org.json.JSONObject; import java.util.*; import java.util.logging.Logger; -/** - * An entry is an actual piece of content that you want to publish. - * You can create entries only for content types that have already been created. - */ +import static com.contentstack.sdk.Constants.ENVIRONMENT; public class Entry { - private static final Logger logger = Logger.getLogger(Entry.class.getSimpleName()); - public JSONObject otherPostJSON; - protected LinkedHashMap formHeader = null; + private final Logger logger = Logger.getLogger(Entry.class.getSimpleName()); + protected JSONObject params; + protected LinkedHashMap headers = null; protected HashMap owner = null; - protected HashMap _metadata = null; protected String uid = null; + protected JSONObject publishDetails; protected JSONObject resultJson = null; - protected String ownerEmailId = null; - protected String ownerUid = null; protected String title = null; protected String url = null; protected String language = null; - private String contentTypeName = null; - private LinkedHashMap localHeader = null; - private ContentType contentTypeInstance = null; - private String[] tags = null; - private JSONArray referenceArray; - private JSONArray objectUidForOnly; - private JSONArray objectUidForExcept; - private JSONObject onlyJsonObject; - private JSONObject exceptJsonObject; - private String rteContent = null; - - private Entry() { + protected String contentTypeUid; + protected ContentType contentType = null; + protected String[] tags = null; + protected JSONArray referenceArray; + protected JSONArray objectUidForOnly; + protected JSONArray exceptFieldArray; + protected JSONObject onlyJsonObject; + protected JSONObject exceptJsonObject; + protected String rteContent = null; + + protected Entry() throws IllegalAccessException { + throw new IllegalAccessException("Can Not Access Private Modifier"); } protected Entry(String contentTypeName) { - this.contentTypeName = contentTypeName; - this.localHeader = new LinkedHashMap<>(); - this.otherPostJSON = new JSONObject(); + this.contentTypeUid = contentTypeName; + this.params = new JSONObject(); } - protected void setContentTypeInstance(ContentType contentTypeInstance) { - this.contentTypeInstance = contentTypeInstance; + protected void setContentType(@NotNull ContentType contentType, @NotNull LinkedHashMap header) { + this.contentType = contentType; + this.headers = header; } public Entry configure(JSONObject jsonObject) { - EntryModel model = new EntryModel(jsonObject, null, true, false, false); + EntryModel model = new EntryModel(jsonObject); this.resultJson = model.jsonObject; - this.ownerEmailId = model.ownerEmailId; - this.ownerUid = model.ownerUid; this.title = model.title; this.url = model.url; this.language = model.language; this.rteContent = model.rteContent; - if (model.ownerMap != null) { - this.owner = new HashMap<>(model.ownerMap); - } - if (model._metadata != null) { - this._metadata = new HashMap<>(model._metadata); - } - this.uid = model.entryUid; + this.uid = model.uid; + this.publishDetails = model.publishDetails; this.setTags(model.tags); - model = null; return this; } - /** * Set headers. * * @param key custom_header_key - * @param value custom_header_value - *

Example :
+ * @param value custom_header_value
+ *
+ * Example :
+ * *
-     * //'blt5d4sample2633b' is a dummy Stack API key
-     * //'blt6d0240b5sample254090d' is dummy access token.
-     * Stack stack = Contentstack.stack( "blt5d4sample2633b", "blt6d0240b5sample254090d", "stag", false);
-     * Entry entry = stack.contentType("form_name").entry("entry_uid");
-     * entry.setHeader("custom_header_key", "custom_header_value");
-     * 
+ * Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment"); + * 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 (!key.isEmpty() && !value.isEmpty()) { - localHeader.put(key, value); + this.headers.put(key, value); } } - /** * Remove header key. * - * @param key custom_header_key - *

Example :
+ * @param key custom_header_key
+ *
+ * Example :
+ * *
-     *  //'blt5d4sample2633b' is a dummy Stack API key
-     *  //'blt6d0240b5sample254090d' is dummy access token.
-     *  Stack stack = Contentstack.stack("blt5d4sample2633b", "blt6d0240b5sample254090d", "stag", false);
-     *  Entry entry = stack.contentType("form_name").entry("entry_uid");
-     *  entry.removeHeader("custom_header_key");
-     *  
+ * Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment"); + * Entry entry = stack.contentType("form_name").entry("entry_uid"); + * entry.removeHeader("custom_header_key"); + * */ public void removeHeader(String key) { if (!key.isEmpty()) { - localHeader.remove(key); + this.headers.remove(key); } } /** * Get title string * - * @return String @title - *

Example :
- *
-     * String title = entry.getTitle();
-     * 
+ * @return String @title
+ *
+ * Example :
+ * + *
+     *         String title = entry.getTitle();
+     *         
*/ public String getTitle() { return title; } - /** * Get url string * - * @return String @url - *

Example :
- *
-     * String url = entry.getURL();
-     * 
+ * @return String @url
+ *
+ * Example :
+ * + *
+     *         String url = entry.getURL();
+     *         
*/ public String getURL() { return url; } - /** * Get tags. * - * @return String @tags - *

Example :
- *
-     * String[] tags = entry.getURL();
-     * 
+ * @return String @tags
+ *
+ * Example :
+ * + *
+     *         String[] tags = entry.getURL();
+     *         
*/ public String[] getTags() { @@ -168,25 +154,29 @@ protected void setTags(String[] tags) { /** * Get contentType name. * - * @return String @contentTypeName - *

Example :
- *
-     * String contentType = entry.getFileType();
-     * 
+ * @return String @contentTypeName
+ *
+ * Example :
+ * + *
+     *         String contentType = entry.getFileType();
+     *         
*/ public String getContentType() { - return contentTypeName; + return contentTypeUid; } /** * Get uid. * - * @return String @uid - *

Example :
- *
-     * String uid = entry.getUid();
-     * 
+ * @return String @uid
+ *
+ * Example :
+ * + *
+     *         String uid = entry.getUid();
+     *         
*/ public String getUid() { @@ -197,84 +187,41 @@ protected void setUid(String uid) { this.uid = uid; } - /** - * Get metadata of entry. - *

Example :
- *
-     * HashMap metaData = entry.getMetadata();
-     * 
- */ - private HashMap getMetadata() { - return _metadata; - } - - /** - * Get {@link Language} instance - * - * @return Language @getLanguage - *

Example :
- *
-     * Language local = entry.getLanguage();
-     * 
- */ - @Deprecated - public Language getLanguage() { - String localeCode = null; - - if (_metadata != null && _metadata.size() > 0 && _metadata.containsKey("locale")) { - localeCode = (String) _metadata.get("locale"); - } else if (resultJson.has("locale")) { - localeCode = (String) resultJson.optString("locale"); - } - - if (localeCode != null) { - localeCode = localeCode.replace("-", "_"); - LanguageCode codeValue = LanguageCode.valueOf(localeCode); - int localeValue = codeValue.ordinal(); - Language[] language = Language.values(); - - return language[localeValue]; - } - return null; - } - public String getLocale() { return this.language; } /** * @param locale {@link String} - * @return Entry - *

Example :
- *
-     *   Entry entry = entry.setLanguage();
-     *  
+ * @return Entry
+ *
+ * Example :
+ * + *
+     *         Entry entry = entry.setLanguage();
+     *         
*/ - public Entry setLocale(String locale) { - if (locale != null) { - try { - otherPostJSON.put("locale", locale); - } catch (JSONException e) { - logger.severe(e.getLocalizedMessage()); - } - } - + public Entry setLocale(@NotNull String locale) { + params.put("locale", locale); return this; } - public HashMap getOwner() { + @Deprecated + public Map getOwner() { return owner; } /** * Get entry representation in json * - * @return JSONObject @resultJson - *

Example :
- *
-     * JSONObject json = entry.toJSON();
-     * 
+ * @return JSONObject @resultJson
+ *
+ * Example :
+ * + *
+     *         JSONObject json = entry.toJSON();
+     *         
*/ public JSONObject toJSON() { @@ -284,43 +231,38 @@ public JSONObject toJSON() { /** * Get object value for key. * - * @param key field_uid as key. - *

Example :
+ * @param key field_uid as key.
+ *
+ * Example :
+ * *
-     *                                  Object obj = entry.get("key");
-     *                                  
+ * Object obj = entry.get("key"); + * + * * @return Object @resultJson */ - public Object get(String key) { - try { - if (resultJson != null && key != null) { - return resultJson.get(key); - } else { - return null; - } - } catch (Exception e) { - logger.severe(e.getLocalizedMessage()); - return null; - } + public Object get(@NotNull String key) { + return resultJson.opt(key); } /** * Get string value for key. * - * @param key field_uid as key. - *

Example :
+ * @param key field_uid as key.
+ *
+ * Example :
+ * *
-     *                                  String value = entry.getString("key");
-     *                                  
+ * String value = entry.getString("key"); + * + * * @return String @getString */ - public String getString(String key) { + public String getString(@NotNull String key) { Object value = get(key); - if (value != null) { - if (value instanceof String) { - return (String) value; - } + if (value instanceof String) { + return (String) value; } return null; } @@ -328,20 +270,21 @@ public String getString(String key) { /** * Get boolean value for key. * - * @param key field_uid as key. - *

Example :
+ * @param key field_uid as key.
+ *
+ * Example :
+ * *
-     *                                  Boolean value = entry.getBoolean("key");
-     *                                  
+ * Boolean value = entry.getBoolean("key"); + * + * * @return boolean @getBoolean */ - public Boolean getBoolean(String key) { + public Boolean getBoolean(@NotNull String key) { Object value = get(key); - if (value != null) { - if (value instanceof Boolean) { - return (Boolean) value; - } + if (value instanceof Boolean) { + return (Boolean) value; } return false; } @@ -349,20 +292,21 @@ public Boolean getBoolean(String key) { /** * Get {@link JSONArray} value for key * - * @param key field_uid as key. - *

Example :
+ * @param key field_uid as key.
+ *
+ * Example :
+ * *
-     *                                  JSONArray value = entry.getJSONArray("key");
-     *                                  
+ * JSONArray value = entry.getJSONArray("key"); + * + * * @return JSONArray @getJSONArray */ - public JSONArray getJSONArray(String key) { + public JSONArray getJSONArray(@NotNull String key) { Object value = get(key); - if (value != null) { - if (value instanceof JSONArray) { - return (JSONArray) value; - } + if (value instanceof JSONArray) { + return (JSONArray) value; } return null; } @@ -370,19 +314,20 @@ public JSONArray getJSONArray(String key) { /** * Get {@link JSONObject} value for key * - * @param key field_uid as key. - *

Example :
+ * @param key field_uid as key.
+ *
+ * Example :
+ * *
-     *                                  JSONObject value = entry.getJSONObject("key");
-     *                                  
+ * JSONObject value = entry.getJSONObject("key"); + * + * * @return JSONObject @getJSONObject */ - public JSONObject getJSONObject(String key) { + public JSONObject getJSONObject(@NotNull String key) { Object value = get(key); - if (value != null) { - if (value instanceof JSONObject) { - return (JSONObject) value; - } + if (value instanceof JSONObject) { + return (JSONObject) value; } return null; } @@ -390,20 +335,21 @@ public JSONObject getJSONObject(String key) { /** * Get {@link JSONObject} value for key * - * @param key field_uid as key. - *

Example :
+ * @param key field_uid as key.
+ *
+ * Example :
+ * *
-     *                                  JSONObject value = entry.getJSONObject("key");
-     *                                  
+ * JSONObject value = entry.getJSONObject("key"); + * + * * @return Number @getNumber */ - public Number getNumber(String key) { + public Number getNumber(@NotNull String key) { Object value = get(key); - if (value != null) { - if (value instanceof Number) { - return (Number) value; - } + if (value instanceof Number) { + return (Number) value; } return null; } @@ -411,18 +357,21 @@ public Number getNumber(String key) { /** * Get integer value for key * - * @param key field_uid as key. - *

Example :
+ * @param key field_uid as key.
+ *
+ * Example :
+ * *
-     *  int value = entry.getInt("key");
-     *  
+ * int value = entry.getInt("key"); + * + * * @return int @getInt */ - public int getInt(String key) { - Number value = getNumber(key); - if (value != null) { - return value.intValue(); + public int getInt(@NotNull String key) { + Object value = getNumber(key); + if (value instanceof Integer) { + return (Integer) value; } return 0; } @@ -431,57 +380,64 @@ public int getInt(String key) { * Get integer value for key * * @param key field_uid as key. - * @return float @getFloat - *

Example :
- *
-     * float value = entry.getFloat("key");
-     * 
+ * @return float @getFloat
+ *
+ * Example :
+ * + *
+     *         float value = entry.getFloat("key");
+     *         
*/ - public float getFloat(String key) { - Number value = getNumber(key); - if (value != null) { - return value.floatValue(); + public float getFloat(@NotNull String key) { + Object value = getNumber(key); + if (value instanceof Float) { + return (Float) value; } - return (float) 0; + return 0; } /** * Get double value for key * * @param key field_uid as key. - * @return double @getDouble - *

Example :
- *
-     * double value = entry.getDouble("key");
-     * 
+ * @return double @getDouble
+ *
+ * Example :
+ * + *
+     *         double value = entry.getDouble("key");
+     *         
*/ - public double getDouble(String key) { + public double getDouble(@NotNull String key) { Number value = getNumber(key); if (value != null) { return value.doubleValue(); } - return (double) 0; + return 0; } /** * Get long value for key * - * @param key field_uid as key. - *

Example :
+ * @param key field_uid as key.
+ *
+ * Example :
+ * *
-     *                                  long value = entry.getLong("key");
-     *                                  
+ * long value = entry.getLong("key"); + * + * * @return long @getLong */ - public long getLong(String key) { + public long getLong(@NotNull String key) { Number value = getNumber(key); if (value != null) { return value.longValue(); } - return (long) 0; + return 0; } /** @@ -489,13 +445,17 @@ public long getLong(String key) { * * @param key field_uid as key. * - *

Example :
+ *
+ *
+ * Example :
+ * *
-     *                                  short value = entry.getShort("key");
-     *                                  
+ * short value = entry.getShort("key"); + * + * * @return short @getShort */ - public short getShort(String key) { + public short getShort(@NotNull String key) { Number value = getNumber(key); if (value != null) { return value.shortValue(); @@ -506,18 +466,21 @@ public short getShort(String key) { /** * Get {@link Calendar} value for key * - * @param key field_uid as key. - *

Example :
+ * @param key field_uid as key.
+ *
+ * Example :
+ * *
-     *                                  Calendar value = entry.getDate("key");
-     *                                  
+ * Calendar value = entry.getDate("key"); + * + * * @return Calendar @getDate */ - public Calendar getDate(String key) { + public Calendar getDate(@NotNull String key) { try { String value = getString(key); - return ContentstackUtil.parseDate(value, null); + return Constants.parseDate(value, null); } catch (Exception e) { logger.severe(e.getLocalizedMessage()); } @@ -527,18 +490,19 @@ public Calendar getDate(String key) { /** * Get {@link Calendar} value of creation time of entry. * - * @return Calendar @getCreateAt - *

Example :
- *
-     * Calendar createdAt = entry.getCreateAt("key");
-     * 
+ * @return Calendar @getCreateAt
+ *
+ * Example :
+ * + *
+     *         Calendar createdAt = entry.getCreateAt("key");
+     *         
*/ - public Calendar getCreateAt() { try { String value = getString("created_at"); - return ContentstackUtil.parseDate(value, null); + return Constants.parseDate(value, null); } catch (Exception e) { logger.severe(e.getLocalizedMessage()); } @@ -548,31 +512,34 @@ public Calendar getCreateAt() { /** * Get uid who created this entry. * - * @return String @getCreatedBy - *

Example :
- *
-     * String createdBy_uid = entry.getCreatedBy();
-     * 
+ * @return String @getCreatedBy
+ *
+ * Example :
+ * + *
+     *         String createdBy_uid = entry.getCreatedBy();
+     *         
*/ public String getCreatedBy() { - return getString("created_by"); } /** * Get {@link Calendar} value of updating time of entry. * - * @return Calendar @getUpdateAt - *

Example :
- *
-     * Calendar updatedAt = entry.getUpdateAt("key");
-     * 
+ * @return Calendar @getUpdateAt
+ *
+ * Example :
+ * + *
+     *         Calendar updatedAt = entry.getUpdateAt("key");
+     *         
*/ public Calendar getUpdateAt() { try { String value = getString("updated_at"); - return ContentstackUtil.parseDate(value, null); + return Constants.parseDate(value, null); } catch (Exception e) { logger.severe(e.getLocalizedMessage()); } @@ -582,11 +549,13 @@ public Calendar getUpdateAt() { /** * Get uid who updated this entry. * - * @return String @getString - *

Example :
- *
-     * String updatedBy_uid = entry.getUpdatedBy();
-     * 
+ * @return String @getString
+ *
+ * Example :
+ * + *
+     *         String updatedBy_uid = entry.getUpdatedBy();
+     *         
*/ public String getUpdatedBy() { return getString("updated_by"); @@ -597,16 +566,19 @@ public String getUpdatedBy() { * * @return Calendar * - *

Example :
- *
-     * Calendar updatedAt = entry.getUpdateAt("key");
-     * 
+ *
+ *
+ * Example :
+ * + *
+     *         Calendar updatedAt = entry.getUpdateAt("key");
+     *         
*/ public Calendar getDeleteAt() { try { String value = getString("deleted_at"); - return ContentstackUtil.parseDate(value, null); + return Constants.parseDate(value, null); } catch (Exception e) { logger.severe(e.getLocalizedMessage()); } @@ -616,14 +588,15 @@ public Calendar getDeleteAt() { /** * Get uid who deleted this entry. * - * @return String - *

Example :
- *
-     * String deletedBy_uid = entry.getDeletedBy();
-     * 
+ * @return String
+ *
+ * Example :
+ * + *
+     *         String deletedBy_uid = entry.getDeletedBy();
+     *         
*/ public String getDeletedBy() { - return getString("deleted_by"); } @@ -631,25 +604,29 @@ public String getDeletedBy() { * Get an asset from the entry * * @param key field_uid as key. - * @return Asset - *

Example :
- *
-     * Asset asset = entry.getAsset("key");
-     * 
+ * @return Asset
+ *
+ * Example :
+ * + *
+     *         Asset asset = entry.getAsset("key");
+     *         
*/ public Asset getAsset(String key) { - JSONObject assetObject = getJSONObject(key); - Asset asset = contentTypeInstance.stackInstance.asset().configure(assetObject); - - return asset; + return contentType.stackInstance.asset().configure(assetObject); } /** - * Get an assets from the entry. This works with multiple true fields - *

Example :
+ * Get an assets from the entry. This works with multiple true fields
+ *
+ * Example :
+ * *
-     * {@code List asset = entry.getAssets("key"); }
+     * {
+     *     @code
+     *     List asset = entry.getAssets("key");
+     * }
      * 
* * @param key This is the String key @@ -659,31 +636,37 @@ public Asset getAsset(String key) { public List getAssets(String key) { List assets = new ArrayList<>(); JSONArray assetArray = getJSONArray(key); - - for (int i = 0; i < assetArray.length(); i++) { - - if (assetArray.opt(i) instanceof JSONObject) { - Asset asset = contentTypeInstance.stackInstance.asset().configure(assetArray.optJSONObject(i)); + assetArray.forEach(model -> { + if (model instanceof JSONObject) { + JSONObject newModel = (JSONObject) model; + Asset asset = contentType.stackInstance.asset().configure(newModel); assets.add(asset); } - } + }); return assets; } /** - * Get a group from entry. + * @param key + * + * + * Get a group from entry. + * + * @param key field_uid as key.
+ *
+ * Example :
* - * @param key field_uid as key. - *

Example :
*
-     *                                  Group innerGroup = entry.getGroup("key");
-     *                                  @return null
-     *                                  
+ * Group innerGroup = entry.getGroup("key"); + * return null + * + * + * + * @return {@link Group} */ public Group getGroup(String key) { - if (!key.isEmpty() && resultJson.has(key) && resultJson.opt(key) instanceof JSONObject) { - return new Group(contentTypeInstance.stackInstance, resultJson.optJSONObject(key)); + return new Group(contentType.stackInstance, resultJson.optJSONObject(key)); } return null; } @@ -694,28 +677,25 @@ public Group getGroup(String key) { * Note :- This will work when group is multiple true. * * @param key field_uid as key. - * @return list of group from entry - *

Example :
- *
-     * Group innerGroup = entry.getGroups("key");
-     * 
+ * @return list of group from entry
+ *
+ * Example :
+ * + *
+     *         Group innerGroup = entry.getGroups("key");
+     *         
*/ public List getGroups(String key) { - + List groupList = new ArrayList<>(); if (!key.isEmpty() && resultJson.has(key) && resultJson.opt(key) instanceof JSONArray) { JSONArray array = resultJson.optJSONArray(key); - List groupList = new ArrayList<>(); - - for (int i = 0; i < array.length(); i++) { - if (array.opt(i) instanceof JSONObject) { - Group group = new Group(contentTypeInstance.stackInstance, array.optJSONObject(i)); - groupList.add(group); - } - } - - return groupList; + array.forEach(model -> { + JSONObject groupModel = (JSONObject) model; + Group group = new Group(contentType.stackInstance, groupModel); + groupList.add(group); + }); } - return null; + return groupList; } /** @@ -723,17 +703,18 @@ public List getGroups(String key) { * * @param refKey key of a reference field. * @param refContentType class uid. - * @return {@link ArrayList} of {@link Entry} instances. - * Also specified contentType value will be set as class uid for all {@link Entry} instance. - *

Example :
- *
-     * //'blt5d4sample2633b' is a dummy Stack API key
-     * //'blt6d0240b5sample254090d' is dummy access token.
-     * {@code
-     * Stack stack = Contentstack.stack( "blt5d4sample2633b", "blt6d0240b5sample254090d", "stag", false);
-     * Query csQuery = stack.contentType("contentType_name").query();
-     * csQuery.includeReference("for_bug");
-     * csQuery.find(new QueryResultsCallBack() {
+ * @return {@link ArrayList} of {@link Entry} instances. Also specified + * contentType value will be set as class uid for all {@link Entry} + * instance.
+ *
+ * Example :
+ * + *
+     *          {@code
+     *          Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentType_name").query();
+     *          csQuery.includeReference("for_bug");
+     *          csQuery.find(new QueryResultsCallBack() {
* @Override * public void onCompletion(ResponseType responseType, QueryResult queryResult, Error error) {
* if(error == null){ @@ -746,81 +727,58 @@ public List getGroups(String key) { * } * }); * }
- *
+ *
*/ public ArrayList getAllEntries(String refKey, String refContentType) { - try { - if (resultJson != null) { - - if (resultJson.get(refKey) instanceof JSONArray) { - - int count = ((JSONArray) resultJson.get(refKey)).length(); - ArrayList builtObjectList = new ArrayList(); - for (int i = 0; i < count; i++) { - - EntryModel model = new EntryModel(((JSONArray) resultJson.get(refKey)).getJSONObject(i), null, false, false, true); - Entry entryInstance = null; - try { - entryInstance = contentTypeInstance.stackInstance.contentType(refContentType).entry(); - } catch (Exception e) { - entryInstance = new Entry(refContentType); - logger.severe(e.getLocalizedMessage()); - } - entryInstance.setUid(model.entryUid); - entryInstance.ownerEmailId = model.ownerEmailId; - entryInstance.ownerUid = model.ownerUid; - if (model.ownerMap != null) { - entryInstance.owner = new HashMap<>(model.ownerMap); - } - entryInstance.resultJson = model.jsonObject; - entryInstance.setTags(model.tags); - - builtObjectList.add(entryInstance); - model = null; + ArrayList entryContainer = new ArrayList<>(); + if (resultJson != null) { + Object resultArr = resultJson.opt(refKey); + if (resultArr instanceof JSONArray) { + JSONArray resultArrList = (JSONArray) resultArr; + resultArrList.forEach(result -> { + JSONObject newResult = (JSONObject) result; + EntryModel model = new EntryModel(newResult); + Entry entryInstance = null; + try { + entryInstance = contentType.stackInstance.contentType(refContentType).entry(); + } catch (Exception e) { + entryInstance = new Entry(refContentType); + logger.severe(e.getLocalizedMessage()); } - - return builtObjectList; - - } + entryInstance.setUid(model.uid); + entryInstance.resultJson = model.jsonObject; + entryInstance.setTags(model.tags); + entryContainer.add(entryInstance); + }); } - } catch (Exception e) { - logger.severe(e.getLocalizedMessage()); - return null; } - - return null; + return entryContainer; } /** - * Specifies list of field uids that would be 'excluded' from the response. + * Specifies list of field uids that would be 'excluded' from the + * response. * - * @param fieldUid field uid which get 'excluded' from the response. - * @return {@link Entry} object, so you can chain this call. - *

Example :
- *
-     *     //'blt5d4sample2633b' is a dummy Stack API key
-     *     //'blt6d0240b5sample254090d' is dummy access token.
-     *     Stack stack = Contentstack.stack( "blt5d4sample2633b", "blt6d0240b5sample254090d", "stag", false);
-     *     Entry entry = stack.contentType("form_name").entry("entry_uid");
- * entry.except(new String[]{"name", "description"}); - *
+ * @param fieldUid field uid which get 'excluded' from the response. + * @return {@link Entry} object, so you can chain this call.
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *          Entry entry = stack.contentType("form_name").entry("entry_uid");
+ * entry.except(new String[]{"name", "description"}); + *
*/ - public Entry except(String[] fieldUid) { - try { - if (fieldUid != null && fieldUid.length > 0) { - - if (objectUidForExcept == null) { - objectUidForExcept = new JSONArray(); - } - - int count = fieldUid.length; - for (int i = 0; i < count; i++) { - objectUidForExcept.put(fieldUid[i]); - } + public Entry except(@NotNull String[] fieldUid) { + if (fieldUid.length > 0) { + if (exceptFieldArray == null) { + exceptFieldArray = new JSONArray(); + } + for (String s : fieldUid) { + exceptFieldArray.put(s); } - } catch (Exception e) { - logger.severe(e.getLocalizedMessage()); } return this; } @@ -829,27 +787,23 @@ public Entry except(String[] fieldUid) { * Add a constraint that requires a particular reference key details. * * @param referenceField key that to be constrained. - * @return {@link Entry} object, so you can chain this call. - *

Example :
- *
-     *    //'blt5d4sample2633b' is a dummy Stack API key
-     *    //'blt6d0240b5sample254090d' is dummy access token.
-     *    Stack stack = Contentstack.stack("blt5d4sample2633b", "blt6d0240b5sample254090d", "stag", false);
-     *    Entry entry = stack.contentType("form_name").entry("entry_uid");
- * entry.includeReference("referenceUid"); - *
+ * @return {@link Entry} object, so you can chain this call.
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *          Entry entry = stack.contentType("form_name").entry("entry_uid");
+ * entry.includeReference("referenceUid"); + *
*/ - public Entry includeReference(String referenceField) { - try { - if (!referenceField.isEmpty()) { - if (referenceArray == null) { - referenceArray = new JSONArray(); - } - referenceArray.put(referenceField); - otherPostJSON.put("include[]", referenceArray); + public Entry includeReference(@NotNull String referenceField) { + if (!referenceField.isEmpty()) { + if (referenceArray == null) { + referenceArray = new JSONArray(); } - } catch (Exception e) { - logger.severe(e.getLocalizedMessage()); + referenceArray.put(referenceField); + params.put("include[]", referenceArray); } return this; } @@ -858,251 +812,223 @@ public Entry includeReference(String referenceField) { * Add a constraint that requires a particular reference key details. * * @param referenceFields array key that to be constrained. - * @return {@link Entry} object, so you can chain this call. - *

Example :
- *
-     *    //'blt5d4sample2633b' is a dummy Stack API key
-     *    //'blt6d0240b5sample254090d' is dummy access token.
-     *    Stack stack = Contentstack.stack("blt5d4sample2633b", "blt6d0240b5sample254090d", "stag", false);
-     *    Entry entry = stack.contentType("form_name").entry("entry_uid");
- * entry.includeReference(new String[]{"referenceUid_A", "referenceUid_B"}); - *
+ * @return {@link Entry} object, so you can chain this call.
+ *
+ * Example :
+ * + *
+    *           Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *          Entry entry = stack.contentType("form_name").entry("entry_uid");
+ * entry.includeReference(new String[]{"referenceUid_A", "referenceUid_B"}); + *
*/ - public Entry includeReference(String[] referenceFields) { - try { - if (referenceFields != null && referenceFields.length > 0) { - if (referenceArray == null) { - referenceArray = new JSONArray(); - } - for (int i = 0; i < referenceFields.length; i++) { - referenceArray.put(referenceFields[i]); - } - otherPostJSON.put("include[]", referenceArray); + public Entry includeReference(@NotNull String[] referenceFields) { + if (referenceFields.length > 0) { + if (referenceArray == null) { + referenceArray = new JSONArray(); } - } catch (Exception e) { - logger.severe(e.getLocalizedMessage()); + for (String field : referenceFields) { + referenceArray.put(field); + } + params.put("include[]", referenceArray); } return this; } /** - * Specifies an array of 'only' keys in BASE object that would be 'included' in the response. + * Specifies an array of 'only' keys in BASE object that would be + * 'included' in the response. * - * @param fieldUid Array of the 'only' reference keys to be included in response. - * @return {@link Entry} object, so you can chain this call. - *

Example :
- *
-     *    //'blt5d4sample2633b' is a dummy Stack API key
-     *    //'blt6d0240b5sample254090d' is dummy access token.
-     *    Stack stack = Contentstack.stack("blt5d4sample2633b", "blt6d0240b5sample254090d", "stag", false);
-     *    Entry entry = stack.contentType("form_name").entry("entry_uid");
- * entry.only(new String[]{"name", "description"}); - *
+ * @param fieldUid Array of the 'only' reference keys to be included in + * response. + * @return {@link Entry} object, so you can chain this call.
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *          Entry entry = stack.contentType("form_name").entry("entry_uid");
+ * entry.only(new String[]{"name", "description"}); + *
*/ public Entry only(String[] fieldUid) { - try { - if (fieldUid != null && fieldUid.length > 0) { - if (objectUidForOnly == null) { - objectUidForOnly = new JSONArray(); - } - - int count = fieldUid.length; - for (int i = 0; i < count; i++) { - objectUidForOnly.put(fieldUid[i]); - } + if (fieldUid != null && fieldUid.length > 0) { + if (objectUidForOnly == null) { + objectUidForOnly = new JSONArray(); + } + for (String field : fieldUid) { + objectUidForOnly.put(field); } - } catch (Exception e) { - logger.severe(e.getLocalizedMessage()); } return this; } /** - * Specifies an array of 'only' keys that would be 'included' in the response. + * Specifies an array of 'only' keys that would be 'included' in + * the response. * - * @param fieldUid Array of the 'only' reference keys to be included in response. + * @param fieldUid Array of the 'only' reference keys to be + * included in response. * @param referenceFieldUid Key who has reference to some other class object.. - * @return {@link Entry} object, so you can chain this call. - *

Example :
- *
-     *    //'blt5d4sample2633b' is a dummy Stack API key
-     *    //'blt6d0240b5sample254090d' is dummy access token.
-     *    Stack stack = Contentstack.stack( "blt5d4sample2633b", "blt6d0240b5sample254090d", "stag", false);
-     *    Entry entry = stack.contentType("form_name").entry("entry_uid");
- * ArrayList<String> array = new ArrayList<String>(); - * array.add("description"); - * array.add("name"); - * entry.onlyWithReferenceUid(array, "referenceUid"); - *
+ * @return {@link Entry} object, so you can chain this call.
+ *
+ * Example :
+ * + *
+                Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *          Entry entry = stack.contentType("form_name").entry("entry_uid");
+ * ArrayList<String> array = new ArrayList<String>(); + * array.add("description"); + * array.add("name"); + * entry.onlyWithReferenceUid(array, "referenceUid"); + *
*/ - public Entry onlyWithReferenceUid(ArrayList fieldUid, String referenceFieldUid) { - try { - if (fieldUid != null && referenceFieldUid != null) { - if (onlyJsonObject == null) { - onlyJsonObject = new JSONObject(); - } - JSONArray fieldValueArray = new JSONArray(); - int count = fieldUid.size(); - for (int i = 0; i < count; i++) { - fieldValueArray.put(fieldUid.get(i)); - } - - onlyJsonObject.put(referenceFieldUid, fieldValueArray); - includeReference(referenceFieldUid); - } - } catch (Exception e) { - logger.severe(e.getLocalizedMessage()); + public Entry onlyWithReferenceUid(@NotNull ArrayList fieldUid, @NotNull String referenceFieldUid) { + if (onlyJsonObject == null) { + onlyJsonObject = new JSONObject(); } + JSONArray fieldValueArray = new JSONArray(); + fieldUid.forEach(field -> { + fieldValueArray.put(field); + }); + onlyJsonObject.put(referenceFieldUid, fieldValueArray); + includeReference(referenceFieldUid); return this; } /** - * Specifies an array of 'except' keys that would be 'excluded' in the response. + * Specifies an array of 'except' keys that would be 'excluded' + * in the response. * - * @param fieldUid Array of the 'except' reference keys to be excluded in response. + * @param fieldUid Array of the 'except' reference keys to be + * excluded in response. * @param referenceFieldUid Key who has reference to some other class object. * @return {@link Entry} object, so you can chain this call. * - *

Example :
- *
-     *    //'blt5d4sample2633b' is a dummy Stack API key
-     *    //'blt6d0240b5sample254090d' is dummy access token.
-     *    Stack stack = Contentstack.stack("blt5d4sample2633b", "blt6d0240b5sample254090d", "stag", false);
-     *    Entry entry = stack.contentType("form_name").entry("entry_uid");
- * ArrayList<String> array = new ArrayList<String>(); - * array.add("description"); - * array.add("name");
- * entry.onlyWithReferenceUid(array, "referenceUid"); - *
+ *
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *          Entry entry = stack.contentType("form_name").entry("entry_uid");
+ * ArrayList<String> array = new ArrayList<String>(); + * array.add("description"); + * array.add("name");
+ * entry.onlyWithReferenceUid(array, "referenceUid"); + *
*/ - public Entry exceptWithReferenceUid(ArrayList fieldUid, String referenceFieldUid) { - try { - if (fieldUid != null && referenceFieldUid != null) { - if (exceptJsonObject == null) { - exceptJsonObject = new JSONObject(); - } - JSONArray fieldValueArray = new JSONArray(); - int count = fieldUid.size(); - for (int i = 0; i < count; i++) { - fieldValueArray.put(fieldUid.get(i)); - } - - exceptJsonObject.put(referenceFieldUid, fieldValueArray); - includeReference(referenceFieldUid); - } - } catch (Exception e) { - logger.severe(e.getLocalizedMessage()); + public Entry exceptWithReferenceUid(@NotNull ArrayList fieldUid, @NotNull String referenceFieldUid) { + if (exceptJsonObject == null) { + exceptJsonObject = new JSONObject(); } + JSONArray fieldValueArray = new JSONArray(); + fieldUid.forEach(field -> fieldValueArray.put(field)); + exceptJsonObject.put(referenceFieldUid, fieldValueArray); + includeReference(referenceFieldUid); return this; } /** * Fetches the latest version of the entries from Contentstack.com content stack * - * @param callBack {@link EntryResultCallBack} object to notify the application when the request has completed. - *

Example :
+ * @param callback {@link EntryResultCallBack} object to notify the application + * when the request has completed.
+ *
+ * Example :
+ * *
-     *                                                    //'blt5d4sample2633b' is a dummy Stack API key
-     *                                                    //'blt6d0240b5sample254090d' is dummy access token.
-     *                                                    {@code
-     *                                                    Stack stack = Contentstack.stack("blt5d4sample2633b", "blt6d0240b5sample254090d", "stag", false);
-     *                                                    Entry entry = stack.contentType("form_name").entry("entry_uid");
- * entry.fetch(new EntryResultCallBack() {
- * @Override - * public void onCompletion(ResponseType responseType, Error error) { - * }
- * });
- * } - *
+ * {@code + * Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment"); + * Entry entry = stack.contentType("form_name").entry("entry_uid");
+ * entry.fetch(new EntryResultCallBack() {
+ * @Override + * public void onCompletion(ResponseType responseType, Error error) { + * }
+ * });
+ * } + * */ - public void fetch(EntryResultCallBack callBack) { - try { - if (!uid.isEmpty()) { - String URL = "/" + contentTypeInstance.stackInstance.VERSION + "/content_types/" + contentTypeName + "/entries/" + uid; - LinkedHashMap headers = getHeader(localHeader); - LinkedHashMap headerAll = new LinkedHashMap(); - JSONObject urlQueries = new JSONObject(); - if (headers != null && headers.size() > 0) { - for (Map.Entry entry : headers.entrySet()) { - headerAll.put(entry.getKey(), (String) entry.getValue()); - } - if (headers.containsKey("environment")) { - urlQueries.put("environment", headers.get("environment")); - } - } - fetchFromNetwork(URL, urlQueries, callBack); + public void fetch(EntryResultCallBack callback) { + if (!uid.isEmpty()) { + try { + throw new IllegalAccessException("Entry Uid is required"); + } catch (IllegalAccessException e) { + logger.severe(e.getLocalizedMessage()); } - } catch (Exception e) { - throwException(null, e, callBack); } + String urlString = "content_types/" + contentTypeUid + "/entries/" + uid; + JSONObject urlQueries = new JSONObject(); + urlQueries.put(ENVIRONMENT, headers.get(ENVIRONMENT)); + checkLivePreview(headers, urlQueries); + fetchFromNetwork(urlString, urlQueries, callback); } - - private void fetchFromNetwork(String URL, JSONObject urlQueries, EntryResultCallBack callBack) { + private void fetchFromNetwork(String urlString, JSONObject urlQueries, EntryResultCallBack callBack) { try { - JSONObject mainJson = new JSONObject(); setIncludeJSON(urlQueries, callBack); mainJson.put("query", urlQueries); - mainJson.put("_method", CSAppConstants.RequestMethod.GET.toString()); HashMap urlParams = getUrlParams(mainJson); - new CSBackgroundTask(this, contentTypeInstance.stackInstance, CSController.FETCHENTRY, URL, getHeader(localHeader), urlParams, new JSONObject(), CSAppConstants.callController.ENTRY.toString(), false, CSAppConstants.RequestMethod.GET, callBack); - + new CSBackgroundTask(this, contentType.stackInstance, Constants.FETCHENTRY, urlString, this.headers, + urlParams, Constants.REQUEST_CONTROLLER.ENTRY.toString(), callBack); } catch (Exception e) { throwException(null, e, callBack); } } + private void checkLivePreview(LinkedHashMap headers, JSONObject urlQueries) { + Config configInstance = contentType.stackInstance.config; + if (configInstance.enableLivePreview + && configInstance.livePreviewContentType.equalsIgnoreCase(contentTypeUid)) { + configInstance.setHost(configInstance.livePreviewHost); + headers.remove("access_token"); // Step 4: Remove access_token from header + headers.remove(ENVIRONMENT); // Remove environment from urlQuery + if (configInstance.livePreviewHash == null || configInstance.livePreviewHash.isEmpty()) { + configInstance.livePreviewHash = "init"; + } + headers.put("live_preview", configInstance.livePreviewHash); + headers.put("authorization", configInstance.managementToken); + urlQueries.remove(ENVIRONMENT); + } + } private LinkedHashMap getUrlParams(JSONObject jsonMain) { - JSONObject queryJSON = jsonMain.optJSONObject("query"); LinkedHashMap hashMap = new LinkedHashMap<>(); - if (queryJSON != null && queryJSON.length() > 0) { Iterator iter = queryJSON.keys(); while (iter.hasNext()) { String key = iter.next(); - try { - Object value = queryJSON.opt(key); - hashMap.put(key, value); - } catch (Exception e) { - logger.severe(e.getLocalizedMessage()); - } + Object value = queryJSON.opt(key); + hashMap.put(key, value); } - return hashMap; } - - return null; + return hashMap; } - private void setIncludeJSON(JSONObject mainJson, ResultCallBack callBack) { try { - Iterator iterator = otherPostJSON.keys(); + Iterator iterator = params.keys(); while (iterator.hasNext()) { String key = iterator.next(); - Object value = otherPostJSON.get(key); + Object value = params.get(key); mainJson.put(key, value); } - if (objectUidForOnly != null && objectUidForOnly.length() > 0) { mainJson.put("only[BASE][]", objectUidForOnly); objectUidForOnly = null; } - - if (objectUidForExcept != null && objectUidForExcept.length() > 0) { - mainJson.put("except[BASE][]", objectUidForExcept); - objectUidForExcept = null; + if (exceptFieldArray != null && exceptFieldArray.length() > 0) { + mainJson.put("except[BASE][]", exceptFieldArray); + exceptFieldArray = null; } - if (exceptJsonObject != null && exceptJsonObject.length() > 0) { mainJson.put("except", exceptJsonObject); exceptJsonObject = null; } - if (onlyJsonObject != null && onlyJsonObject.length() > 0) { mainJson.put("only", onlyJsonObject); onlyJsonObject = null; @@ -1113,43 +1039,15 @@ private void setIncludeJSON(JSONObject mainJson, ResultCallBack callBack) { } private void throwException(String errorMsg, Exception e, EntryResultCallBack callBack) { - Error error = new Error(); if (errorMsg != null) { error.setErrorMessage(errorMsg); } else { error.setErrorMessage(e.toString()); } - callBack.onRequestFail(ResponseType.UNKNOWN, error); - } - private LinkedHashMap getHeader(LinkedHashMap localHeader) { - LinkedHashMap mainHeader = formHeader; - LinkedHashMap classHeaders = new LinkedHashMap<>(); - 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 formHeader; - } - } - - /** * This method adds key and value to an Entry. * @@ -1157,126 +1055,132 @@ private LinkedHashMap getHeader(LinkedHashMap lo * @param value The value as string which needs to be added to an Entry * @return {@link Entry} * - *

Example :
- *
-     * //'blt5d4sample2633b' is a dummy Stack API key
-     * //'blt6d0240b5sample254090d' is dummy access token.
-     * {@code
-     * Stack stack = Contentstack.stack("blt5d4sample2633b", "blt6d0240b5sample254090d", "stag");
-     * final Entry entry = stack.contentType("user").entry("blt3b0aaebf6f1c3762"); 
- * entry.addParam("include_dimensions", "true");
- * entry.fetch(new ResultCallBack() { - *
@ - * Override - * public void onCompletion(ResponseType responseType, Error error) { - * }
- * });
- * } - *
+ *
+ *
+ * Example :
+ * + *
+     *         {@code
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         final Entry entry = stack.contentType("user").entry("entryUid"); 
+ * entry.addParam("include_dimensions", "true");
+ * entry.fetch(new ResultCallBack() { + *
@ Override + * public void onCompletion(ResponseType responseType, Error error) { + * }
+ * });
+ * } + *
*/ - public Entry addParam(String key, String value) { - - if (key != null && value != null) { - try { - otherPostJSON.put(key, value); - } catch (JSONException e) { - logger.severe(e.getLocalizedMessage()); - } - } - + public Entry addParam(@NotNull String key, @NotNull String value) { + params.put(key, value); return this; } - /** - * This method also includes the content type UIDs of the referenced entries returned in the response + * This method also includes the content type UIDs of the referenced entries + * returned in the response * * @return {@link Entry} * - *

Example :
- *
-     * //'blt5d4sample2633b' is a dummy Stack API key
-     * //'blt6d0240b5sample254090d' is dummy access token.
-     * {@code
-     * Stack stack = Contentstack.stack("blt5d4sample2633b", "blt6d0240b5sample254090d", "stag");
-     * final Entry entry = stack.contentType("user").entry("blt3b0aaebf6f1c3762"); 
- * entry.includeReferenceContentTypeUID;
- * entry.fetch(new EntryResultCallBack() { - *
@ - * Override - * public void onCompletion(ResponseType responseType, Error error) { - * }
- * });
- * } - *
+ *
+ * Example :
+ * + *
+     *          {@code
+     *          Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *          final Entry entry = stack.contentType("user").entry("entryUid"); 
+ * entry.includeReferenceContentTypeUID;
+ * entry.fetch(new EntryResultCallBack() { + *
@Override + * public void onCompletion(ResponseType responseType, Error error) { + * }
+ * });
+ * } + *
*/ public Entry includeReferenceContentTypeUID() { - try { - otherPostJSON.put("include_reference_content_type_uid", "true"); - } catch (JSONException e) { - logger.severe(e.getLocalizedMessage()); - } + params.put("include_reference_content_type_uid", "true"); return this; } - /** * Include Content Type of all returned objects along with objects themselves. * - * @return {@link Entry} object, so you can chain this call. - *

Example :
- *
-     *     //'blt5d4sample2633b' is a dummy Stack API key
-     *     //'blt6d0240b5sample254090d' is dummy access token.
-     *     Stack stack = Contentstack.stack("blt5d4sample2633b", "blt6d0240b5sample254090d", "stag");
-     *     final Entry entry = stack.contentType("user").entry("blt3b0aaebf6f1c3762");
-     *     entry.includeContentType();
-     * 
+ * @return {@link Entry} object, so you can chain this call.
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         final Entry entry = stack.contentType("user").entry("entryUid");
+     *         entry.includeContentType();
+     *         
*/ public Entry includeContentType() { - try { - if (otherPostJSON.has("include_schema")) { - otherPostJSON.remove("include_schema"); - } - otherPostJSON.put("include_content_type", true); - otherPostJSON.put("include_global_field_schema", true); - } catch (Exception e) { - logger.severe(e.getLocalizedMessage()); - } + params.remove("include_schema"); + params.put("include_content_type", true); + params.put("include_global_field_schema", true); return this; } - /** - * Retrieve the published content of the fallback locale if an entry is not localized in specified locale + * Retrieve the published content of the fallback locale if an entry is not + * localized in specified locale * - * @return {@link Entry} object, so you can chain this call. - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "ApiKey", "deliveryToken", "environment");
-     *     final Entry entry = stack.contentType("user").entry("entryUid");
-     *     entry.includeFallback();
-     * 
+ * @return {@link Entry} object, so you can chain this call.
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         final Entry entry = stack.contentType("user").entry("entryUid");
+     *         entry.includeFallback();
+     *         
*/ public Entry includeFallback() { - otherPostJSON.put("include_fallback", true); + params.put("include_fallback", true); return this; } - /** - * includeEmbeddedItems instance of Entry - * Include Embedded Objects (Entries and Assets) along with entry/entries details.
- * Stack stack = Contentstack.stack( "ApiKey", "deliveryToken", "environment"); - * final Entry entry = stack.contentType("user").entry("entryUid"); - * entry = entry.includeEmbeddedObjects() - * entry.fetch() + * includeEmbeddedItems instance of Entry Include Embedded Objects (Entries and + * Assets) along with entry/entries details.
+ * + * @return {@link Entry} object, so you can chain this call.
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         final Entry entry = stack.contentType("user").entry("entryUid");
+     *         entry.includeEmbeddedItems();
+     *         
* - * @return {@link Entry} */ public Entry includeEmbeddedItems() { - otherPostJSON.put("include_embedded_items[]", "BASE"); + params.put("include_embedded_items[]", "BASE"); + return this; + } + + /** + * Includes Branch in the entry response + * + * @return {@link Entry} object, so you can chain this call. + * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         final Entry entry = stack.contentType("user").entry("entryUid");
+     *         entry.includeBranch();
+     *         
+ */ + public Entry includeBranch() { + params.put("include_branch", true); return this; } diff --git a/src/main/java/com/contentstack/sdk/EntryModel.java b/src/main/java/com/contentstack/sdk/EntryModel.java index b1c03d4b..9696716c 100644 --- a/src/main/java/com/contentstack/sdk/EntryModel.java +++ b/src/main/java/com/contentstack/sdk/EntryModel.java @@ -1,132 +1,89 @@ package com.contentstack.sdk; + import org.json.JSONArray; import org.json.JSONObject; + import java.util.HashMap; -import java.util.Iterator; import java.util.Map; -import java.util.logging.Logger; - class EntryModel { + private static final String publishDetailKey = "publish_details"; + private static final String entryKey = "entry"; + private static final String titleKey = "title"; + private static final String localeKey = "locale"; + private static final String uidKey = "uid"; + private static final String urlKey = "url"; + + protected JSONObject publishDetails; + protected JSONObject jsonObject; + protected String title = null; + protected String uid = null; + protected String url = null; + protected String updatedAt = null; + protected String updatedBy = null; + protected String createdAt = null; + protected String createdBy = null; + protected Boolean isDirectory = false; + protected String[] tags = null; + protected String description = null; + protected String environment = null; + protected JSONArray images = null; + protected String locale = null; + protected String time = null; + protected String user = null; + protected int version = 1; + protected Boolean inProgress = null; + protected String language = null; + protected String rteContent = null; + protected Map metadata = null; + + public EntryModel(JSONObject response) { + this.jsonObject = response; + if (this.jsonObject.has(entryKey)) { + this.jsonObject = jsonObject.optJSONObject(entryKey); + } - private static final Logger logger = Logger.getLogger(EntryModel.class.getSimpleName()); - protected JSONObject jsonObject = null; - protected String entryUid = null; - protected String ownerEmailId = null; - protected String ownerUid = null; - protected String title = null; - protected String url = null; - protected String[] tags = null; - protected String language = null; - protected String rteContent = null; - protected Map ownerMap = null; - protected Map _metadata= null; - private JSONArray tagsArray = null; - - public EntryModel(JSONObject jsonObj, String entryUid, boolean isFromObjectsModel ,boolean isFromCache, boolean isFromDeltaResponse) { - - try{ - this.entryUid = entryUid; - if(isFromObjectsModel){ - jsonObject = jsonObj; - this.entryUid = (String) (jsonObject.isNull("uid") ? " " : jsonObject.opt("uid")); - }else{ - - if(isFromCache){ - jsonObject = jsonObj.opt("response") == null ? null : jsonObj.optJSONObject("response"); - }else{ - jsonObject = jsonObj; - } - - if(isFromDeltaResponse){ - this.entryUid = (String) (jsonObject != null && jsonObject.isNull("uid") ? " " : jsonObject.opt("uid")); - }else{ - jsonObject = jsonObject != null && jsonObject.opt("entry") == null ? null : jsonObject.optJSONObject("entry"); - } - } - if(jsonObject != null && jsonObject.has("uid")){ - this.entryUid = (String) (jsonObject.isNull("uid") ? " " : jsonObject.opt("uid")); - } - - if(jsonObject != null && jsonObject.has("title")){ - this.title = (String) (jsonObject.isNull("title") ? " " : jsonObject.opt("title")); - } - - if(jsonObject != null && jsonObject.has("locale")){ - this.language = (String) (jsonObject.isNull("locale") ? " " : jsonObject.opt("locale")); - } - - if(jsonObject != null && jsonObject.has("url")){ - this.url = (String) (jsonObject.isNull("url") ? " " : jsonObject.opt("url")); - } - - if(jsonObject != null && jsonObject.has("_metadata")){ - JSONObject _metadataJSON = jsonObject.optJSONObject("_metadata"); - Iterator iterator = _metadataJSON.keys(); - _metadata = new HashMap<>(); - while (iterator.hasNext()) { - String key = iterator.next(); - if(key.equalsIgnoreCase("uid")){ - this.entryUid = _metadataJSON.optString(key); - } - _metadata.put(key, _metadataJSON.optString(key)); - } - }else if(jsonObject != null && jsonObject.has("publish_details")){ - - JSONArray publishArray = jsonObject.optJSONArray("publish_details"); - - if (publishArray!=null && publishArray.length()>0){ - - 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)); - } - } - } - - - - if(_metadata == null) { - _metadata = new HashMap<>(); - _metadata.put("publish_details", publishArray); - } - - } - - - if(jsonObject != null && jsonObject.has("_owner") && (jsonObject.opt("_owner") != null) && (! jsonObject.opt("_owner").toString().equalsIgnoreCase("null")) ){ - JSONObject ownerObject = jsonObject.optJSONObject("_owner"); - 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(); - } - JSONObject owner = jsonObject.optJSONObject("_owner"); - Iterator iterator = owner.keys(); - ownerMap = new HashMap<>(); - while (iterator.hasNext()) { - String key = iterator.next(); - ownerMap.put(key, owner.optString(key)); - } - } - - if(jsonObject != null && jsonObject.has("rich_text_editor")){ - this.rteContent = (String) (jsonObject.isNull("rich_text_editor") ? " " : jsonObject.opt("rich_text_editor")); + if (this.jsonObject.has(uidKey)) { + this.uid = (String) this.jsonObject.opt(uidKey); + } + if (this.jsonObject.has(titleKey)) { + this.title = (String) this.jsonObject.opt(titleKey); + } + if (this.jsonObject.has(localeKey)) { + this.language = (String) this.jsonObject.opt(localeKey); + } + if (this.jsonObject.has(urlKey)) { + this.url = (String) this.jsonObject.opt(urlKey); + } + if (this.jsonObject.has("description")) { + this.description = (String) this.jsonObject.opt("description"); + } - //do rich_text_editor utility stuff + this.images = (JSONArray) this.jsonObject.opt("images"); + this.isDirectory = (Boolean) this.jsonObject.opt("is_dir"); + this.updatedAt = (String) this.jsonObject.opt("updated_at"); + this.updatedBy = (String) this.jsonObject.opt("updated_by"); + this.createdAt = (String) this.jsonObject.opt("created_at"); + this.createdBy = (String) this.jsonObject.opt("created_by"); + this.locale = (String) this.jsonObject.opt(localeKey); + this.inProgress = (Boolean) this.jsonObject.opt("_in_progress"); + this.version = (int) this.jsonObject.opt("_version"); + + if (this.jsonObject.has(publishDetailKey)) { + parsePublishDetail(); + } - } + } - }catch (Exception e) { - logger.severe(e.getLocalizedMessage()); + private void parsePublishDetail() { + if (this.jsonObject.opt(publishDetailKey) instanceof JSONObject) { + this.publishDetails = (JSONObject) this.jsonObject.opt(publishDetailKey); + this.environment = this.publishDetails.optString("environment"); + this.time = this.publishDetails.optString("time"); + this.user = this.publishDetails.optString("user"); } - + this.metadata = new HashMap<>(); + this.metadata.put(publishDetailKey, this.publishDetails); } } diff --git a/src/main/java/com/contentstack/sdk/EntryResultCallBack.java b/src/main/java/com/contentstack/sdk/EntryResultCallBack.java index 0afbb9fd..b8372a28 100644 --- a/src/main/java/com/contentstack/sdk/EntryResultCallBack.java +++ b/src/main/java/com/contentstack/sdk/EntryResultCallBack.java @@ -1,23 +1,16 @@ package com.contentstack.sdk; -public abstract class EntryResultCallBack extends ResultCallBack{ +public abstract class EntryResultCallBack implements ResultCallBack { - /** - * Triggered after call execution complete. - * @param responseType call response from cache or network. - * @param error {@link Error} instance if call failed else null. - */ public abstract void onCompletion(ResponseType responseType, Error error); - void onRequestFinish(ResponseType responseType){ + void onRequestFinish(ResponseType responseType) { onCompletion(responseType, null); } @Override - void onRequestFail(ResponseType responseType, Error error) { + public void onRequestFail(ResponseType responseType, Error error) { onCompletion(responseType, error); } - @Override - public void always() { } } diff --git a/src/main/java/com/contentstack/sdk/Error.java b/src/main/java/com/contentstack/sdk/Error.java index 456a3522..86306791 100644 --- a/src/main/java/com/contentstack/sdk/Error.java +++ b/src/main/java/com/contentstack/sdk/Error.java @@ -1,26 +1,20 @@ package com.contentstack.sdk; -import org.json.JSONObject; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; - /** - * If there is something wrong with the API request, Contentstack returns an error. + * If there is something wrong with the API request, Contentstack returns an + * error. */ public class Error { String errorMessage = null; - int errorCode = 0; + int errorCode = 0; String errDetails = null; public Error() { } - public Error(String errorMessage, int errorCode, String errDetails) { + public Error(String errorMessage, int errorCode, String errDetails) { this.errorMessage = errorMessage; this.errorCode = errorCode; this.errDetails = errDetails; @@ -29,11 +23,14 @@ public Error(String errorMessage, int errorCode, String errDetails) { /** * * Returns error in string format. - * @return String error message - *

Example :
- *
-     *  String errorString = error.getErrorMessage();
-     *  
+ * + * @return String error message
+ *
+ * Example :
+ * + *
+     *         String errorString = error.getErrorMessage();
+     *         
*/ public String getErrorMessage() { return errorMessage; @@ -43,14 +40,16 @@ protected void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } - /** * Returns error code - * @return int value. - *

Example :
- *
-     *  int errorCode = error.getErrorCode();
-     *  
+ * + * @return int value.
+ *
+ * Example :
+ * + *
+     *         int errorCode = error.getErrorCode();
+     *         
*/ public int getErrorCode() { return errorCode; @@ -60,14 +59,16 @@ protected void setErrorCode(int errorCode) { this.errorCode = errorCode; } - /** - Returns error details in {@linkplain String} - @return String - *

Example :
- *
-     * String error = error.getErrorDetail();
-     * 
+ * Returns error details in {@linkplain String} + * + * @return String
+ *
+ * Example :
+ * + *
+     *         String error = error.getErrorDetail();
+     *         
*/ public String getErrorDetail() { return this.errDetails; diff --git a/src/main/java/com/contentstack/sdk/ErrorType.java b/src/main/java/com/contentstack/sdk/ErrorType.java deleted file mode 100644 index d83bcf52..00000000 --- a/src/main/java/com/contentstack/sdk/ErrorType.java +++ /dev/null @@ -1,181 +0,0 @@ -package com.contentstack.sdk; - -public class ErrorType { - - public static final int HTTP_CREATED = 201; - /** - * HTTP Status-Code 202: Accepted. - */ - public static final int HTTP_ACCEPTED = 202; - /** - * HTTP Status-Code 203: Non-Authoritative Information. - */ - public static final int HTTP_NOT_AUTHORITATIVE = 203; - /** - * HTTP Status-Code 204: No Content. - */ - public static final int HTTP_NO_CONTENT = 204; - /** - * HTTP Status-Code 205: Reset Content. - */ - public static final int HTTP_RESET = 205; - - /** - * HTTP Status-Code 206: Partial Content. - */ - public static final int HTTP_PARTIAL = 206; - - /* 3XX: relocation/redirect */ - - /** - * HTTP Status-Code 300: Multiple Choices. - */ - public static final int HTTP_MULT_CHOICE = 300; - - /** - * HTTP Status-Code 301: Moved Permanently. - */ - public static final int HTTP_MOVED_PERM = 301; - - /** - * HTTP Status-Code 302: Temporary Redirect. - */ - public static final int HTTP_MOVED_TEMP = 302; - - /** - * HTTP Status-Code 303: See Other. - */ - public static final int HTTP_SEE_OTHER = 303; - - /** - * HTTP Status-Code 304: Not Modified. - */ - public static final int HTTP_NOT_MODIFIED = 304; - - /** - * HTTP Status-Code 305: Use Proxy. - */ - public static final int HTTP_USE_PROXY = 305; - - /* 4XX: client error */ - - /** - * HTTP Status-Code 400: Bad Request. - */ - public static final int HTTP_BAD_REQUEST = 400; - - /** - * HTTP Status-Code 401: Unauthorized. - */ - public static final int HTTP_UNAUTHORIZED = 401; - - /** - * HTTP Status-Code 402: Payment Required. - */ - public static final int HTTP_PAYMENT_REQUIRED = 402; - - /** - * HTTP Status-Code 403: Forbidden. - */ - public static final int HTTP_FORBIDDEN = 403; - - /** - * HTTP Status-Code 404: Not Found. - */ - public static final int HTTP_NOT_FOUND = 404; - - /** - * HTTP Status-Code 405: Method Not Allowed. - */ - public static final int HTTP_BAD_METHOD = 405; - - /** - * HTTP Status-Code 406: Not Acceptable. - */ - public static final int HTTP_NOT_ACCEPTABLE = 406; - - /** - * HTTP Status-Code 407: Proxy Authentication Required. - */ - public static final int HTTP_PROXY_AUTH = 407; - - /** - * HTTP Status-Code 408: Request Time-Out. - */ - public static final int HTTP_CLIENT_TIMEOUT = 408; - - /** - * HTTP Status-Code 409: Conflict. - */ - public static final int HTTP_CONFLICT = 409; - - /** - * HTTP Status-Code 410: Gone. - */ - public static final int HTTP_GONE = 410; - - /** - * HTTP Status-Code 411: Length Required. - */ - public static final int HTTP_LENGTH_REQUIRED = 411; - - /** - * HTTP Status-Code 412: Precondition Failed. - */ - public static final int HTTP_PRECON_FAILED = 412; - - /** - * HTTP Status-Code 413: Request Entity Too Large. - */ - public static final int HTTP_ENTITY_TOO_LARGE = 413; - - /** - * HTTP Status-Code 414: Request-URI Too Large. - */ - public static final int HTTP_REQ_TOO_LONG = 414; - - /** - * HTTP Status-Code 415: Unsupported Media Type. - */ - public static final int HTTP_UNSUPPORTED_TYPE = 415; - - /* 5XX: server error */ - - /** - * HTTP Status-Code 500: Internal Server Error. - * @deprecated it is misplaced and shouldn't have existed. - */ - @Deprecated - public static final int HTTP_SERVER_ERROR = 500; - - /** - * HTTP Status-Code 500: Internal Server Error. - */ - public static final int HTTP_INTERNAL_ERROR = 500; - - /** - * HTTP Status-Code 501: Not Implemented. - */ - public static final int HTTP_NOT_IMPLEMENTED = 501; - - /** - * HTTP Status-Code 502: Bad Gateway. - */ - public static final int HTTP_BAD_GATEWAY = 502; - - /** - * HTTP Status-Code 503: Service Unavailable. - */ - public static final int HTTP_UNAVAILABLE = 503; - - /** - * HTTP Status-Code 504: Gateway Timeout. - */ - public static final int HTTP_GATEWAY_TIMEOUT = 504; - - /** - * HTTP Status-Code 505: HTTP Version Not Supported. - */ - public static final int HTTP_VERSION = 505; - -} diff --git a/src/main/java/com/contentstack/sdk/FetchAssetsCallback.java b/src/main/java/com/contentstack/sdk/FetchAssetsCallback.java index ee636a4c..84dd56fe 100644 --- a/src/main/java/com/contentstack/sdk/FetchAssetsCallback.java +++ b/src/main/java/com/contentstack/sdk/FetchAssetsCallback.java @@ -2,22 +2,17 @@ import java.util.List; - -public abstract class FetchAssetsCallback extends ResultCallBack{ +public abstract class FetchAssetsCallback implements ResultCallBack { public abstract void onCompletion(ResponseType responseType, List assets, Error error); - public void onRequestFinish(ResponseType responseType, List assets){ + public void onRequestFinish(ResponseType responseType, List assets) { onCompletion(responseType, assets, null); } @Override - void onRequestFail(ResponseType responseType, Error error) { + public void onRequestFail(ResponseType responseType, Error error) { onCompletion(responseType, null, error); } - @Override - public void always() { - - } } diff --git a/src/main/java/com/contentstack/sdk/FetchResultCallback.java b/src/main/java/com/contentstack/sdk/FetchResultCallback.java index 89402241..9605fdad 100644 --- a/src/main/java/com/contentstack/sdk/FetchResultCallback.java +++ b/src/main/java/com/contentstack/sdk/FetchResultCallback.java @@ -1,29 +1,16 @@ package com.contentstack.sdk; - -public abstract class FetchResultCallback extends ResultCallBack{ - - /** - * Triggered after call execution complete. - * @param responseType - * call response from cache or network. - * @param error - * {@link Error} instance if call failed else null. - */ +public abstract class FetchResultCallback implements ResultCallBack { public abstract void onCompletion(ResponseType responseType, Error error); - void onRequestFinish(ResponseType responseType){ + void onRequestFinish(ResponseType responseType) { onCompletion(responseType, null); } @Override - void onRequestFail(ResponseType responseType, Error error) { + public void onRequestFail(ResponseType responseType, Error error) { onCompletion(responseType, error); } - @Override - public void always() { - } - } diff --git a/src/main/java/com/contentstack/sdk/Group.java b/src/main/java/com/contentstack/sdk/Group.java index 1856fc40..f3506695 100644 --- a/src/main/java/com/contentstack/sdk/Group.java +++ b/src/main/java/com/contentstack/sdk/Group.java @@ -1,265 +1,252 @@ package com.contentstack.sdk; -import com.contentstack.sdk.utility.ContentstackUtil; import org.json.JSONArray; import org.json.JSONObject; + import java.util.ArrayList; import java.util.Calendar; -import java.util.HashMap; import java.util.List; - public class Group { - private JSONObject resultJson; - private Stack stackInstance; - + private final JSONObject resultJson; + private final Stack stackInstance; - protected Group(Stack stack, JSONObject jsonObject){ - resultJson = jsonObject; + protected Group(Stack stack, JSONObject jsonObject) { + resultJson = jsonObject; stackInstance = stack; } - /** * Get group representation in json - * @return JSONObject - *

Example :
- *
-     * JSONObject json = group.toJSON();
-     * 
* + * @return JSONObject
+ *
+ * Example :
+ * + *
+     *         JSONObject json = group.toJSON();
+     *         
*/ - public JSONObject toJSON(){ + public JSONObject toJSON() { return resultJson; } - - /** * Get object value for key. + * * @param key field_uid as key. - * @return JSONObject - *

Example :
- *
-     * Object obj = group.get("key");
-     * 
+ * @return JSONObject
+ *
+ * Example :
+ * + *
+     *         Object obj = group.get("key");
+     *         
*/ - public Object get(String key){ - try{ - if(resultJson != null && key != null){ - return resultJson.get(key); - }else{ - return null; - } - }catch (Exception e) { - e.printStackTrace(); + public Object get(String key) { + if (resultJson != null && key != null) { + return resultJson.get(key); + } else { return null; } } - /** * Get string value for key. + * * @param key field_uid as key. - * @return String - *

Example :
- *
-     * String value = group.getString("key");
-     * 
+ * @return String
+ *
+ * Example :
+ * + *
+     *         String value = group.getString("key");
+     *         
*/ - public String getString(String key){ + public String getString(String key) { Object value = get(key); - if(value != null){ - if(value instanceof String){ - return (String) value; - } + if (value != null) { + return (String) value; } return null; } - - - /** * Get boolean value for key. + * * @param key field_uid as key. - * @return boolean true or false - *

Example :
- *
-     * Boolean value = group.getBoolean("key");
-     * 
+ * @return boolean true or false
+ *
+ * Example :
+ * + *
+     *         Boolean value = group.getBoolean("key");
+     *         
*/ - public Boolean getBoolean(String key){ + public Boolean getBoolean(String key) { Object value = get(key); - if(value != null){ - if(value instanceof Boolean){ - return (Boolean) value; - } + if (value != null) { + return (Boolean) value; } return false; } - - - - /** * Get {@link JSONArray} value for key + * * @param key field_uid as key. - * @return JSONArray - *

Example :
- *
-     * JSONArray value = group.getJSONArray("key");
-     * 
+ * @return JSONArray
+ *
+ * Example :
+ * + *
+     *         JSONArray value = group.getJSONArray("key");
+     *         
*/ - public JSONArray getJSONArray(String key){ + public JSONArray getJSONArray(String key) { Object value = get(key); - if(value != null){ - if(value instanceof JSONArray){ - return (JSONArray) value; - } + if (value != null) { + return (JSONArray) value; } return null; } - - - /** * Get {@link JSONObject} value for key * - * @param key - * field_uid as key. - * @return JSONObject - *

Example :
- *
-     * JSONObject value = group.getJSONObject("key");
-     * 
+ * @param key field_uid as key. + * @return JSONObject
+ *
+ * Example :
+ * + *
+     *         JSONObject value = group.getJSONObject("key");
+     *         
*/ - public JSONObject getJSONObject(String key){ + public JSONObject getJSONObject(String key) { Object value = get(key); - if(value != null){ - if(value instanceof JSONObject){ - return (JSONObject) value; - } + if (value != null) { + return (JSONObject) value; } return null; } - - - /** * Get {@link JSONObject} value for key + * * @param key field_uid as key. - * @return Number - *

Example :
- *
-     * JSONObject value = group.getJSONObject("key");
-     * 
+ * @return Number
+ *
+ * Example :
+ * + *
+     *         JSONObject value = group.getJSONObject("key");
+     *         
*/ - public Number getNumber(String key){ + public Number getNumber(String key) { Object value = get(key); - if(value != null){ - if(value instanceof Number){ - return (Number) value; - } + if (value != null) { + return (Number) value; } return null; } - - - /** * Get integer value for key + * * @param key field_uid as key. - * @return int - *

Example :
- *
-     * int value = group.getInt("key");
-     * 
+ * @return int
+ *
+ * Example :
+ * + *
+     *         int value = group.getInt("key");
+     *         
*/ - public int getInt(String key){ + public int getInt(String key) { Number value = getNumber(key); - if(value != null){ + if (value != null) { return value.intValue(); } return 0; } - - - /** * Get integer value for key + * * @param key field_uid as key. - * @return float - *

Example :
- *
-     * float value = group.getFloat("key");
-     * 
+ * @return float
+ *
+ * Example :
+ * + *
+     *         float value = group.getFloat("key");
+     *         
*/ - public float getFloat(String key){ + public float getFloat(String key) { Number value = getNumber(key); - if(value != null){ + if (value != null) { return value.floatValue(); } - return (float) 0; + return 0; } - - /** * Get double value for key * - * @param key - * field_uid as key. - * @return double - *

Example :
- *
-     * double value = group.getDouble("key");
-     * 
+ * @param key field_uid as key. + * @return double
+ *
+ * Example :
+ * + *
+     *         double value = group.getDouble("key");
+     *         
*/ - public double getDouble(String key){ + public double getDouble(String key) { Number value = getNumber(key); - if(value != null){ + if (value != null) { return value.doubleValue(); } - return (double) 0; + return 0; } - /** * Get long value for key + * * @param key field_uid as key. - * @return long - *

Example :
- *
-     * long value = group.getLong("key");
-     * 
+ * @return long
+ *
+ * Example :
+ * + *
+     *         long value = group.getLong("key");
+     *         
*/ - public long getLong(String key){ + public long getLong(String key) { Number value = getNumber(key); - if(value != null){ + if (value != null) { return value.longValue(); } - return (long) 0; + return 0; } /** * Get short value for key + * * @param key field_uid as key. - * @return short - *

Example :
- *
-     * short value = group.getShort("key");
-     * 
+ * @return short
+ *
+ * Example :
+ * + *
+     *         short value = group.getShort("key");
+     *         
*/ - public short getShort(String key){ + public short getShort(String key) { Number value = getNumber(key); - if(value != null){ + if (value != null) { return value.shortValue(); } return (short) 0; @@ -267,57 +254,61 @@ public short getShort(String key){ /** * Get {@link Calendar} value for key + * * @param key field_uid as key. - * @return {@link java.util.Date} - *

Example :
- *
-     * Calendar value = group.getDate("key");
-     * 
+ * @return {@link java.util.Date}
+ *
+ * Example :
+ * + *
+     *         Calendar value = group.getDate("key");
+     *         
*/ - public Calendar getDate(String key){ + public Calendar getDate(String key) { try { String value = getString(key); - return ContentstackUtil.parseDate(value, null); + return Constants.parseDate(value, null); } catch (Exception e) { e.printStackTrace(); } return null; } - - /** * Get an asset from the group + * * @param key field_uid as key. - * @return Asset object - *

Example :
- *
-     * Asset asset = group.getAsset("key");
-     * 
+ * @return Asset object
+ *
+ * Example :
+ * + *
+     *         Asset asset = group.getAsset("key");
+     *         
*/ - public Asset getAsset(String key){ - + public Asset getAsset(String key) { JSONObject assetObject = getJSONObject(key); return stackInstance.asset().configure(assetObject); } - - /** * Get an assets from the group. This works with multiple true fields - * @param key field_uid as key. - *

Example :
- *
-     * {@code List asset = group.getAssets("key"); }
-     * @return ArrayList of {@link Asset}
-     * 
+ * + * @param key field_uid as key.
+ *
+ * Example :
+ * + *
+     *              {@code List asset = group.getAssets("key"); }
+     *              @return ArrayList of {@link Asset}
+     *            
*/ - public List getAssets(String key){ + public List getAssets(String key) { List assets = new ArrayList<>(); JSONArray assetArray = getJSONArray(key); for (int i = 0; i < assetArray.length(); i++) { - if(assetArray.opt(i) instanceof JSONObject){ + if (assetArray.opt(i) instanceof JSONObject) { Asset asset = stackInstance.asset().configure(assetArray.optJSONObject(i)); assets.add(asset); } @@ -325,74 +316,72 @@ public List getAssets(String key){ return assets; } - /** * Get a group from the group. - * @param key field_uid as key. - *

Example :
- *
-     * Group innerGroup = group.getGroup("key");
-     * @return Group object
-     * 
+ * + * @param key field_uid as key.
+ *
+ * Example :
+ * + *
+     *              Group innerGroup = group.getGroup("key");            @return Group
+     *         object
+     *            
+ * + * @return the group */ - public Group getGroup(String key){ - if(!key.isEmpty() && resultJson.has(key) && resultJson.opt(key) instanceof JSONObject ){ + public Group getGroup(String key) { + if (!key.isEmpty() && resultJson.has(key) && resultJson.opt(key) instanceof JSONObject) { return new Group(stackInstance, resultJson.optJSONObject(key)); } return null; } - - /** * Get a list of group from the group. *

* Note :- This will work when group is multiple true. - * @param key field_uid as key. - *

Example :
- *

-     * Group innerGroup = group.getGroups("key");
-     * @return List of {@link Group}
-     * 
+ * + * @param key field_uid as key.
+ *
+ * Example :
+ * + *
+     *              Group innerGroup = group.getGroups("key");
+     *         @return List of {@link Group}
+     *            
*/ - public List getGroups(String key){ - - if(!key.isEmpty() && resultJson.has(key) && resultJson.opt(key) instanceof JSONArray ){ + public List getGroups(String key) { + List groupList = new ArrayList<>(); + if (!key.isEmpty() && resultJson.has(key) && resultJson.opt(key) instanceof JSONArray) { JSONArray array = resultJson.optJSONArray(key); - List groupList = new ArrayList<>(); - - for (int i = 0; i < array.length(); i++) { - if(array.opt(i) instanceof JSONObject){ - Group group = new Group(stackInstance, array.optJSONObject(i)); - groupList.add(group); - } - } - - return groupList; + array.forEach(model -> { + JSONObject newModel = (JSONObject) model; + Group group = new Group(stackInstance, newModel); + groupList.add(group); + }); } - return null; + return groupList; } - - /** * Get value for the given reference key. - * @param refKey key of a reference field. + * + * @param refKey key of a reference field. * @param refContentType class uid. - * @return {@link ArrayList} of {@link Entry} instances. - * Also specified contentType value will be set as class uid for all {@link Entry} instance. + * @return {@link ArrayList} of {@link Entry} instances. Also specified + * contentType value will be set as class uid for all {@link Entry} + * instance. */ public ArrayList getAllEntries(String refKey, String refContentType) { + ArrayList entryContainer = new ArrayList<>(); try { - if (resultJson != null) { + if (resultJson != null) { if (resultJson.get(refKey) instanceof JSONArray) { - int count = ((JSONArray) resultJson.get(refKey)).length(); - ArrayList builtObjectList = new ArrayList(); for (int i = 0; i < count; i++) { - - EntryModel model = new EntryModel(((JSONArray) resultJson.get(refKey)).getJSONObject(i), null, false, false, true); + EntryModel model = new EntryModel(((JSONArray) resultJson.get(refKey)).getJSONObject(i)); Entry entryInstance = null; try { entryInstance = stackInstance.contentType(refContentType).entry(); @@ -400,27 +389,19 @@ public ArrayList getAllEntries(String refKey, String refContentType) { entryInstance = new Entry(refContentType); e.printStackTrace(); } - entryInstance.setUid(model.entryUid); - entryInstance.ownerEmailId = model.ownerEmailId; - entryInstance.ownerUid = model.ownerUid; - if(model.ownerMap != null) { - entryInstance.owner = new HashMap<>(model.ownerMap); - } + entryInstance.setUid(model.uid); entryInstance.resultJson = model.jsonObject; entryInstance.setTags(model.tags); - - builtObjectList.add(entryInstance); - model = null; + entryContainer.add(entryInstance); } - return builtObjectList; + return entryContainer; } } } catch (Exception e) { e.printStackTrace(); - return null; + return entryContainer; } - return null; + return entryContainer; } - } diff --git a/src/main/java/com/contentstack/sdk/INotifyClass.java b/src/main/java/com/contentstack/sdk/INotifyClass.java index 662be255..82bfab3c 100644 --- a/src/main/java/com/contentstack/sdk/INotifyClass.java +++ b/src/main/java/com/contentstack/sdk/INotifyClass.java @@ -1,9 +1,12 @@ package com.contentstack.sdk; + import org.json.JSONObject; import java.util.List; public interface INotifyClass { - public void getResult(Object object, String controller); - public void getResultObject(List object, JSONObject jsonObject, boolean isSingleEntry); + + void getResult(Object object, String controller); + + void getResultObject(List object, JSONObject jsonObject, boolean isSingleEntry); } diff --git a/src/main/java/com/contentstack/sdk/IRequestModelHTTP.java b/src/main/java/com/contentstack/sdk/IRequestModelHTTP.java index eb2b2791..717091bd 100644 --- a/src/main/java/com/contentstack/sdk/IRequestModelHTTP.java +++ b/src/main/java/com/contentstack/sdk/IRequestModelHTTP.java @@ -3,7 +3,10 @@ import org.json.JSONObject; public interface IRequestModelHTTP { - public void sendRequest(); - public void onRequestFailed(JSONObject error, int statusCode, ResultCallBack callBackObject); - public void onRequestFinished(CSHttpConnection request); + + void sendRequest(); + + void onRequestFailed(JSONObject error, int statusCode, ResultCallBack callBackObject); + + void onRequestFinished(CSHttpConnection request); } diff --git a/src/main/java/com/contentstack/sdk/IURLRequestHTTP.java b/src/main/java/com/contentstack/sdk/IURLRequestHTTP.java index 9d2081d4..607ad0f8 100644 --- a/src/main/java/com/contentstack/sdk/IURLRequestHTTP.java +++ b/src/main/java/com/contentstack/sdk/IURLRequestHTTP.java @@ -1,37 +1,29 @@ package com.contentstack.sdk; -import com.contentstack.sdk.utility.CSAppConstants; + import org.json.JSONObject; + import java.util.LinkedHashMap; public interface IURLRequestHTTP { - public void send(); - - public void setHeaders(LinkedHashMap headers); - - public LinkedHashMap getHeaders(); - - public void setRequestMethod(CSAppConstants.RequestMethod requestMethod); - - public CSAppConstants.RequestMethod getRequestMethod(); - - public JSONObject getResponse(); + void send(); - public void setInfo(String info); + LinkedHashMap getHeaders(); - public String getInfo(); + void setHeaders(LinkedHashMap headers); - public void setController(String controller); + JSONObject getResponse(); - public String getController(); + String getInfo(); - public void setCallBackObject(ResultCallBack builtResultCallBackObject); + void setInfo(String info); - public ResultCallBack getCallBackObject(); + String getController(); - public void setTreatDuplicateKeysAsArrayItems(boolean treatDuplicateKeysAsArrayItems); + void setController(String controller); - public boolean getTreatDuplicateKeysAsArrayItems(); + ResultCallBack getCallBackObject(); + void setCallBackObject(ResultCallBack builtResultCallBackObject); } diff --git a/src/main/java/com/contentstack/sdk/Language.java b/src/main/java/com/contentstack/sdk/Language.java deleted file mode 100644 index 4efee11b..00000000 --- a/src/main/java/com/contentstack/sdk/Language.java +++ /dev/null @@ -1,286 +0,0 @@ -package com.contentstack.sdk; - - -/** - * Language - * @deprecated - * This Enum is no longer acceptable to apply language. - *

Use {@link Entry entry.setLocale("en-us")} instead. - */ -@Deprecated -public enum Language { - - AFRIKAANS_SOUTH_AFRICA, - - ALBANIAN_ALBANIA, - - ARABIC_ALGERIA, - - ARABIC_BAHRAIN, - - ARABIC_EGYPT, - - ARABIC_IRAQ, - - ARABIC_JORDAN, - - ARABIC_KUWAIT, - - ARABIC_LEBANON, - - ARABIC_LIBYA, - - ARABIC_MOROCCO, - - ARABIC_OMAN, - - ARABIC_QATAR, - - ARABIC_SAUDI_ARABIA, - - ARABIC_SYRIA, - - ARABIC_TUNISIA, - - ARABIC_UNITED_ARAB_EMIRATES, - - ARABIC_YEMEN, - - ARMENIAN_ARMENIA, - - AZERI_CYRILLIC_ARMENIA, - - AZERI_LATIN_AZERBAIJAN, - - BASQUE_BASQUE, - - BELARUSIAN_BELARUS, - - BULGARIAN_BULGARIA, - - CATALAN_CATALAN, - - CHINESE_CHINA, - - CHINESE_HONG_KONG_SAR, - - CHINESE_MACUS_SAR, - - CHINESE_SINGAPORE, - - CHINESE_TAIWAN, - - CHINESE_SIMPLIFIED, - - CHINESE_TRADITIONAL, - - CROATIAN_CROATIA, - - CZECH_CZECH_REPUBLIC, - - DANISH_DENMARK, - - DHIVEHI_MALDIVES, - - DUTCH_BELGIUM, - - DUTCH_NETHERLANDS, - - ENGLISH_AUSTRALIA, - - ENGLISH_BELIZE, - - ENGLISH_CANADA, - - ENGLISH_CARIBBEAN, - - ENGLISH_IRELAND, - - ENGLISH_JAMAICA, - - ENGLISH_NEW_ZEALAND, - - ENGLISH_PHILIPPINES, - - ENGLISH_SOUTH_AFRICA, - - ENGLISH_TRINIDAD_AND_TOBAGO, - - ENGLISH_UNITED_KINGDOM, - - ENGLISH_UNITED_STATES, - - ENGLISH_ZIMBABWE, - - ESTONIAN_ESTONIA, - - FAROESE_FAROE_ISLANDS, - - FARSI_IRAN, - - FINNISH_FINLAND, - - FRENCH_BELGIUM, - - FRENCH_CANADA, - - FRENCH_FRANCE, - - FRENCH_LUXEMBOURG, - - FRENCH_MONACO, - - FRENCH_SWITZERLAND, - - GALICIAN_GALICIAN, - - GEORGIAN_GEORGIA, - - GERMAN_AUSTRIA, - - GERMAN_GERMANY, - - GERMAN_LIENCHTENSTEIN, - - GERMAN_LUXEMBOURG, - - GERMAN_SWITZERLAND, - - GREEK_GREECE, - - GUJARATI_INDIA, - - HEBREW_ISRAEL, - - HINDI_INDIA, - - HUNGARIAN_HUNGARY, - - ICELANDIC_ICELAND, - - INDONESIAN_INDONESIA, - - ITALIAN_ITALY, - - ITALIAN_SWITZERLAND, - - JAPANESE_JAPAN, - - KANNADA_INDIA, - - KAZAKH_KAZAKHSTAN, - - KONKANI_INDIA, - - KOREAN_KOREA, - - KYRGYZ_KAZAKHSTAN, - - LATVIAN_LATVIA, - - LITHUANIAN_LITHUANIA, - - MACEDONIAN_FYROM, - - MALAY_BRUNEI, - - MALAY_MALAYSIA, - - MARATHI_INDIA, - - MONGOLIAN_MONGOLIA, - - NORWEGIAN_BOKMAL_NORWAY, - - NORWEGIAN_NYNORSK_NORWAY, - - POLISH_POLAND, - - PORTUGUESE_BRAZIL, - - PORTUGUESE_PORTUGAL, - - PUNJABI_INDIA, - - ROMANIAN_ROMANIA, - - RUSSIAN_RUSSIA, - - SANSKRIT_INDIA, - - SERBIAN_CYRILLIC_SERBIA, - - SERBIAN_LATIN_SERBIA, - - SLOVAK_SLOVAKIA, - - SLOVENIAN_SLOVENIAN, - - SPANISH_ARGENTINA, - - SPANISH_BOLIVIA, - - SPANISH_CHILE, - - SPANISH_COLOMBIA, - - SPANISH_COSTA_RICA, - - SPANISH_DOMINICAN_REPUBLIC, - - SPANISH_ECUADOR, - - SPANISH_ELSALVADOR, - - SPANISH_GUATEMALA, - - SPANISH_HONDURAS, - - SPANISH_MEXICO, - - SPANISH_NICARAGUA, - - SPANISH_PANAMA, - - SPANISH_PARAGUAY, - - SPANISH_PERU, - - SPANISH_PUERTO_RICO, - - SPANISH_SPAIN, - - SPANISH_URUGUAY, - - SPANISH_VENEZUELA, - - SWAHILI_KENYA, - - SWEDISH_FINLAND, - - SWEDISH_SWEDEN, - - SYRIAC_SYRIA, - - TAMIL_INDIA, - - TATAR_RUSSIA, - - TELUGU_INDIA, - - THAI_THAILAND, - - TURKISH_TURKEY, - - UKRAINIAN_UKRAINE, - - URDU_PAKISTAN, - - UZBEK_CYRILLIC_UZBEKISTAN, - - UZBEK_LATIN_UZEBEKISTAN, - - VIETNAMESE_VIETNAM; - -} - diff --git a/src/main/java/com/contentstack/sdk/LanguageCode.java b/src/main/java/com/contentstack/sdk/LanguageCode.java deleted file mode 100644 index 426ba2ef..00000000 --- a/src/main/java/com/contentstack/sdk/LanguageCode.java +++ /dev/null @@ -1,284 +0,0 @@ -package com.contentstack.sdk; - -/** - * LanguageCode - * @deprecated - * This Enum is no longer acceptable to apply {@link LanguageCode}. - *

Use {@link Entry entry.setLocale("en-us")} instead. - */ -@Deprecated -enum LanguageCode { - - af_za, - - sq_al, - - ar_dz, - - ar_bh, - - ar_eg, - - ar_iq, - - ar_jo, - - ar_kw, - - ar_lb, - - ar_ly, - - ar_ma, - - ar_om, - - ar_qa, - - ar_sa, - - ar_sy, - - ar_tn, - - ar_ae, - - ar_ye, - - hy_am, - - cy_az_az, - - lt_az_az, - - eu_es, - - be_by, - - bg_bg, - - ca_es, - - zh_cn, - - zh_hk, - - zh_mo, - - zh_sg, - - zh_tw, - - zh_chs, - - zh_cht, - - hr_hr, - - cs_cz, - - da_dk, - - div_mv, - - nl_be, - - nl_nl, - - en_au, - - en_bz, - - en_ca, - - en_cb, - - en_ie, - - en_jm, - - en_nz, - - en_ph, - - en_za, - - en_tt, - - en_gb, - - en_us, - - en_zw, - - et_ee, - - fo_fo, - - fa_ir, - - fi_fi, - - fr_be, - - fr_ca, - - fr_fr, - - fr_lu, - - fr_mc, - - fr_ch, - - gl_es, - - ka_ge, - - de_at, - - de_de, - - de_li, - - de_lu, - - de_ch, - - el_gr, - - gu_in, - - he_il, - - hi_in, - - hu_hu, - - is_is, - - id_id, - - it_it, - - it_ch, - - ja_jp, - - kn_in, - - kk_kz, - - kok_in, - - ko_kr, - - ky_kz, - - lv_lv, - - lt_lt, - - mk_mk, - - ms_bn, - - ms_my, - - mr_in, - - mn_mn, - - nb_no, - - nn_no, - - pl_pl, - - pt_br, - - pt_pt, - - pa_in, - - ro_ro, - - ru_ru, - - sa_in, - - cy_sr_sp, - - lt_sr_sp, - - sk_sk, - - sl_si, - - es_ar, - - es_bo, - - es_cl, - - es_co, - - es_cr, - - es_do, - - es_ec, - - es_sv, - - es_gt, - - es_hn, - - es_mx, - - es_ni, - - es_pa, - - es_py, - - es_pe, - - es_pr, - - es_es, - - es_uy, - - es_ve, - - sw_ke, - - sv_fi, - - sv_se, - - syr_sy, - - ta_in, - - tt_ru, - - te_in, - - th_th, - - tr_tr, - - uk_ua, - - ur_pk, - - cy_uz_uz, - - lt_uz_uz, - - vi_vn; - -} diff --git a/src/main/java/com/contentstack/sdk/Query.java b/src/main/java/com/contentstack/sdk/Query.java index 5309e8a8..e6345d67 100644 --- a/src/main/java/com/contentstack/sdk/Query.java +++ b/src/main/java/com/contentstack/sdk/Query.java @@ -1,46 +1,42 @@ package com.contentstack.sdk; -import com.contentstack.sdk.utility.CSAppConstants; -import com.contentstack.sdk.utility.CSController; + +import org.jetbrains.annotations.NotNull; import org.json.JSONArray; -import org.json.JSONException; import org.json.JSONObject; + import java.util.*; import java.util.logging.Logger; +import static com.contentstack.sdk.Constants.*; /** - * Contentstack provides certain queries that you can use to fetch - * filtered results. You can use queries for Entries and Assets API requests. + * Contentstack provides certain queries that you can use to fetch filtered + * results. You can use queries for Entries and Assets API requests. */ - public class Query implements INotifyClass { private static final Logger logger = Logger.getLogger(Query.class.getSimpleName()); protected ContentType contentTypeInstance = null; - protected LinkedHashMap formHeader = null; - private JSONObject mainJSON = null; - private String formName = null; - protected JSONObject urlQueries = null; - private LinkedHashMap localHeader = null; - private QueryResultsCallBack queryResultCallback; - private SingleQueryResultCallback singleQueryResultCallback; - private JSONObject queryValueJSON = null; - private JSONObject queryValue = null; - private JSONArray objectUidForInclude = null; - private JSONArray objectUidForExcept = null; - private JSONArray objectUidForOnly = null; + protected LinkedHashMap headers = null; + protected JSONObject urlQueries; + protected JSONObject mainJSON; + protected String contentTypeUid; + protected QueryResultsCallBack queryResultCallback; + protected SingleQueryResultCallback singleQueryResultCallback; + protected JSONObject queryValueJSON; + protected JSONObject queryValue; + protected JSONArray objectUidForInclude = null; + protected JSONArray objectUidForExcept = null; + protected JSONArray objectUidForOnly = null; private boolean isJsonProper = true; private String errorString; - private HashMap errorHashMap; private JSONObject onlyJsonObject; private JSONObject exceptJsonObject; - protected Query(String formName) { - this.formName = formName; - this.localHeader = new LinkedHashMap<>(); + this.contentTypeUid = formName; this.urlQueries = new JSONObject(); this.queryValue = new JSONObject(); this.queryValueJSON = new JSONObject(); @@ -51,81 +47,82 @@ protected void setContentTypeInstance(ContentType contentTypeInstance) { this.contentTypeInstance = contentTypeInstance; } - /** - * To set headers for Built.io Contentstack rest calls. - *
+ * To set headers for Built.io Contentstack rest calls.
* Scope is limited to this object and followed classes. * * @param key header name. - * @param value header value against given header name. - *

Example :
- *

-     * Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     * Query csQuery = stack.contentType("contentType_name").query();
- * csQuery.setHeader("custom_key", "custom_value"); - *
+ * @param value header value against given header name.
+ * + * + *
+ *
+ * Example :
+ * + *
+     *              Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment");
+     *              Query csQuery = stack.contentType("contentTypeUid").query();
+ * csQuery.setHeader("custom_key", "custom_value"); + *
*/ - public void setHeader(String key, String value) { + public void setHeader(@NotNull String key, @NotNull String value) { if (!key.isEmpty() && !value.isEmpty()) { - localHeader.put(key, value); + this.headers.put(key, value); } } - /** * Remove header key @param key custom_header_key * - * @param key {@link String} - *

Example :
- *
-     * Stack stack = Contentstack..stack( "APIKey", "deliveryToken", "environment_name");
-     * Query csQuery = stack.contentType("contentType_name").query();
- * csQuery.removeHeader("custom_key"); - *
+ * @param key {@link String}
+ * + *
+ *
+ * Example :
+ * + *
+     *            Stack stack = Contentstack..stack( "apiKey", "deliveryToken", "environment");
+     *            Query csQuery = stack.contentType("contentTypeUid").query();
+ * csQuery.removeHeader("custom_key"); + *
*/ - public void removeHeader(String key) { + public void removeHeader(@NotNull String key) { if (!key.isEmpty()) { - localHeader.remove(key); + this.headers.remove(key); } } public String getContentType() { - return contentTypeInstance.contentTypeName; + return contentTypeInstance.contentTypeUid; } - /** - * Add a constraint to fetch all entries that contains given value against specified key + * Add a constraint to fetch all entries that contains given value against + * specified key * * @param key field uid. * @param value field value which get 'included' from the response. * @return {@link Query} object, so you can chain this call. - *

- * Note : for group field provide key in a "key.groupFieldUid" format. - *

Example :
- *

-     * Stack stack = Contentstack..stack( "APIKey", "deliveryToken", "environment_name");
-     * Query csQuery = stack.contentType("contentType_name").query();
-     * csQuery.where("uid", "bltf4fbsample851db");
-     * 
+ *

+ * Note : for group field provide key in a + * "key.groupFieldUid" format.
+ * + *
+ *
+ * Example :
+ * + *

+     *          Stack stack = Contentstack..stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+     *          csQuery.where("uid", "entry_uid");
+     *         
*/ - public Query where(String key, Object value) { - try { - if (key != null && value != null) { - queryValueJSON.put(key, value); - } else { - throwException("where", CSAppConstants.ErrorMessage_QueryFilterException, null); - } - } catch (Exception e) { - throwException("where", CSAppConstants.ErrorMessage_QueryFilterException, e); - } - + public Query where(@NotNull String key, Object value) { + queryValueJSON.put(key, value); return this; } - /** * Add a custom query against specified key. * @@ -133,379 +130,323 @@ public Query where(String key, Object value) { * @param value value. * @return {@link Query} object, so you can chain this call. * - *

Example :
- *
-     * Stack stack = Contentstack..stack( "APIKey", "deliveryToken", "environment_name");
-     * Query csQuery = stack.contentType("contentType_name").query();
-     * csQuery.addQuery("query_param_key", "query_param_value");
-     * 
+ *
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack..stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+     *          csQuery.addQuery("query_param_key", "query_param_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); - } - } catch (Exception e) { - throwException("and", CSAppConstants.ErrorMessage_QueryFilterException, e); + public Query addQuery(@NotNull String key, String value) { + if (value != null) { + urlQueries.put(key, value); } return this; } - /** * Remove provided query key from custom query if exist. * * @param key Query name to remove. - * @return {@linkplain Query} object, so you can chain this call. - *

Example :
- *
-     * projectQuery.removeQuery("Query_Key");
-     * 
+ * @return {@linkplain Query} object, so you can chain this call.
+ * + *
+ *
+ * Example :
+ * + *
+     *         projectQuery.removeQuery("Query_Key");
+     *         
*/ - public Query removeQuery(String key) { - try { - if (urlQueries.has(key)) { - urlQueries.remove(key); - } - } catch (Exception e) { - throwException("and", CSAppConstants.ErrorMessage_QueryFilterException, e); + public Query removeQuery(@NotNull String key) { + if (urlQueries.has(key)) { + urlQueries.remove(key); } return this; } - /** * Combines all the queries together using AND operator * - * @param queryObjects list of {@link Query} instances on which AND query executes. + * @param queryObjects list of {@link Query} instances on which AND query + * executes. * @return {@link Query} object, so you can chain this call. * - *

Example ;
- *
-     * Stack stack = Contentstack..stack( "APIKey", "deliveryToken", "environment_name");
-     * Query csQuery = stack.contentType("contentType_name").query();
-     *
-     * Query query = projectClass.query();
-     * query.where('username','something');
-     *
-     * Query subQuery = projectClass.query();
-     * subQuery.where('email_address','something@email.com');
-     *
-     * ArrayList<Query> array = new ArrayList<Query>();
- * array.add(query); - * array.add(subQuery);
- * projectQuery.and(array); - *
+ *
+ *
+ * Example ;
+ * + *
+     *          Stack stack = Contentstack..stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+     *
+     *          Query query = projectClass.query();
+     *          query.where('username','something');
+     *
+     *          Query subQuery = projectClass.query();
+     *          subQuery.where('email_address','something@email.com');
+     *
+     *          ArrayList<Query> array = new ArrayList<Query>();
+ * array.add(query); + * array.add(subQuery);
+ * projectQuery.and(array); + *
*/ - public Query and(ArrayList queryObjects) { - if (queryObjects != null && queryObjects.size() > 0) { - try { - JSONArray orValueJson = new JSONArray(); - int count = queryObjects.size(); - - for (int i = 0; i < count; i++) { - orValueJson.put(queryObjects.get(i).queryValueJSON); - } - queryValueJSON.put("$and", orValueJson); - - } catch (Exception e) { - throwException("and", CSAppConstants.ErrorMessage_QueryFilterException, e); - } + public Query and(@NotNull ArrayList queryObjects) { + if (!queryObjects.isEmpty()) { + JSONArray orValueJson = new JSONArray(); + queryObjects.forEach(obj -> orValueJson.put(obj.queryValueJSON)); + queryValueJSON.put("$and", orValueJson); } else { - throwException("and", CSAppConstants.ErrorMessage_QueryFilterException, null); + throwException("and", "Can not process with blank query objects", null); } - return this; } - /** * Add a constraint to fetch all entries which satisfy any queries. * - * @param queryObjects list of {@link Query} instances on which OR query executes. + * @param queryObjects list of {@link Query} instances on which OR query + * executes. * @return {@link Query} object, so you can chain this call. * - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
-     *
-     *     Query query = projectClass.query();
-     *     query.where('username','something');
-     *
-     *     Query subQuery = projectClass.query();
-     *     subQuery.where('email_address','something@email.com');
-     *
-     *     ArrayList<Query> array = new ArrayList<Query>();
-     *     array.add(query);
-     *     array.add(subQuery);
- * csQuery.or(array); - *
+ *
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+     *
+     *          Query query = projectClass.query();
+     *          query.where('username','something');
+     *
+     *          Query subQuery = projectClass.query();
+     *          subQuery.where('email_address','something@email.com');
+     *
+     *          ArrayList<Query> array = new ArrayList<Query>();
+     *          array.add(query);
+     *          array.add(subQuery);
+ * csQuery.or(array); + *
*/ public Query or(ArrayList queryObjects) { - if (queryObjects != null && queryObjects.size() > 0) { + if (queryObjects != null && !queryObjects.isEmpty()) { try { JSONArray orValueJson = new JSONArray(); - int count = queryObjects.size(); - - for (int i = 0; i < count; i++) { - orValueJson.put(queryObjects.get(i).queryValueJSON); + for (Query queryObject : queryObjects) { + orValueJson.put(queryObject.queryValueJSON); } - queryValueJSON.put("$or", orValueJson); } catch (Exception e) { - throwException("or", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("or", Constants.QUERY_EXCEPTION, e); } - } else { - throwException("or", CSAppConstants.ErrorMessage_QueryFilterException, null); } return this; } - /** - * Add a constraint to the query that requires a particular key entry to be less than the provided value. + * Add a constraint to the query that requires a particular key entry to be less + * than the provided value. * * @param key the key to be constrained. * @param value the value that provides an upper bound. - * @return {@link Query} object, so you can chain this call. - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
-     *     csQuery.lessThan("due_date", "2013-06-25T00:00:00+05:30");
-     * 
+ * @return {@link Query} object, so you can chain this call.
+ * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Query csQuery = stack.contentType("contentTypeUid").query();
+     *         csQuery.lessThan("due_date", "2013-06-25T00:00:00+05:30");
+     *         
*/ - public Query lessThan(String key, Object value) { - if (key != null && value != null) { - try { - if (queryValueJSON.isNull(key)) { - if (queryValue.length() > 0) { - queryValue = new JSONObject(); - } - queryValue.put("$lt", value); - queryValueJSON.put(key, queryValue); - } else if (queryValueJSON.has(key)) { - queryValue.put("$lt", value); - queryValueJSON.put(key, queryValue); - } - } catch (Exception e) { - throwException("lessThan", CSAppConstants.ErrorMessage_QueryFilterException, e); + public Query lessThan(@NotNull String key, @NotNull Object value) { + if (queryValueJSON.isNull(key)) { + if (queryValue.length() > 0) { + queryValue = new JSONObject(); } - } else { - throwException("lessThan", CSAppConstants.ErrorMessage_QueryFilterException, null); + queryValue.put("$lt", value); + queryValueJSON.put(key, queryValue); + } else if (queryValueJSON.has(key)) { + queryValue.put("$lt", value); + queryValueJSON.put(key, queryValue); } - return this; } - /** - * Add a constraint to the query that requires a particular key entry to be less than or equal to the provided value. + * Add a constraint to the query that requires a particular key entry to be less + * than or equal to the provided value. * * @param key The key to be constrained * @param value The value that must be equalled. * @return {@link Query} object, so you can chain this call. * - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
-     *     csQuery.lessThanOrEqualTo("due_date", "2013-06-25T00:00:00+05:30");
-     * 
+ *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Query csQuery = stack.contentType("contentTypeUid").query();
+     *         csQuery.lessThanOrEqualTo("due_date", "2013-06-25T00:00:00+05:30");
+     *         
*/ - public Query lessThanOrEqualTo(String key, Object value) { - - if (key != null && value != null) { - - try { - if (queryValueJSON.isNull(key)) { - if (queryValue.length() > 0) { - queryValue = new JSONObject(); - } - queryValue.put("$lte", value); - queryValueJSON.put(key, queryValue); - } else if (queryValueJSON.has(key)) { - queryValue.put("$lte", value); - queryValueJSON.put(key, queryValue); - } - } catch (Exception e) { - throwException("lessThanOrEqualTo", CSAppConstants.ErrorMessage_QueryFilterException, e); + public Query lessThanOrEqualTo(@NotNull String key, Object value) { + if (queryValueJSON.isNull(key)) { + if (queryValue.length() > 0) { + queryValue = new JSONObject(); } - } else { - throwException("lessThanOrEqualTo", CSAppConstants.ErrorMessage_QueryFilterException, null); + queryValue.put("$lte", value); + queryValueJSON.put(key, queryValue); + } else if (queryValueJSON.has(key)) { + queryValue.put("$lte", value); + queryValueJSON.put(key, queryValue); } return this; } - /** - * Add a constraint to the query that requires a particular key entry to be greater than the provided value. + * Add a constraint to the query that requires a particular key entry to be + * greater than the provided value. * * @param key The key to be constrained. * @param value The value that provides an lower bound. * @return {@link Query} object, so you can chain this call. * - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
-     *     csQuery.greaterThan("due_date", "2013-06-25T00:00:00+05:30");
-     * 
+ *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Query csQuery = stack.contentType("contentTypeUid").query();
+     *         csQuery.greaterThan("due_date", "2013-06-25T00:00:00+05:30");
+     *         
*/ - public Query greaterThan(String key, Object value) { - - if (key != null && value != null) { - try { - if (queryValueJSON.isNull(key)) { - if (queryValue.length() > 0) { - queryValue = new JSONObject(); - } - queryValue.put("$gt", value); - queryValueJSON.put(key, queryValue); - } else if (queryValueJSON.has(key)) { - queryValue.put("$gt", value); - queryValueJSON.put(key, queryValue); - } - } catch (Exception e) { - throwException("greaterThan", CSAppConstants.ErrorMessage_QueryFilterException, e); + public Query greaterThan(@NotNull String key, Object value) { + if (queryValueJSON.isNull(key)) { + if (queryValue.length() > 0) { + queryValue = new JSONObject(); } - } else { - throwException("greaterThan", CSAppConstants.ErrorMessage_QueryFilterException, null); + queryValue.put("$gt", value); + queryValueJSON.put(key, queryValue); + } else if (queryValueJSON.has(key)) { + queryValue.put("$gt", value); + queryValueJSON.put(key, queryValue); } return this; } - /** - * Add a constraint to the query that requires a particular key entry to be greater than or equal to the provided value. + * Add a constraint to the query that requires a particular key entry to be + * greater than or equal to the provided value. * * @param key The key to be constrained. * @param value The value that provides an lower bound. * @return {@link Query} object, so you can chain this call. * - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
-     *     csQuery.greaterThanOrEqualTo("due_date", "2013-06-25T00:00:00+05:30");
-     * 
+ *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Query csQuery = stack.contentType("contentTypeUid").query();
+     *         csQuery.greaterThanOrEqualTo("due_date", "2013-06-25T00:00:00+05:30");
+     *         
*/ public Query greaterThanOrEqualTo(String key, Object value) { - - if (key != null && value != null) { - try { - if (queryValueJSON.isNull(key)) { - if (queryValue.length() > 0) { - queryValue = new JSONObject(); - } - queryValue.put("$gte", value); - queryValueJSON.put(key, queryValue); - } else if (queryValueJSON.has(key)) { - queryValue.put("$gte", value); - queryValueJSON.put(key, queryValue); - } - } catch (Exception e) { - throwException("greaterThanOrEqualTo", CSAppConstants.ErrorMessage_QueryFilterException, e); + if (queryValueJSON.isNull(key)) { + if (queryValue.length() > 0) { + queryValue = new JSONObject(); } - } else { - throwException("greaterThanOrEqualTo", CSAppConstants.ErrorMessage_QueryFilterException, null); + queryValue.put("$gte", value); + queryValueJSON.put(key, queryValue); + } else if (queryValueJSON.has(key)) { + queryValue.put("$gte", value); + queryValueJSON.put(key, queryValue); } return this; } - /** - * Add a constraint to the query that requires a particular key's - * entry to be not equal to the provided value. + * Add a constraint to the query that requires a particular key's entry to + * be not equal to the provided value. * * @param key The key to be constrained. * @param value The object that must not be equaled. * @return {@link Query} object, so you can chain this call. * - *

Example ;
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
-     *     csQuery.notEqualTo("due_date", "2013-06-25T00:00:00+05:30");
-     * 
+ *
+ *
+ * Example ;
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Query csQuery = stack.contentType("contentTypeUid").query();
+     *         csQuery.notEqualTo("due_date", "2013-06-25T00:00:00+05:30");
+     *         
*/ - public Query notEqualTo(String key, Object value) { - - if (key != null && value != null) { - - try { - if (queryValueJSON.isNull(key)) { - if (queryValue.length() > 0) { - queryValue = new JSONObject(); - } - queryValue.put("$ne", value); - queryValueJSON.put(key, queryValue); - } else if (queryValueJSON.has(key)) { - queryValue.put("$ne", value); - queryValueJSON.put(key, queryValue); - } - } catch (Exception e) { - throwException("notEqualTo", null, e); + public Query notEqualTo(@NotNull String key, Object value) { + if (queryValueJSON.isNull(key)) { + if (queryValue.length() > 0) { + queryValue = new JSONObject(); } - - } else { - throwException("notEqualTo", CSAppConstants.ErrorMessage_QueryFilterException, null); + queryValue.put("$ne", value); + queryValueJSON.put(key, queryValue); + } else if (queryValueJSON.has(key)) { + queryValue.put("$ne", value); + queryValueJSON.put(key, queryValue); } - return this; } - /** - * Add a constraint to the query that requires a particular key's entry to be contained - * in the provided array. + * Add a constraint to the query that requires a particular key's entry to + * be contained in the provided array. * * @param key The key to be constrained. * @param values The possible values for the key's object. - * @return {@link Query} object, so you can chain this call. - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
-     *     csQuery.containedIn("severity", new Object[]{"Show Stopper", "Critical"});
-     * 
+ * @return {@link Query} object, so you can chain this call.
+ * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Query csQuery = stack.contentType("contentTypeUid").query();
+     *         csQuery.containedIn("severity", new Object[] { "Show Stopper", "Critical" });
+     *         
*/ - public Query containedIn(String key, Object[] values) { - - if (key != null && values != null) { - try { - JSONArray valuesArray = new JSONArray(); - int length = values.length; - for (int i = 0; i < length; i++) { - valuesArray.put(values[i]); - } - if (queryValueJSON.isNull(key)) { - if (queryValue.length() > 0) { - queryValue = new JSONObject(); - } - queryValue.put("$in", valuesArray); - queryValueJSON.put(key, queryValue); - } else if (queryValueJSON.has(key)) { - queryValue.put("$in", valuesArray); - queryValueJSON.put(key, queryValue); - } - } catch (Exception e) { - throwException("containedIn", CSAppConstants.ErrorMessage_QueryFilterException, e); + public Query containedIn(@NotNull String key, Object[] values) { + JSONArray valuesArray = new JSONArray(); + int length = values.length; + for (int i = 0; i < length; i++) { + valuesArray.put(values[i]); + } + if (queryValueJSON.isNull(key)) { + if (queryValue.length() > 0) { + queryValue = new JSONObject(); } - } else { - throwException("containedIn", CSAppConstants.ErrorMessage_QueryFilterException, null); + queryValue.put("$in", valuesArray); + queryValueJSON.put(key, queryValue); + } else if (queryValueJSON.has(key)) { + queryValue.put("$in", valuesArray); + queryValueJSON.put(key, queryValue); } - return this; } - /** * Add a constraint to the query that requires a particular key entry's * value not be contained in the provided array. @@ -514,131 +455,113 @@ public Query containedIn(String key, Object[] values) { * @param values The list of values the key object should not be. * @return {@link Query} object, so you can chain this call. * - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
-     *     csQuery.notContainedIn("severity", new Object[]{"Show Stopper", "Critical"});
-     * 
+ * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Query csQuery = stack.contentType("contentTypeUid").query();
+     *         csQuery.notContainedIn("severity", new Object[] { "Show Stopper", "Critical" });
+     *         
*/ - public Query notContainedIn(String key, Object[] values) { - - if (key != null && values != null) { - try { - JSONArray valuesArray = new JSONArray(); - int length = values.length; - for (int i = 0; i < length; i++) { - valuesArray.put(values[i]); - } - if (queryValueJSON.isNull(key)) { - if (queryValue.length() > 0) { - queryValue = new JSONObject(); - } - queryValue.put("$nin", valuesArray); - queryValueJSON.put(key, queryValue); - } else if (queryValueJSON.has(key)) { - queryValue.put("$nin", valuesArray); - queryValueJSON.put(key, queryValue); - } - } catch (Exception e) { - throwException("containedIn", CSAppConstants.ErrorMessage_QueryFilterException, e); + public Query notContainedIn(@NotNull String key, Object[] values) { + JSONArray valuesArray = new JSONArray(); + int length = values.length; + for (int i = 0; i < length; i++) { + valuesArray.put(values[i]); + } + if (queryValueJSON.isNull(key)) { + if (queryValue.length() > 0) { + queryValue = new JSONObject(); } - } else { - throwException("containedIn", CSAppConstants.ErrorMessage_QueryFilterException, null); + queryValue.put("$nin", valuesArray); + queryValueJSON.put(key, queryValue); + } else if (queryValueJSON.has(key)) { + queryValue.put("$nin", valuesArray); + queryValueJSON.put(key, queryValue); } - return this; } - /** * Add a constraint that requires, a specified key exists in response. * * @param key The key to be constrained. * @return {@link Query} object, so you can chain this call. * - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
-     *     csQuery.exists("status");
-     * 
+ *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Query csQuery = stack.contentType("contentTypeUid").query();
+     *         csQuery.exists("status");
+     *         
*/ - public Query exists(String key) { - - if (key != null) { - try { - if (queryValueJSON.isNull(key)) { - if (queryValue.length() > 0) { - queryValue = new JSONObject(); - } - queryValue.put("$exists", true); - queryValueJSON.put(key, queryValue); - } else if (queryValueJSON.has(key)) { - queryValue.put("$exists", true); - queryValueJSON.put(key, queryValue); - } - } catch (Exception e) { - throwException("exists", CSAppConstants.ErrorMessage_QueryFilterException, e); + public Query exists(@NotNull String key) { + if (queryValueJSON.isNull(key)) { + if (queryValue.length() > 0) { + queryValue = new JSONObject(); } - } else { - throwException("exists", CSAppConstants.ErrorMessage_QueryFilterException, null); + queryValue.put(EXISTS, true); + queryValueJSON.put(key, queryValue); + } else if (queryValueJSON.has(key)) { + queryValue.put(EXISTS, true); + queryValueJSON.put(key, queryValue); } return this; } - /** * Add a constraint that requires, a specified key does not exists in response. * * @param key The key to be constrained. - * @return {@link Query} object, so you can chain this call. - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
-     *     csQuery.notExists("status");
-     * 
+ * @return {@link Query} object, so you can chain this call.
+ * + * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Query csQuery = stack.contentType("contentTypeUid").query();
+     *         csQuery.notExists("status");
+     *         
*/ - public Query notExists(String key) { - - if (key != null) { - try { - - if (queryValueJSON.isNull(key)) { - if (queryValue.length() > 0) { - queryValue = new JSONObject(); - } - queryValue.put("$exists", false); - queryValueJSON.put(key, queryValue); - } else if (queryValueJSON.has(key)) { - - queryValue.put("$exists", false); - queryValueJSON.put(key, queryValue); - } - } catch (Exception e) { - throwException("notExists", CSAppConstants.ErrorMessage_QueryFilterException, e); + public Query notExists(@NotNull String key) { + if (queryValueJSON.isNull(key)) { + if (queryValue.length() > 0) { + queryValue = new JSONObject(); } - } else { - throwException("notExists", CSAppConstants.ErrorMessage_QueryFilterException, null); - } + queryValue.put(EXISTS, false); + queryValueJSON.put(key, queryValue); + } else if (queryValueJSON.has(key)) { + queryValue.put(EXISTS, false); + queryValueJSON.put(key, queryValue); + } return this; } - /** * Add a constraint that requires a particular reference key details. * * @param key key that to be constrained. * @return {@link Query} object, so you can chain this call. * - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
-     *     csQuery.includeReference("for_bug");
-     * 
+ *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Query csQuery = stack.contentType("contentTypeUid").query();
+     *         csQuery.includeReference("for_bug");
+     *         
*/ public Query includeReference(String key) { if (objectUidForInclude == null) { @@ -648,891 +571,697 @@ public Query includeReference(String key) { return this; } - /** * Include tags with which to search entries. * * @param tags Comma separated array of tags with which to search entries. - * @return {@link Query} object, so you can chain this call. - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
-     *     csQuery.tags(new String[]{"tag1","tag2"});
-     * 
+ * @return {@link Query} object, so you can chain this call.
+ * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Query csQuery = stack.contentType("contentTypeUid").query();
+     *         csQuery.tags(new String[] { "tag1", "tag2" });
+     *         
*/ - public Query tags(String[] tags) { - try { - if (tags != null) { - - String tagsvalue = null; - int count = tags.length; - for (int i = 0; i < count; i++) { - tagsvalue = tagsvalue + "," + tags[i]; - } - urlQueries.put("tags", tagsvalue); - } else { - throwException("tags", CSAppConstants.ErrorMessage_QueryFilterException, null); - } - } catch (Exception e) { - throwException("tags", CSAppConstants.ErrorMessage_QueryFilterException, e); + public Query tags(@NotNull String[] tags) { + String tagsvalue = null; + int count = tags.length; + for (int i = 0; i < count; i++) { + tagsvalue = tagsvalue + "," + tags[i]; } + urlQueries.put("tags", tagsvalue); return this; } - /** - * Sort the results in ascending order with the given key. - *
+ * Sort the results in ascending order with the given key.
* Sort the returned entries in ascending order of the provided key. * * @param key The key to order by. - * @return {@link Query} object, so you can chain this call. - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
-     *     csQuery.ascending("name");
-     * 
+ * @return {@link Query} object, so you can chain this call.
+ * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Query csQuery = stack.contentType("contentTypeUid").query();
+     *         csQuery.ascending("name");
+     *         
*/ - - public Query ascending(String key) { - if (key != null) { - try { - urlQueries.put("asc", key); - } catch (Exception e) { - throwException("ascending", CSAppConstants.ErrorMessage_QueryFilterException, e); - } - } else { - throwException("ascending", CSAppConstants.ErrorMessage_QueryFilterException, null); - } + public Query ascending(@NotNull String key) { + urlQueries.put("asc", key); return this; } - /** - * Sort the results in descending order with the given key. - *
+ * Sort the results in descending order with the given key.
* Sort the returned entries in descending order of the provided key. * * @param key The key to order by. - * @return {@link Query} object, so you can chain this call. - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
-     *     csQuery.descending("name");
-     * 
+ * @return {@link Query} object, so you can chain this call.
+ * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Query csQuery = stack.contentType("contentTypeUid").query();
+     *         csQuery.descending("name");
+     *         
*/ - public Query descending(String key) { - if (key != null) { - try { - urlQueries.put("desc", key); - } catch (Exception e) { - throwException("descending", CSAppConstants.ErrorMessage_QueryFilterException, e); - } - } else { - throwException("descending", CSAppConstants.ErrorMessage_QueryFilterException, null); - } + public Query descending(@NotNull String key) { + urlQueries.put("desc", key); return this; } - /** - * Specifies list of field uids that would be 'excluded' from the response. + * Specifies list of field uids that would be 'excluded' from the + * response. * - * @param fieldUid field uid which get 'excluded' from the response. + * @param fieldUid field uid which get 'excluded' from the response. * @return {@link Query} object, so you can chain this call. * - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
- * ArrayList<String> array = new ArrayList<String>(); - * array.add("name"); - * array.add("description");
- * csQuery.except(array); - *
+ * + *
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+ * ArrayList<String> array = new ArrayList<String>(); + * array.add("name"); + * array.add("description");
+ * csQuery.except(array); + *
*/ - public Query except(ArrayList fieldUid) { - try { - if (fieldUid != null && fieldUid.size() > 0) { - if (objectUidForExcept == null) { - objectUidForExcept = new JSONArray(); - } - int count = fieldUid.size(); - for (int i = 0; i < count; i++) { - objectUidForExcept.put(fieldUid.get(i)); - } - } else { - throwException("except", CSAppConstants.ErrorMessage_QueryFilterException, null); + public Query except(@NotNull ArrayList fieldUid) { + if (!fieldUid.isEmpty()) { + if (objectUidForExcept == null) { + objectUidForExcept = new JSONArray(); + } + for (String s : fieldUid) { + objectUidForExcept.put(s); } - } catch (Exception e) { - throwException("except", CSAppConstants.ErrorMessage_QueryFilterException, e); } return this; } - /** - * Specifies list of field uids that would be 'excluded' from the response. - * - * @param fieldUids field uid which get 'excluded' from the response. - * @return {@link Query} object, so you can chain this call. - *

Example :
- *
-     *  Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *  Query csQuery = stack.contentType("contentType_name").query();
- * csQuery.except(new String[]{"name", "description"}); - *
+ * Specifies list of field uids that would be 'excluded' from the + * response. + * + * @param fieldIds field uid which get 'excluded' from the response. + * @return {@link Query} object, so you can chain this call.
+ * + *
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+ * csQuery.except(new String[]{"name", "description"}); + *
*/ - public Query except(String[] fieldUids) { - try { - if (fieldUids != null && fieldUids.length > 0) { - if (objectUidForExcept == null) { - objectUidForExcept = new JSONArray(); - } - int count = fieldUids.length; - for (int i = 0; i < count; i++) { - objectUidForExcept.put(fieldUids[i]); - } - } else { - throwException("except", CSAppConstants.ErrorMessage_QueryFilterException, null); + public Query except(@NotNull String[] fieldIds) { + if (fieldIds.length > 0) { + if (objectUidForExcept == null) { + objectUidForExcept = new JSONArray(); + } + for (String fieldId : fieldIds) { + objectUidForExcept.put(fieldId); } - } catch (Exception e) { - throwException("except", CSAppConstants.ErrorMessage_QueryFilterException, e); } return this; } - /** - * Specifies an array of 'only' keys in BASE object that would be 'included' in the response. - * - * @param fieldUid Array of the 'only' reference keys to be included in response. - * @return {@link Query} object, so you can chain this call. - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
- * csQuery.only(new String[]{"name"}); - *
+ * Specifies an array of 'only' keys in BASE object that would be + * 'included' in the response. + * + * @param fieldUid Array of the 'only' reference keys to be included in + * response. + * @return {@link Query} object, so you can chain this call.
+ * + *
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+ * csQuery.only(new String[]{"name"}); + *
*/ - public Query only(String[] fieldUid) { - try { - if (fieldUid != null && fieldUid.length > 0) { - if (objectUidForOnly == null) { - objectUidForOnly = new JSONArray(); - } - int count = fieldUid.length; - for (int i = 0; i < count; i++) { - objectUidForOnly.put(fieldUid[i]); - } - } else { - throwException("only", CSAppConstants.ErrorMessage_QueryFilterException, null); + public Query only(@NotNull String[] fieldUid) { + if (fieldUid.length > 0) { + if (objectUidForOnly == null) { + objectUidForOnly = new JSONArray(); + } + for (String s : fieldUid) { + objectUidForOnly.put(s); } - } catch (Exception e) { - throwException("only", CSAppConstants.ErrorMessage_QueryFilterException, e); } return this; } - /** - * Specifies an array of 'only' keys that would be 'included' in the response. + * Specifies an array of 'only' keys that would be 'included' in + * the response. * - * @param fieldUid Array of the 'only' reference keys to be included in response. + * @param fieldUid Array of the 'only' reference keys to be + * included in response. * @param referenceFieldUid Key who has reference to some other class object. - * @return {@link Query} object, so you can chain this call. - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
- * ArrayList<String> array = new ArrayList<String>(); - * array.add("description"); - * array.add("name");
- * csQuery.onlyWithReferenceUid(array, "for_bug"); - *
+ * @return {@link Query} object, so you can chain this call.
+ * + * + *
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+ * ArrayList<String> array = new ArrayList<String>(); + * array.add("description"); + * array.add("name");
+ * csQuery.onlyWithReferenceUid(array, "for_bug"); + *
*/ - public Query onlyWithReferenceUid(ArrayList fieldUid, String referenceFieldUid) { - try { - if (fieldUid != null && referenceFieldUid != null) { - if (onlyJsonObject == null) { - onlyJsonObject = new JSONObject(); - } - JSONArray fieldValueArray = new JSONArray(); - int count = fieldUid.size(); - for (int i = 0; i < count; i++) { - fieldValueArray.put(fieldUid.get(i)); - } - - onlyJsonObject.put(referenceFieldUid, fieldValueArray); - if (objectUidForInclude == null) { - objectUidForInclude = new JSONArray(); - } - objectUidForInclude.put(referenceFieldUid); - - } else { - throwException("onlyWithReferenceUid", CSAppConstants.ErrorMessage_QueryFilterException, null); - } - } catch (Exception e) { - throwException("onlyWithReferenceUid", CSAppConstants.ErrorMessage_QueryFilterException, e); + public Query onlyWithReferenceUid(@NotNull ArrayList fieldUid, @NotNull String referenceFieldUid) { + if (onlyJsonObject == null) { + onlyJsonObject = new JSONObject(); + } + JSONArray fieldValueArray = new JSONArray(); + for (String s : fieldUid) { + fieldValueArray.put(s); + } + onlyJsonObject.put(referenceFieldUid, fieldValueArray); + if (objectUidForInclude == null) { + objectUidForInclude = new JSONArray(); } + objectUidForInclude.put(referenceFieldUid); return this; } - /** - * Specifies an array of 'except' keys that would be 'excluded' in the response. + * Specifies an array of 'except' keys that would be 'excluded' + * in the response. * - * @param fieldUid Array of the 'except' reference keys to be excluded in response. + * @param fieldUid Array of the 'except' reference keys to be + * excluded in response. * @param referenceFieldUid Key who has reference to some other class object. - * @return {@link Query} object, so you can chain this call. - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
- * ArrayList<String> array = new ArrayList<String>(); - * array.add("description"); - * array.add("name");
- * csQuery.exceptWithReferenceUid(array, "for_bug"); - *
+ * @return {@link Query} object, so you can chain this call.
+ * + *
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+ * ArrayList<String> array = new ArrayList<String>(); + * array.add("description"); + * array.add("name");
+ * csQuery.exceptWithReferenceUid(array, "for_bug"); + *
*/ - public Query exceptWithReferenceUid(ArrayList fieldUid, String referenceFieldUid) { - try { - if (fieldUid != null && referenceFieldUid != null) { - if (exceptJsonObject == null) { - exceptJsonObject = new JSONObject(); - } - JSONArray fieldValueArray = new JSONArray(); - int count = fieldUid.size(); - for (int i = 0; i < count; i++) { - fieldValueArray.put(fieldUid.get(i)); - } - exceptJsonObject.put(referenceFieldUid, fieldValueArray); - if (objectUidForInclude == null) { - objectUidForInclude = new JSONArray(); - } - objectUidForInclude.put(referenceFieldUid); - } else { - throwException("exceptWithReferenceUid", CSAppConstants.ErrorMessage_QueryFilterException, null); - } - } catch (Exception e) { - throwException("exceptWithReferenceUid", CSAppConstants.ErrorMessage_QueryFilterException, e); + public Query exceptWithReferenceUid(@NotNull ArrayList fieldUid, @NotNull String referenceFieldUid) { + if (exceptJsonObject == null) { + exceptJsonObject = new JSONObject(); } + JSONArray fieldValueArray = new JSONArray(); + for (String s : fieldUid) { + fieldValueArray.put(s); + } + exceptJsonObject.put(referenceFieldUid, fieldValueArray); + if (objectUidForInclude == null) { + objectUidForInclude = new JSONArray(); + } + objectUidForInclude.put(referenceFieldUid); return this; } - /** * Retrieve only count of entries in result. * - * @return {@link Query} object, so you can chain this call. - * Note :- - * Call {@link QueryResult#getCount()} method in the success to get count of objects. - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
- * csQuery.count(); - *
+ * @return {@link Query} object, so you can chain this call. Note :- + * Call {@link QueryResult#getCount()} method in the success to get + * count of objects.
+ * + *
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+ * csQuery.count(); + *
*/ public Query count() { - try { - urlQueries.put("count", "true"); - } catch (Exception e) { - throwException("count", CSAppConstants.ErrorMessage_QueryFilterException, e); - } + urlQueries.put("count", "true"); return this; } - /** * Retrieve count and data of objects in result * - * @return {@link Query} object, so you can chain this call. - * Note :- - * Call {@link QueryResult#getCount()} method in the success to get count of objects. - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
- * csQuery.includeCount(); - *
+ * @return {@link Query} object, so you can chain this call. Note :- + * Call {@link QueryResult#getCount()} method in the success to get + * count of objects.
+ * + *
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+ * csQuery.includeCount(); + *
*/ public Query includeCount() { - try { - urlQueries.put("include_count", "true"); - } catch (Exception e) { - throwException("includeCount", CSAppConstants.ErrorMessage_QueryFilterException, e); - } + urlQueries.put("include_count", "true"); return this; } - /** * Include Content Type of all returned objects along with objects themselves. * - * @return {@link Query} object, so you can chain this call. - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
- * csQuery.includeContentType(); - *
+ * @return {@link Query} object, so you can chain this call.
+ * + *
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+ * csQuery.includeContentType(); + *
*/ public Query includeContentType() { - try { - if (urlQueries.has("include_schema")) { - urlQueries.remove("include_schema"); - } - urlQueries.put("include_content_type", true); - urlQueries.put("include_global_field_schema", true); - } catch (Exception e) { - throwException("include_content_type", CSAppConstants.ErrorMessage_QueryFilterException, e); + if (urlQueries.has("include_schema")) { + urlQueries.remove("include_schema"); } + urlQueries.put("include_content_type", true); + urlQueries.put("include_global_field_schema", true); return this; } - /** * Include object owner's profile in the objects data. * - * @return {@linkplain Query} object, so you can chain this call. - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
- * csQuery.includeOwner(); - *
+ * @return {@linkplain Query} object, so you can chain this call.
+ * + *
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+ * csQuery.includeOwner(); + *
*/ public Query includeOwner() { - try { - urlQueries.put("include_owner", true); - } catch (Exception e) { - throwException("includeUser", CSAppConstants.ErrorMessage_QueryFilterException, e); - } + urlQueries.put("include_owner", true); return this; } - - /** - * Fetches all the objects before specified uid. - * - * @param uid uid before which objects should be returned. - * @return {@link Query} object, so you can chain this call. - * - *

Example :
- *
-     *   Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *   Query csQuery = stack.contentType("content_type").query();
- * //'blt0ae4df463e93f6f5' is dummy uid - * csQuery.beforeUid("blt0ae4df463e93f6f5"); - *
- */ - private Query beforeUid(String uid) { - if (uid != null) { - try { - urlQueries.put("before_uid", uid); - } catch (Exception e) { - throwException("beforeUid", CSAppConstants.ErrorMessage_QueryFilterException, e); - } - } else { - throwException("beforeUid", CSAppConstants.ErrorMessage_QueryFilterException, null); - } - return this; - } - - - /** - * Fetches all the objects after specified uid. - * - * @param uid uid after which objects should be returned. - * @return {@link Query} object, so you can chain this call. - *

Example :
- *
-     *      Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *      Query csQuery = stack.contentType("contentType_name").query();
- * //'blt0ae4df463e93f6f5' is dummy uid - * csQuery.afterUid("blt0ae4df463e93f6f5"); - *
- */ - private Query afterUid(String uid) { - if (uid != null) { - try { - urlQueries.put("after_uid", uid); - } catch (Exception e) { - throwException("afterUid", CSAppConstants.ErrorMessage_QueryFilterException, e); - } - } else { - throwException("afterUid", CSAppConstants.ErrorMessage_QueryFilterException, null); - } - return this; - } - - /** * The number of objects to skip before returning any. * * @param number No of objects to skip from returned objects * @return {@link Query} object, so you can chain this call. - *

- * Note: - * The skip parameter can be used for pagination, "skip" specifies the number of objects to skip in the response. - *

Example :
- *

-     *      Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *      Query csQuery = stack.contentType("contentType_name").query();
- * csQuery.skip(2); - *
+ *

+ * Note: The skip parameter can be used for pagination, + * "skip" specifies the number of objects to skip in the + * response.
+ * + *
+ *
+ * Example :
+ * + *

+     *          Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+ * csQuery.skip(2); + *
*/ public Query skip(int number) { - try { - urlQueries.put("skip", number); - } catch (Exception e) { - throwException("skip", CSAppConstants.ErrorMessage_QueryFilterException, e); - } + urlQueries.put("skip", number); return this; } - /** * A limit on the number of objects to return. * * @param number No of objects to limit. * @return {@link Query} object, so you can chain this call. - *

- * Note: The limit parameter can be used for pagination, " - * limit" specifies the number of objects to limit to in the response. - *

Example :
- *

-     *      Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *      Query csQuery = stack.contentType("contentType_name").query();
- * csQuery.limit(2); - *
+ *

+ * Note: The limit parameter can be used for pagination, " + * limit" specifies the number of objects to limit to in the + * response.
+ * + *
+ *
+ * Example :
+ * + *

+     *          Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+ * csQuery.limit(2); + *
*/ public Query limit(int number) { - try { - urlQueries.put("limit", number); - } catch (Exception e) { - throwException("limit", CSAppConstants.ErrorMessage_QueryFilterException, e); - } + urlQueries.put(LIMIT, number); return this; } - /** - * Add a regular expression constraint for finding string values that match the provided regular expression. - * This may be slow for large data sets. + * Add a regular expression constraint for finding string values that match the + * provided regular expression. This may be slow for large data sets. * * @param key The key to be constrained. * @param regex The regular expression pattern to match. - * @return {@link Query} object, so you can chain this call. - *

Example :
- *
-     *      Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *      Query csQuery = stack.contentType("contentType_name").query();
- * csQuery.regex("name", "^browser"); - *
+ * @return {@link Query} object, so you can chain this call.
+ * + *
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+ * csQuery.regex("name", "^browser"); + *
*/ - public Query regex(String key, String regex) { - - if (key != null && regex != null) { - try { - if (queryValueJSON.isNull(key)) { - - if (queryValue.length() > 0) { - queryValue = new JSONObject(); - } - queryValue.put("$regex", regex); - queryValueJSON.put(key, queryValue); - } else if (queryValueJSON.has(key)) { - queryValue.put("$regex", regex); - queryValueJSON.put(key, queryValue); - } - } catch (Exception e) { - throwException("matches", CSAppConstants.ErrorMessage_QueryFilterException, e); + public Query regex(@NotNull String key, @NotNull String regex) { + if (queryValueJSON.isNull(key)) { + if (!queryValue.isEmpty()) { + queryValue = new JSONObject(); } - } else { - throwException("matches", CSAppConstants.ErrorMessage_QueryFilterException, null); + queryValue.put(REGEX, regex); + queryValueJSON.put(key, queryValue); + } else if (queryValueJSON.has(key)) { + queryValue.put(REGEX, regex); + queryValueJSON.put(key, queryValue); } return this; } - /** - * Add a regular expression constraint for finding string values that match the provided regular expression. - * This may be slow for large data sets. + * Add a regular expression constraint for finding string values that match the + * provided regular expression. This may be slow for large data sets. * * @param key The key to be constrained. * @param regex The regular expression pattern to match * @param modifiers Any of the following supported Regular expression modifiers. - *

use i for case-insensitive matching.

- *

use m for making dot match newlines.

- *

use x for ignoring whitespace in regex

- * @return {@link Query} object, so you can chain this call. - *

Example :
- *
-     *      Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *      Query csQuery = stack.contentType("contentType_name").query();
- * csQuery.regex("name", "^browser", "i"); - *
+ *

+ * use i for case-insensitive matching. + *

+ *

+ * use m for making dot match newlines. + *

+ *

+ * use x for ignoring whitespace in regex + *

+ * @return {@link Query} object, so you can chain this call.
+ * + *
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+ * csQuery.regex("name", "^browser", "i"); + *
*/ - - public Query regex(String key, String regex, String modifiers) { - if (key != null && regex != null) { - - try { - if (queryValueJSON.isNull(key)) { - - if (queryValue.length() > 0) { - queryValue = new JSONObject(); - } - queryValue.put("$regex", regex); - if (modifiers != null) { - queryValue.put("$options", modifiers); - } - queryValueJSON.put(key, queryValue); - } else if (queryValueJSON.has(key)) { - queryValue.put("$regex", regex); - if (modifiers != null) { - queryValue.put("$options", modifiers); - } - queryValueJSON.put(key, queryValue); + public Query regex(@NotNull String key, @NotNull String regex, String modifiers) { + try { + if (queryValueJSON.isNull(key)) { + if (queryValue.length() > 0) { + queryValue = new JSONObject(); } - } catch (Exception e) { - throwException("matches", CSAppConstants.ErrorMessage_QueryFilterException, e); - } - } else { - throwException("matches", CSAppConstants.ErrorMessage_QueryFilterException, null); - } - return this; - } - - - /** - * Set {@link Language} instance. - * - * @param language {@link Language} value - * @return {@link Query} object, so you can chain this call - *

Example :
- *
-     *      Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *      Query csQuery = stack.contentType("contentType_name").query();
- * csQuery.language(Language.ENGLISH_UNITED_STATES); - *
- */ - @Deprecated - public Query language(Language language) { - - if (language != null) { - try { - Language languageName = Language.valueOf(language.name()); - int localeValue = languageName.ordinal(); - LanguageCode[] languageCodeValues = LanguageCode.values(); - String localeCode = languageCodeValues[localeValue].name(); - localeCode = localeCode.replace("_", "-"); - - if (urlQueries != null) { - urlQueries.put("locale", localeCode); + queryValue.put(REGEX, regex); + if (modifiers != null) { + queryValue.put(OPTIONS, modifiers); } - - } catch (Exception e) { - throwException("language", CSAppConstants.ErrorMessage_QueryFilterException, e); + queryValueJSON.put(key, queryValue); + } else if (queryValueJSON.has(key)) { + queryValue.put(REGEX, regex); + if (modifiers != null) { + queryValue.put(OPTIONS, modifiers); + } + queryValueJSON.put(key, queryValue); } - } else { - throwException("language", CSAppConstants.ErrorMessage_QueryFilterException, null); + } catch (Exception e) { + throwException(OPTIONS, Constants.QUERY_EXCEPTION, e); } - return this; } - /** - * Set {@link Language} instance. + * set Language using locale code. * * @param locale {@link String} value - * @return {@link Query} object, so you can chain this call - *

Example :
- *
-     *      Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *      Query csQuery = stack.contentType("contentType_name").query();
- * csQuery.locale("en-us"); - *
+ * @return {@link Query} object, so you can chain this call
+ *
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+ * csQuery.locale("en-us"); + *
*/ - public Query locale(String locale) { - - if (locale != null && urlQueries != null) { - try { - urlQueries.put("locale", locale); - } catch (JSONException e) { - logger.severe(e.getLocalizedMessage()); - } - } - + public Query locale(@NotNull String locale) { + urlQueries.put("locale", locale); return this; } - /** * This method provides only the entries matching the specified value. * * @param value value used to match or compare - * @return {@link Query} object, so you can chain this call. - *

Example :
- *
-     *      Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *      Query csQuery = stack.contentType("contentType_name").query();
- * csQuery.search("header"); - *
+ * @return {@link Query} object, so you can chain this call.
+ * + *
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+ * csQuery.search("header"); + *
*/ - public Query search(String value) { - - if (value != null) { - try { - if (urlQueries.isNull(value)) { - urlQueries.put("typeahead", value); - } - } catch (Exception e) { - throwException("value", CSAppConstants.ErrorMessage_QueryFilterException, e); - } - } else { - throwException("value", CSAppConstants.ErrorMessage_QueryFilterException, null); + public Query search(@NotNull String value) { + if (urlQueries.isNull(value)) { + urlQueries.put("typeahead", value); } - return this; } - /** * Execute a Query and Caches its result (Optional) * - * @param callback {@link QueryResultsCallBack} object to notify the application when the request has completed. - * @return {@linkplain Query} object, so you can chain this call. - *

Example :
- *
-     *      Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *      Query csQuery = stack.contentType("contentType_name").query();
- * csQuery.find(new QueryResultsCallBack() {
- * @Override + * @param callback {@link QueryResultsCallBack} object to notify the application + * when the request has completed. + * @return {@linkplain Query} object, so you can chain this call.
+ * + * + *
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+ * csQuery.find(new QueryResultsCallBack() {
+ * @Override * public void onCompletion(ResponseType responseType, QueryResult queryResult, Error error) {
- * } + * } * });
- *
+ *
*/ public Query find(QueryResultsCallBack callback) { - Error error = null; - try { - if (isJsonProper) { - if (!formName.isEmpty()) { - execQuery(null, callback, false); - } else { - throwException("find", CSAppConstants.ErrorMessage_FormName, null); - error = new Error(); - error.setErrorMessage(errorString); - } + if (isJsonProper) { + if (!contentTypeUid.isEmpty()) { + execQuery(null, callback); } else { + throwException("find", Constants.CONTENT_TYPE_NAME, null); error = new Error(); error.setErrorMessage(errorString); } - } catch (Exception e) { - logger.severe(e.getLocalizedMessage()); - throwException("find", CSAppConstants.ErrorMessage_JsonNotProper, null); + } else { error = new Error(); error.setErrorMessage(errorString); } - - if (error != null && callback != null) { - callback.onRequestFail(ResponseType.UNKNOWN, error); - } return this; } - /** * Execute a Query and Caches its result (Optional) * - * @param callBack {@link QueryResultsCallBack} object to notify the application when the request has completed. - * @return {@linkplain Query} object, so you can chain this call. - *

Example :
- *
-     *      Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *      Query csQuery = stack.contentType("contentType_name").query();
- * csQuery.findOne(new QueryResultsCallBack() {
- * @Override + * @param callBack {@link QueryResultsCallBack} object to notify the application + * when the request has completed. + * @return {@linkplain Query} object, so you can chain this call.
+ * + *
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+ * csQuery.findOne(new QueryResultsCallBack() {
+ * @Override * public void onCompletion(ResponseType responseType, ENTRY entry, Error error) {
* * } * });
- *
+ *
*/ public Query findOne(SingleQueryResultCallback callBack) { - Error error = null; - try { - if (isJsonProper) { - if (!formName.isEmpty()) { - - int limit = -1; - if (urlQueries != null && urlQueries.has("limit")) { - limit = (int) urlQueries.get("limit"); - } - urlQueries.put("limit", 1); - - execQuery(callBack, null, false); + if (isJsonProper) { + if (!contentTypeUid.isEmpty()) { + int limit = -1; + if (urlQueries != null && urlQueries.has(LIMIT)) { + limit = (int) urlQueries.get(LIMIT); + } + if (urlQueries != null) { + urlQueries.put(LIMIT, 1); + execQuery(callBack, null); if (limit != -1) { - urlQueries.put("limit", limit); + urlQueries.put(LIMIT, limit); } - - } else { - - throwException("find", CSAppConstants.ErrorMessage_FormName, null); - error = new Error(); - error.setErrorMessage(errorString); } } else { - - error = new Error(); - error.setErrorMessage(errorString); + throwException("find", Constants.CONTENT_TYPE_NAME, null); } - } catch (Exception e) { - - throwException("find", CSAppConstants.ErrorMessage_JsonNotProper, null); - error = new Error(); - error.setErrorMessage(errorString); } - - if (error != null && callBack != null) { - callBack.onRequestFail(ResponseType.UNKNOWN, error); - } - return this; } - private void throwException(String queryName, String messageString, Exception e) { + HashMap errorHashMap = new HashMap<>(); isJsonProper = false; errorString = messageString; - errorHashMap = new HashMap(); if (e != null) { - errorHashMap.put(queryName, e.toString()); + errorHashMap.put(queryName, e.getLocalizedMessage()); } + errorHashMap.put("detail", messageString); + logger.warning(messageString); } - - protected void setQueryJson(QueryResultsCallBack callback) { - try { - - if (queryValueJSON != null && queryValueJSON.length() > 0) { - urlQueries.put("query", queryValueJSON); - } - - if (objectUidForExcept != null && objectUidForExcept.length() > 0) { - //JSONObject exceptValueJson = new JSONObject(); - //exceptValueJson.put("BASE", objectUidForExcept); - urlQueries.put("except[BASE][]", objectUidForExcept); - objectUidForExcept = null; - - } - - if (objectUidForOnly != null && objectUidForOnly.length() > 0) { - //JSONObject onlyValueJson = new JSONObject(); - //onlyValueJson.put("BASE", objectUidForOnly); - urlQueries.put("only[BASE][]", objectUidForOnly); - objectUidForOnly = null; - - } - - if (onlyJsonObject != null && onlyJsonObject.length() > 0) { - urlQueries.put("only", onlyJsonObject); - onlyJsonObject = null; - } - - if (exceptJsonObject != null && exceptJsonObject.length() > 0) { - urlQueries.put("except", exceptJsonObject); - exceptJsonObject = null; - } - - if (objectUidForInclude != null && objectUidForInclude.length() > 0) { - urlQueries.put("include[]", objectUidForInclude); - objectUidForInclude = null; - } - - } catch (Exception e) { - throwException("find", CSAppConstants.ErrorMessage_QueryFilterException, e); + protected void setQueryJson() { + if (queryValueJSON != null && queryValueJSON.length() > 0) { + urlQueries.put(QUERY, queryValueJSON); + } + if (objectUidForExcept != null && objectUidForExcept.length() > 0) { + urlQueries.put("except[BASE][]", objectUidForExcept); + objectUidForExcept = null; + } + if (objectUidForOnly != null && objectUidForOnly.length() > 0) { + urlQueries.put("only[BASE][]", objectUidForOnly); + objectUidForOnly = null; + } + if (onlyJsonObject != null && onlyJsonObject.length() > 0) { + urlQueries.put("only", onlyJsonObject); + onlyJsonObject = null; + } + if (exceptJsonObject != null && exceptJsonObject.length() > 0) { + urlQueries.put(EXCEPT, exceptJsonObject); + exceptJsonObject = null; + } + if (objectUidForInclude != null && objectUidForInclude.length() > 0) { + urlQueries.put("include[]", objectUidForInclude); + objectUidForInclude = null; } } - - protected void execQuery(SingleQueryResultCallback callBack, QueryResultsCallBack callback, boolean isFromLocal) { + protected void execQuery(SingleQueryResultCallback callBack, QueryResultsCallBack callback) { try { - - String URL = "/" + contentTypeInstance.stackInstance.VERSION + "/content_types/" + formName + "/entries"; + String urlString = "content_types/" + contentTypeUid + "/entries"; queryResultCallback = callback; singleQueryResultCallback = callBack; - setQueryJson(callback); - LinkedHashMap headers = getHeader(localHeader); - if (headers.size() < 1) { - throwException("find", CSAppConstants.ErrorMessage_CalledDefaultMethod, null); - } else { - if (headers.containsKey("environment")) { - urlQueries.put("environment", headers.get("environment")); - } - mainJSON.put("query", urlQueries); - mainJSON.put("_method", CSAppConstants.RequestMethod.GET.toString()); - fetchFromNetwork(URL, headers, mainJSON, callback, callBack); - } - - + setQueryJson(); + urlQueries.put(Constants.ENVIRONMENT, this.headers.get(Constants.ENVIRONMENT)); + includeLivePreview(); + mainJSON.put(QUERY, urlQueries); + fetchFromNetwork(urlString, mainJSON, callback, callBack); } catch (Exception e) { logger.severe(e.getLocalizedMessage()); - throwException("find", CSAppConstants.ErrorMessage_QueryFilterException, e); + throwException("find", Constants.QUERY_EXCEPTION, e); } } + private void includeLivePreview() { + Config configInstance = contentTypeInstance.stackInstance.config; + if (configInstance.enableLivePreview + && configInstance.livePreviewContentType.equalsIgnoreCase(contentTypeUid)) { + configInstance.setHost(configInstance.livePreviewHost); // Check host and replace with new host + this.headers.remove("access_token"); + urlQueries.remove(Constants.ENVIRONMENT); + this.headers.remove(Constants.ENVIRONMENT); + if (configInstance.livePreviewHash == null || configInstance.livePreviewHash.isEmpty()) { + configInstance.livePreviewHash = "init"; + } + this.headers.put("live_preview", configInstance.livePreviewHash); + this.headers.put("authorization", configInstance.managementToken); + } + } - //fetch from network. - private void fetchFromNetwork(String URL, LinkedHashMap headers, JSONObject jsonMain, ResultCallBack callback, SingleQueryResultCallback resultCallback) { + // fetch from network. + private void fetchFromNetwork(String urlString, JSONObject jsonMain, ResultCallBack callback, + SingleQueryResultCallback resultCallback) { LinkedHashMap urlParams = getUrlParams(jsonMain); if (resultCallback != null) { - new CSBackgroundTask(this, contentTypeInstance.stackInstance, CSController.SINGLEQUERYOBJECT, URL, headers, urlParams, new JSONObject(), CSAppConstants.callController.QUERY.toString(), CSAppConstants.RequestMethod.GET, resultCallback); + new CSBackgroundTask(this, contentTypeInstance.stackInstance, Constants.SINGLEQUERYOBJECT, urlString, + this.headers, urlParams, Constants.REQUEST_CONTROLLER.QUERY.toString(), resultCallback); } else { - new CSBackgroundTask(this, contentTypeInstance.stackInstance, CSController.QUERYOBJECT, URL, headers, urlParams, new JSONObject(), CSAppConstants.callController.QUERY.toString(), CSAppConstants.RequestMethod.GET, callback); + new CSBackgroundTask(this, contentTypeInstance.stackInstance, Constants.QUERYOBJECT, urlString, + this.headers, urlParams, Constants.REQUEST_CONTROLLER.QUERY.toString(), callback); } } - private LinkedHashMap getUrlParams(JSONObject jsonMain) { - - JSONObject queryJSON = jsonMain.optJSONObject("query"); LinkedHashMap hashMap = new LinkedHashMap<>(); + JSONObject queryJSON = jsonMain.optJSONObject(QUERY); if (queryJSON != null && queryJSON.length() > 0) { Iterator iter = queryJSON.keys(); while (iter.hasNext()) { String key = iter.next(); - try { - Object value = queryJSON.opt(key); - hashMap.put(key, value); - } catch (Exception e) { - logger.severe(e.getLocalizedMessage()); - } + Object value = queryJSON.opt(key); + hashMap.put(key, value); } - return hashMap; } - - return null; + return hashMap; } - @Override public void getResult(Object object, String controller) { - + // It would not be called. } @Override @@ -1542,30 +1271,22 @@ public void getResultObject(List objects, JSONObject jsonObject, boolean for (int i = 0; i < countObject; i++) { Entry entry = null; try { - entry = contentTypeInstance.stackInstance.contentType(formName).entry(((EntryModel) objects.get(i)).entryUid); + entry = contentTypeInstance.stackInstance.contentType(contentTypeUid) + .entry(((EntryModel) objects.get(i)).uid); } catch (Exception e) { - entry = new Entry(formName); + entry = new Entry(contentTypeUid); } - entry.setUid(((EntryModel) objects.get(i)).entryUid); + entry.setUid(((EntryModel) objects.get(i)).uid); entry.resultJson = ((EntryModel) objects.get(i)).jsonObject; - entry.ownerEmailId = ((EntryModel) objects.get(i)).ownerEmailId; - entry.ownerUid = ((EntryModel) objects.get(i)).ownerUid; entry.title = ((EntryModel) objects.get(i)).title; entry.url = ((EntryModel) objects.get(i)).url; - - if (((EntryModel) objects.get(i)).ownerMap != null) { - entry.owner = new HashMap<>(((EntryModel) objects.get(i)).ownerMap); - } - if (((EntryModel) objects.get(i))._metadata != null) { - entry._metadata = new HashMap<>(((EntryModel) objects.get(i))._metadata); - } entry.setTags(((EntryModel) objects.get(i)).tags); objectList.add(entry); } if (isSingleEntry) { Entry entry = contentTypeInstance.entry(); - if (objectList != null && objectList.size() > 0) { + if (!objectList.isEmpty()) { entry = objectList.get(0); } if (singleQueryResultCallback != null) { @@ -1581,166 +1302,125 @@ public void getResultObject(List objects, JSONObject jsonObject, boolean } - - private LinkedHashMap getHeader(LinkedHashMap localHeader) { - LinkedHashMap mainHeader = formHeader; - LinkedHashMap classHeaders = new LinkedHashMap<>(); - - 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 formHeader; - } - } - - /** - * This method adds key and value to an Entry. - * Parameters: + * This method adds key and value to an Entry. Parameters: * - * @param key: The key as string which needs to be added to the Query - * @param value: The value as string which needs to be added to the Query + * @param paramKey: The key as string which needs to be added to the Query + * @param paramValue: The value as string which needs to be added to the Query * @return - Query * - *

Example :
- *
-     *      Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *      Query csQuery = stack.contentType("contentType_name").query();
-     *      csQuery.addParam("key", "some_value");
-     *      csQuery.findOne(new QueryResultsCallBack() {
-     *          @Override
-     *          public void onCompletion(ResponseType responseType, ENTRY entry, Error error) {
-     *          }
-     *      });
-     * 
+ *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Query csQuery = stack.contentType("contentTypeUid").query();
+     *         csQuery.addParam("key", "some_value");
+     *         csQuery.findOne(new QueryResultsCallBack() {
+     *             @Override
+     *             public void onCompletion(ResponseType responseType, ENTRY entry, Error error) {
+     *             }
+     *         });
+     *         
*/ - public Query addParam(String key, String value) { - try { - if (key != null) { - urlQueries.put(key, value == null ? JSONObject.NULL : value); - } else { - throwException("and", CSAppConstants.ErrorMessage_QueryFilterException, null); - } - } catch (Exception e) { - throwException("and", CSAppConstants.ErrorMessage_QueryFilterException, e); - } + public Query addParam(@NotNull String paramKey, @NotNull String paramValue) { + urlQueries.put(paramKey, paramValue); return this; } - /** - * This method also includes the content type UIDs of the referenced entries returned in the response - * @return {@link Query} - *

Example :
- *
-     *      //'blt5d4sample2633b' is a dummy Stack API key
-     *      //'blt6d0240b5sample254090d' is dummy access token.
-     *      Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *      Query csQuery = stack.contentType("contentType_name").query();
- * csQuery.includeReferenceContentTypUid(); - * csQuery.findOne(new QueryResultsCallBack() {
+ * This method also includes the content type UIDs of the referenced entries + * returned in the response + * + * @return {@link Query}
+ * + *
+ *
+ * Example :
+ * + *
+     *          Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment");
+     *          Query csQuery = stack.contentType("contentTypeUid").query();
+ * csQuery.includeReferenceContentTypUid(); + * csQuery.findOne(new QueryResultsCallBack() {
* @Override * public void onCompletion(ResponseType responseType, ENTRY entry, Error error) {
* } * });
- *
+ *
*/ public Query includeReferenceContentTypUid() { - try { - urlQueries.put("include_reference_content_type_uid", "true"); - } catch (JSONException e) { - logger.severe(e.getLocalizedMessage()); - } + urlQueries.put("include_reference_content_type_uid", "true"); return this; } - /** - * Get entries having values based on referenced fields. - * This query retrieves all entries that satisfy the query conditions made on referenced fields. + * Get entries having values based on referenced fields. This query retrieves + * all entries that satisfy the query conditions made on referenced fields. * - * @param key The key to be constrained + * @param key The key to be constrained * @param queryObject {@link Query} object, so you can chain this call - * @return {@link Query} object, so you can chain this call - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
-     *     csQuery.whereIn("due_date", csQuery);
-     * 
+ * @return {@link Query} object, so you can chain this call
+ * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Query csQuery = stack.contentType("contentTypeUid").query();
+     *         csQuery.whereIn("due_date", csQuery);
+     *         
*/ - public Query whereIn(String key, Query queryObject) { - if (key != null) { - try { - JSONObject inQueryObj = new JSONObject(); - inQueryObj.put("$in_query", queryObject.queryValueJSON.toString()); - queryValueJSON.put(key, inQueryObj); - } catch (Exception e) { - throwException("in_query", CSAppConstants.ErrorMessage_QueryFilterException, e); - } - } else { - throwException("in_query", CSAppConstants.ErrorMessage_QueryFilterException, null); - } + public Query whereIn(@NotNull String key, Query queryObject) { + JSONObject inQueryObj = new JSONObject(); + inQueryObj.put("$in_query", queryObject.queryValueJSON.toString()); + queryValueJSON.put(key, inQueryObj); return this; } - /** - * Get entries having values based on referenced fields. This query works the opposite of $in_query and retrieves all entries that does not satisfy query conditions made on referenced fields. + * Get entries having values based on referenced fields. This query works the + * opposite of $in_query and retrieves all entries that does not satisfy query + * conditions made on referenced fields. * * @param key The key to be constrained * @param queryObject {@link Query} object, so you can chain this call * @return {@link Query} object, so you can chain this call * - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "APIKey", "deliveryToken", "environment_name");
-     *     Query csQuery = stack.contentType("contentType_name").query();
-     *     csQuery.whereNotIn("due_date", csQuery);
-     * 
+ *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Query csQuery = stack.contentType("contentTypeUid").query();
+     *         csQuery.whereNotIn("due_date", csQuery);
+     *         
*/ - public Query whereNotIn(String key, Query queryObject) { - - if (key != null) { - try { - JSONObject inQueryObj = new JSONObject(); - inQueryObj.put("$nin_query", queryObject.queryValueJSON.toString()); - queryValueJSON.put(key, inQueryObj); - } catch (Exception e) { - throwException("nin_query", CSAppConstants.ErrorMessage_QueryFilterException, e); - } - } else { - throwException("nin_query", CSAppConstants.ErrorMessage_QueryFilterException, null); - } + public Query whereNotIn(@NotNull String key, Query queryObject) { + JSONObject inQueryObj = new JSONObject(); + inQueryObj.put("$nin_query", queryObject.queryValueJSON.toString()); + queryValueJSON.put(key, inQueryObj); return this; } - /** - * Retrieve the published content of the fallback locale if an entry is not localized in specified locale - * @return {@link Query} object, so you can chain this call. - *

Example :
- *
-     *     Stack stack = Contentstack.stack( "ApiKey", "deliveryToken",  environment_name);
-     *     Query csQuery = stack.contentType("contentType_name").query();
-     *     csQuery.includeFallback();
-     * 
+ * Retrieve the published content of the fallback locale if an entry is not + * localized in specified locale + * + * @return {@link Query} object, so you can chain this call.
+ * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", environment);
+     *         Query csQuery = stack.contentType("contentTypeUid").query();
+     *         csQuery.includeFallback();
+     *         
*/ public Query includeFallback() { urlQueries.put("include_fallback", true); @@ -1748,17 +1428,44 @@ public Query includeFallback() { } /** - * includeEmbeddedItems instance of Query - * Include Embedded Objects (Entries and Assets) along with entry/entries details.
- * Stack stack = Contentstack.stack( "ApiKey", "deliveryToken", "environment"); - * final Query query = stack.contentType("user").query(); - * query = query.includeEmbeddedObjects() + * @return {@link Query} object, so you can chain this call.
+ * + * * @return {@link Query} + * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", environment);
+     *         Query query = stack.contentType("contentTypeUid").query();
+     *         query.includeEmbeddedObjects()
+     *         
*/ public Query includeEmbeddedItems() { urlQueries.put("include_embedded_items[]", "BASE"); return this; } -} + /** + * Includes Branch in the entry response + * + * @return {@link Query} object, so you can chain this call.
+ * + *
+ *
+ * Example :
+ * + *
+     *         Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment");
+     *         Query query = stack.contentType("contentTypeUid").query();
+     *         entry.includeBranch();
+     *         
+ */ + public Query includeBranch() { + urlQueries.put("include_branch", true); + return this; + } +} diff --git a/src/main/java/com/contentstack/sdk/QueryResult.java b/src/main/java/com/contentstack/sdk/QueryResult.java index c7c06def..0cf50919 100644 --- a/src/main/java/com/contentstack/sdk/QueryResult.java +++ b/src/main/java/com/contentstack/sdk/QueryResult.java @@ -6,96 +6,90 @@ import java.util.List; import java.util.logging.Logger; -/** - * It results the query response - */ - public class QueryResult { - - private static final Logger logger = Logger.getLogger(QueryResult.class.getSimpleName()); + private final Logger logger = Logger.getLogger(QueryResult.class.getSimpleName()); protected JSONObject receiveJson; protected JSONArray schemaArray; protected JSONObject contentObject; protected int count; protected List resultObjects; - /** - * @return List of {@link Entry} objects list. - *

Example :
- *
+     * @return List of {@link Entry} objects list. 
+ *
+ * Example :
+ * + *
      * List<Entry> list = queryResultObject.getResultObjects();
- *
+ *
*/ public List getResultObjects() { return resultObjects; } - /** * Returns count of objects available.
- * Note : - * To retrieve this data, {@link Query#includeCount()} or {@link Query#count()} - * should be added in {@link Query} while querying. + * Note : To retrieve this data, {@link Query#includeCount()} or + * {@link Query#count()} should be added in {@link Query} while querying. * - * @return int count - *

Example :
- *
+     * @return int count 
+ *
+ * Example :
+ * + *
      * int count = queryResultObject.getCount();
- *
+ *
*/ public int getCount() { return count; } - /** * Returns class's schema if call to fetch schema executed successfully. * - * @return JSONArray schema Array - *

Example :
- *
+     * @return JSONArray schema Array 
+ *
+ * Example :
+ * + *
      * JSONArray schemaArray = queryResultObject.getSchema();
- *
+ *
*/ public JSONArray getSchema() { return schemaArray; } - /** - * Returns class's content type if call to fetch contentType executed successfully. + * Returns class's content type if call to fetch contentType executed + * successfully. * - * @return JSONObject contentObject - *

Example :
- *
+     * @return JSONObject contentObject 
+ *
+ * Example :
+ * + *
      * JSONObject contentObject = queryResultObject.getContentType();
- *
+ *
*/ public JSONObject getContentType() { return contentObject; } - protected void setJSON(JSONObject jsonobject, List objectList) { receiveJson = jsonobject; resultObjects = objectList; - try { if (receiveJson != null) { if (receiveJson.has("schema")) { - - JSONArray jsonarray = new JSONArray(); - jsonarray = receiveJson.getJSONArray("schema"); + JSONArray jsonarray = receiveJson.getJSONArray("schema"); if (jsonarray != null) { schemaArray = jsonarray; } } if (receiveJson.has("content_type")) { - JSONObject jsonObject = receiveJson.getJSONObject("content_type"); if (jsonObject != null) { contentObject = jsonObject; @@ -106,7 +100,7 @@ protected void setJSON(JSONObject jsonobject, List objectList) { count = receiveJson.optInt("count"); } - if (count <= 0) { + if (count == 0) { if (receiveJson.has("entries")) { count = receiveJson.optInt("entries"); } @@ -118,5 +112,4 @@ protected void setJSON(JSONObject jsonobject, List objectList) { } } - } diff --git a/src/main/java/com/contentstack/sdk/QueryResultsCallBack.java b/src/main/java/com/contentstack/sdk/QueryResultsCallBack.java index 22599622..5d8c3ac1 100644 --- a/src/main/java/com/contentstack/sdk/QueryResultsCallBack.java +++ b/src/main/java/com/contentstack/sdk/QueryResultsCallBack.java @@ -1,7 +1,6 @@ package com.contentstack.sdk; - -public abstract class QueryResultsCallBack extends ResultCallBack { +public abstract class QueryResultsCallBack implements ResultCallBack { public abstract void onCompletion(ResponseType responseType, QueryResult queryresult, Error error); @@ -10,14 +9,8 @@ void onRequestFinish(ResponseType responseType, QueryResult queryResultObject) { } @Override - void onRequestFail(ResponseType responseType, Error error) { + public void onRequestFail(ResponseType responseType, Error error) { onCompletion(responseType, null, error); } - @Override - public void always() { - - } - - } diff --git a/src/main/java/com/contentstack/sdk/ResultCallBack.java b/src/main/java/com/contentstack/sdk/ResultCallBack.java index 50c14ad8..189fbbb7 100644 --- a/src/main/java/com/contentstack/sdk/ResultCallBack.java +++ b/src/main/java/com/contentstack/sdk/ResultCallBack.java @@ -1,8 +1,5 @@ package com.contentstack.sdk; -public abstract class ResultCallBack { - - abstract void onRequestFail(ResponseType responseType, Error error); - - public abstract void always(); -} +public interface ResultCallBack { + void onRequestFail(ResponseType responseType, Error error); +} \ No newline at end of file diff --git a/src/main/java/com/contentstack/sdk/SingleQueryResultCallback.java b/src/main/java/com/contentstack/sdk/SingleQueryResultCallback.java index 3587e80e..14bb4cc1 100644 --- a/src/main/java/com/contentstack/sdk/SingleQueryResultCallback.java +++ b/src/main/java/com/contentstack/sdk/SingleQueryResultCallback.java @@ -1,6 +1,6 @@ package com.contentstack.sdk; -public abstract class SingleQueryResultCallback extends ResultCallBack { +public abstract class SingleQueryResultCallback implements ResultCallBack { public abstract void onCompletion(ResponseType responseType, Entry entry, Error error); @@ -9,15 +9,8 @@ void onRequestFinish(ResponseType responseType, Entry entry) { } @Override - void onRequestFail(ResponseType responseType, Error error) { + public void onRequestFail(ResponseType responseType, Error error) { onCompletion(responseType, null, error); } - @Override - public void always() { - - } - - } - diff --git a/src/main/java/com/contentstack/sdk/Stack.java b/src/main/java/com/contentstack/sdk/Stack.java index fdc9e2f8..1fd5e871 100644 --- a/src/main/java/com/contentstack/sdk/Stack.java +++ b/src/main/java/com/contentstack/sdk/Stack.java @@ -1,723 +1,542 @@ package com.contentstack.sdk; -import com.contentstack.sdk.utility.CSAppConstants; -import com.contentstack.sdk.utility.CSController; -import org.json.JSONException; + +import org.jetbrains.annotations.NotNull; import org.json.JSONObject; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.logging.Logger; +import java.util.stream.Collectors; + +import static com.contentstack.sdk.Constants.*; /** - * A stack is a repository or a container that holds all the content/assets of your site. - * It allows multiple users to create, edit, approve, and publish their content within a single space. + * A stack is a repository or a container that holds all the content/assets of + * your site. It allows multiple users to create, edit, approve, and publish + * their content within a single space. */ - public class Stack { - private static final Logger logger = Logger.getLogger(Stack.class.getSimpleName()); - private String stackApiKey = null; - protected LinkedHashMap localHeader = null; - private String imageTransformationUrl; - private LinkedHashMap imageParams = new LinkedHashMap<>(); - - protected String URLSCHEMA = "https://"; - protected String URL = "cdn.contentstack.io"; - protected String VERSION = "v3"; + private final Logger logger = Logger.getLogger(Stack.class.getSimpleName()); + protected LinkedHashMap headers; protected Config config; - protected String SYNC_KEY = "sync"; - protected String content_type; - - private JSONObject syncParams = null; - protected String sync_token = null; - protected String pagination_token = null; protected String contentType; - protected String localeCode ; - protected PublishType publishType; - protected String start_from_date; - private SyncResultCallBack syncCallBack; - protected HashMap headerGroup_app; - - private Stack(){ } - - - public static enum PublishType - { - entry_published, - entry_unpublished , - entry_deleted , - asset_published , - asset_unpublished , - asset_deleted , - content_type_deleted - } + protected String apiKey; + protected JSONObject syncParams = null; - - protected Stack(String stackApiKey) { - this.stackApiKey = stackApiKey; - this.localHeader = new LinkedHashMap<>(); + protected Stack() throws IllegalAccessException { + throw new IllegalAccessException("Can Not Access Private Modifier"); } - protected void setConfig(Config config){ - this.config = config; - URLSCHEMA = config.URLSCHEMA; - URL = config.URL; - VERSION = config.VERSION; - - if(!config.environment.isEmpty()){ - setHeader("environment", config.environment); - } + protected Stack(@NotNull String apiKey) { + this.apiKey = apiKey; + this.headers = new LinkedHashMap<>(); + } - if (!config.region.name().isEmpty()){ + protected void setConfig(Config config) { + this.config = config; + String urlDomain = config.host; + if (!config.region.name().isEmpty()) { String region = config.region.name().toLowerCase(); - if (!region.equalsIgnoreCase("us")){ - if(URL.equalsIgnoreCase("cdn.contentstack.io")) { - URL = "cdn.contentstack.com"; + if (!region.equalsIgnoreCase("us")) { + if (urlDomain.equalsIgnoreCase("cdn.contentstack.io")) { + urlDomain = "cdn.contentstack.com"; } - URL = region+"-"+URL; + config.host = region + "-" + urlDomain; } } + includeLivePreview(); + // Set the endpoint + String endpoint = config.scheme + config.host; + this.config.setEndpoint(endpoint); } + private void includeLivePreview() { + try { + if (config.enableLivePreview) { + if (config.managementToken == null || config.managementToken.isEmpty()) { + throw new IllegalAccessException("managementToken is required"); + } + if (config.livePreviewHost == null || config.livePreviewHost.isEmpty()) { + throw new IllegalAccessException("host is required"); + } + config.host = config.livePreviewHost; + } + } catch (Exception e) { + String info = "To enable live preview, managementToken and host are required"; + logger.warning(info); + throw new IllegalArgumentException(e.getLocalizedMessage()); + } + } - public ContentType contentType(String contentTypeName){ - this.content_type = contentType; - ContentType contentType = new ContentType(contentTypeName); - contentType.setStackInstance(this); - return contentType; + /** + * Live Preview lets content managers preview entry content across multiple + * channels before saving or publishing it to a live website. You can edit an + * entry and preview the content changes side by side in real-time. + *

+ * Note: To be able to preview entry content, developers need to first + * configure Live Preview for the frontend website and then enable it from the + * stack settings section in Contentstack. You can set up the base URL and + * environment across which you want to preview content. + *

+ * + * @param query the query of type {@link HashMap} + * @return stack + *

+ * Example + * + * + * stack = contentstack.Stack("apiKey", "deliveryToken", "environment"); + *

+ * HashMap queryMap = new HashMap(); + *

+ * stack.livePreviewQuery(queryMap) + * + */ + public Stack livePreviewQuery(Map query) { + if (this.config.enableLivePreview) { + config.livePreviewHash = query.get("live_preview"); + config.livePreviewContentType = query.get(CONTENT_TYPE_UID); + } + return this; } + /** + * Content type defines the structure or schema of a page or a section of your + * web or mobile property. To create content for your application, you are + * required to first create a content type, and then create entries using the + * content type. + * + * @param contentTypeUid Enter the unique ID of the content type of which you + * want to retrieve the entries. The UID is often based on + * the title of the content type and it is unique across a + * stack. + * @return the {@link ContentType} + *

+ * Example + * + *

+     *  Stack stack = contentstack.Stack("apiKey",
+     * "deliveryToken", "environment"); ContentType contentType = stack.contentType("contentTypeUid")
+     *         
+ */ + public ContentType contentType(String contentTypeUid) { + this.contentType = contentTypeUid; // set contentTypeUid for stack instance + ContentType ct = new ContentType(contentTypeUid); + ct.setStackInstance(this); + return ct; + } /** - * Takes asset uid as a parameter and returns @{@link Asset} instance + * Assets refer to all the media files (images, videos, PDFs, audio files, and + * so on) uploaded in your Contentstack repository for future use. These files + * can be attached and used in multiple entries. + *

+ * The Get a single asset request fetches the latest version of a specific asset + * of a particular stack. + *

+ * * @param uid uid of {@link Asset} - * @return Asset instance + * @return {@link Asset} instance Tip: If no version is mentioned, the + * request will retrieve the latest published version of the asset. To + * retrieve a specific version, use the version parameter, keep the + * environment parameter blank, and use the management token instead of + * the delivery token. + *

+ * Example Stack stack = contentstack.Stack("apiKey", + * "deliveryToken", "environment"); Asset asset = + * stack.asset("assetUid"); + * */ - public Asset asset(String uid){ + public Asset asset(@NotNull String uid) { Asset asset = new Asset(uid); asset.setStackInstance(this); return asset; } - - - protected Asset asset(){ + protected Asset asset() { Asset asset = new Asset(); asset.setStackInstance(this); return asset; } /** - * assetLibrary returns AssetLibrary instance - * @return AssetLibrary + * The Get all assets request fetches the list of all the assets of a particular + * stack. It returns the content of each asset in JSON format. + * + * @return {@link AssetLibrary} asset library + *

+ * Example + * + *

+     *         Stack stack = contentstack.Stack("apiKey", "deliveryToken", "environment");
+     *         AssetLibrary assets = stack.assetLibrary();
+     *         
*/ - public AssetLibrary assetLibrary(){ + public AssetLibrary assetLibrary() { AssetLibrary library = new AssetLibrary(); library.setStackInstance(this); return library; } - /** * Returns apiKey of particular stack - * @return stack api key + * + * @return {@link Stack} apiKey */ - public String getApplicationKey(){ return stackApiKey;} - + public String getApplicationKey() { + return apiKey; + } /** - * Returns accessToken of particular stack - * @return access token of particular stack + * @deprecated accessToken of particular stack + * + * @return {@link Stack} accessToken */ - public String getAccessToken(){ return localHeader != null ? (String)localHeader.get("access_token") : null;}; - + @Deprecated + public String getAccessToken() { + return (String) headers.get("access_token"); + } /** - * Removes Header by key - * @param key header key - *

Example :
- * stack.removeHeader("delivery_token"); - *

- *

+ * Returns deliveryToken of particular stack + * + * @return deliveryToken delivery token */ - public void removeHeader(String key){ - if(!key.isEmpty()){ - localHeader.remove(key); - } + public String getDeliveryToken() { + return (String) headers.get("access_token"); } - /** - * Adds header to the stack by key and value - * @param key header key - * @param value header value - *

- * Example - * stack.setHeader("delivery_token","blt843748744"); - *

+ * Removes Header by key + * + * @param headerKey of the header + *

+ * Example: stack.removeHeader("delivery_token"); */ - public void setHeader(String key, String value) { - if (!key.isEmpty() && !value.isEmpty()) { - localHeader.put(key, value); - } + public void removeHeader(String headerKey) { + headers.remove(headerKey); } - - /** - * @param image_url - * on which we want to manipulate. - * @param parameters - * It is an second parameter in which we want to place different manipulation key and value in array form - * @return String - * - * ImageTransform function is define for image manipulation with different - * parameters in second parameter in array form - * - *

Example :
- *

-     *  //'blt5d4sample2633b' is a dummy Stack API key
-     *  //'blt6d0240b5sample254090d' is dummy access token.
-     *  Stack stack = Contentstack.stack("blt5d4sample2633b", "blt6d0240b5sample254090d", "stag", false);
- * // resize the image by specifying width and height - * LinkedHashMap imageParams = new LinkedHashMap(); - * imageParams.put("width", 100); - * imageParams.put("height",100); - * imageUrl = Stack.ImageTransform(image_url, parameters); - * stack.ImageTransform(image_url, parameters); - *
+ * Adds header to the stack * + * @param headerKey the header key + * @param headerValue the header value */ - public String ImageTransform(String image_url, LinkedHashMap parameters) { - imageTransformationUrl = image_url; - imageParams = parameters; - return getImageUrl(); - } - - - - private String getImageUrl() { - - if (imageParams == null || imageParams.size() == 0) { - return imageTransformationUrl; + public void setHeader(@NotNull String headerKey, @NotNull String headerValue) { + if (!headerKey.isEmpty() && !headerValue.isEmpty()) { + headers.put(headerKey, headerValue); } - - imageParams.forEach((key, value) -> { - - try { - final String encodedKey = URLEncoder.encode(key.toString(), "UTF-8"); - final String encodedValue = URLEncoder.encode(value.toString(), "UTF-8"); - if (!imageTransformationUrl.contains("?")) { - imageTransformationUrl += "?" + encodedKey + "=" + encodedValue; - } else { - imageTransformationUrl += "&" + encodedKey + "=" + encodedValue; - } - - } catch (UnsupportedEncodingException e) { - logger.severe(e.getLocalizedMessage()); - } - }); - - return imageTransformationUrl; } - - - - - /** - * @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(new ContentTypesCallback() {
-     * public void onCompletion(ContentTypesModel contentTypesModel, Error error) {
-     *  if (error == null){
-     *     // do your stuff.
-     *  }
-     * }
-     * });
-     *
+ * Image transform string. This document is a detailed reference to Contentstack + * Image Delivery API and covers the parameters that you can add to the URL to + * retrieve, manipulate (or convert) image files and display it to your web or + * mobile properties. + * + * @param imageUrl the image url + * @param parameters the parameters {@link LinkedHashMap} + * @return the string */ - - public void getContentTypes(JSONObject params, final ContentTypesCallback callback) { - - try { - String URL = "/" + this.VERSION + "/content_types"; - HashMap 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")); - params.put("include_count", true); - } - - fetchContentTypes(URL, params, headers, callback ); - - }catch (Exception e){ - - Error error = new Error(); - error.setErrorMessage(CSAppConstants.ErrorMessage_JsonNotProper); - callback.onRequestFail(ResponseType.UNKNOWN, error); + public String imageTransform(@NotNull String imageUrl, @NotNull Map parameters) { + if (parameters.size() == 0) { + return imageUrl; + } + String query = getQueryParam(parameters); + if (imageUrl.contains("?")) { + imageUrl += "&" + query; + } else { + imageUrl += "?" + query; } + return imageUrl; } - - - - + protected String getQueryParam(Map params) { + return params.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining("&")); + } /** - * @param syncCallBack returns callback for sync result. - * The Sync request performs a complete sync of your app data. - * It returns all the published entries and assets of the specified stack in response. - * The response also contains a sync token, which you need to store, - * since this token is used to get subsequent delta updates later. - * - *

Example :
- *
+     * The Get all content types call returns comprehensive information of all the
+     * content types available in a particular stack in your account..
      *
-     * stack.sync(SyncResultCallBack syncCallBack){  }
-     *
-     * 
+ * @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. */ - - public void sync(SyncResultCallBack syncCallBack){ - - if (syncParams == null){ - syncParams = new JSONObject(); + public void getContentTypes(@NotNull JSONObject params, final ContentTypesCallback callback) { + Iterator keys = params.keys(); + while (keys.hasNext()) { + String key = keys.next(); + Object value = params.opt(key); + params.put(key, value); } - try { - syncParams.put("init", true); - } catch (JSONException e) { - logger.severe(e.getLocalizedMessage()); + if (this.headers.containsKey(ENVIRONMENT)) { + params.put(ENVIRONMENT, this.headers.get(ENVIRONMENT)); + params.put("include_count", true); } - - this.requestSync(syncCallBack); - + fetchContentTypes("content_types", params, this.headers, callback); } - - /** + * The Sync request performs a complete sync of your app data. It returns all + * the published entries and assets of the specified stack in response. The + * response also contains a sync token, which you need to store, since this + * token is used to get subsequent delta * - * @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 :
- *
-     *
-     * // dummy pagination_token = "blt7f35951d259183fba680e1";
-     *   stack.syncPaginationToken(pagination_token, new SyncResultCallBack()) {}
-     *
+     * @param syncCallBack returns callback for sync result.
      *
-     * 
*/ - public void syncPaginationToken(String pagination_token, SyncResultCallBack syncCallBack){ - this.pagination_token = pagination_token; - if (syncParams == null){ - syncParams = new JSONObject(); - } - - try { - syncParams.put("init", true); - syncParams.put("pagination_token", pagination_token); - } catch (JSONException e) { - logger.severe(e.getLocalizedMessage()); - } - + public void sync(SyncResultCallBack syncCallBack) { + syncParams = new JSONObject(); + syncParams.put("init", true); this.requestSync(syncCallBack); } - - - /** - * @param sync_token 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. - * The sync token fetches only the content that was added after your last sync, - * and the details of the content that was deleted or updated. - * + * Sync pagination token. + * + * @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.
+ *
+ * Example :
* - *

Example :
- *

-     *
-     *  //dummy sync_token = "blt28937206743728463";
-     *  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(); - } - try { - syncParams.put("init", true); - syncParams.put("sync_token", sync_token); - } catch (JSONException e) { - logger.severe(e.getLocalizedMessage()); - } - + public void syncPaginationToken(@NotNull String paginationToken, SyncResultCallBack syncCallBack) { + this.sync(null); + syncParams.put("pagination_token", paginationToken); this.requestSync(syncCallBack); } - - - - - - - /** - * @param from_date 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 - * and specify the start date as its value. - * - *

Example :
- *
-     *
-     *   // dummy date final Date start_date = sdf.parse("2018-10-07");
-     *   stack.syncFromDate(start_date, new SyncResultCallBack()) { }
+     * Sync token.
      *
-     *
-     *  
+ * @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. The + * sync token fetches only the content that was added after + * your last sync, and the details of the content that was + * deleted or updated.
+ *
+ * Example :
+ * + *

+     *                     stack.syncToken(sync_token, new SyncResultCallBack()                                                                                                                                                                                                               ){ }
+     *                     
*/ - public void syncFromDate(Date from_date, SyncResultCallBack syncCallBack){ - start_from_date = convertUTCToISO(from_date); - if (syncParams == null){ - syncParams = new JSONObject(); - } - - try { - syncParams.put("init", true); - syncParams.put("start_from", start_from_date); - } catch (JSONException e) { - logger.severe(e.getLocalizedMessage()); - } + public void syncToken(String syncToken, SyncResultCallBack syncCallBack) { + this.sync(null); + syncParams.put("sync_token", syncToken); this.requestSync(syncCallBack); } + /** + * Sync from date. + * + * @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 and specify + * the start date as its value.
+ *
+ * Example :
+ * + *

+     *                     final Date start_date = sdf.parse("2018-10-07"); 

+ * stack.syncFromDate(start_date, SyncResultCallBack()) { + * + * } + *

+ */ + public void syncFromDate(@NotNull Date fromDate, SyncResultCallBack syncCallBack) { + String newFromDate = convertUTCToISO(fromDate); + this.sync(null); + syncParams.put("start_from", newFromDate); + this.requestSync(syncCallBack); + } - - - private String convertUTCToISO(Date date) { - + protected 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); } - - /** + * Sync content type. * - * @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()){  }
-     *
-     *  
+ *

+ * 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 : + *

+ * 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(); - } - try { - syncParams.put("init", true); - syncParams.put("content_type_uid", contentType); - } catch (JSONException e) { - logger.severe(e.getLocalizedMessage()); - } - + public void syncContentType(@NotNull String contentType, SyncResultCallBack syncCallBack) { + this.sync(null); + syncParams.put(CONTENT_TYPE_UID, contentType); this.requestSync(syncCallBack); } - - - - /** - * @param language Select the required locale from the Language class. - * @param syncCallBack Returns callback for sync result. + * Sync locale. * - * You can also initialize sync with entries of only specific locales. - * To do this, use syncLocale and specify the locale code as its value. - * However, if you do this, the subsequent syncs will only include the entries of the specified locales. + * @param localeCode Select the required locale code. + * @param syncCallBack Returns callback for sync result. + *

+ * You can also initialize sync with entries of only + * specific locales. To do this, use syncLocale and specify + * the locale code as its value. However, if you do this, + * the subsequent syncs will only include the entries of the + * specified locales.
+ *
+ * Example :
* - *

Example :
- *

      *
-     * // dummy language- Language.ENGLISH_UNITED_STATES
-     * stackInstance.syncLocale(Language.ENGLISH_UNITED_STATES, new SyncResultCallBack() ) { }
      *
-     * 
*/ - public void syncLocale(Language language, SyncResultCallBack syncCallBack) { - this.localeCode = getLanguageCode(language); - - if (syncParams == null) { - syncParams = new JSONObject(); - } - try { - syncParams.put("init", true); - syncParams.put("locale", localeCode); - } catch (JSONException e) { - logger.severe(e.getLocalizedMessage()); - } - - + public void syncLocale(String localeCode, SyncResultCallBack syncCallBack) { + this.sync(null); + syncParams.put("locale", localeCode); 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.) - * - * + * Sync publish type. + * + * @param publishType 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.) * @param syncCallBack returns callback for sync result. - * - * 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. - * - *

Example :
- *

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

+ * 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. + *
+ *
+ * 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); - } catch (JSONException e) { - logger.severe(e.getLocalizedMessage()); - } - + public void syncPublishType(PublishType publishType, SyncResultCallBack syncCallBack) { + this.sync(null); + syncParams.put("type", publishType.name()); this.requestSync(syncCallBack); } - - /** + * Sync. * - * @param contentType your content type id - * @param from_date start date - * @param language language as {@link Language} - * @param type type as PublishType + * @param contentType your content type id + * @param fromDate start date + * @param localeCode language as language code + * @param publishType type as PublishType * @param syncCallBack Callback - * - * You can also initialize sync with entries that satisfy multiple parameters. - * To do this, use syncWith and specify the parameters. - * However, if you do this, the subsequent syncs will only include the entries of the specified parameters - * - *

Example :
- *
-     *
-     *  stackInstance.sync(String contentType, Date from_date, Language language, PublishType type,  SyncResultCallBack syncCallBack) { }
+     *                     

+ * You can also initialize sync with entries that satisfy + * multiple parameters. To do this, use syncWith and specify + * the parameters. However, if you do this, the subsequent + * syncs will only include the entries of the specified + * parameters
+ *
+ * Example :
* * - *

*/ - - public void sync( String contentType, Date from_date, Language language, PublishType type, SyncResultCallBack syncCallBack){ - start_from_date = convertUTCToISO(from_date); - this.contentType = contentType; - this.publishType = type; - this.localeCode = getLanguageCode(language); - - if (syncParams == null){ - syncParams = new JSONObject(); - } - try { - syncParams.put("init", true); - syncParams.put("start_from", this.start_from_date); - syncParams.put("content_type_uid", this.contentType); - syncParams.put("type", publishType); - syncParams.put("locale", this.localeCode); - } catch (JSONException e) { - logger.severe(e.getLocalizedMessage()); - } - + public void sync(String contentType, Date fromDate, String localeCode, PublishType publishType, + SyncResultCallBack syncCallBack) { + String newDate = convertUTCToISO(fromDate); + this.sync(null); + syncParams.put("start_from", newDate); + syncParams.put("content_type_uid", contentType); + syncParams.put("type", publishType.name()); + syncParams.put("locale", localeCode); this.requestSync(syncCallBack); } - - - - - private void requestSync(final SyncResultCallBack callback){ - - try { - - String URL = "/" + this.VERSION + "/stacks/" + SYNC_KEY; - HashMap headers = getHeader(localHeader); - - JSONObject urlQueries = new JSONObject(); - if (headers.containsKey("environment")) { - syncParams.put("environment", headers.get("environment")); - } - - urlQueries = syncParams; - fetchFromNetwork(URL, syncParams, headers, callback ); - - - }catch (Exception e){ - - Error error = new Error(); - error.setErrorMessage(CSAppConstants.ErrorMessage_JsonNotProper); - callback.onRequestFail(ResponseType.UNKNOWN, error); + private void requestSync(final SyncResultCallBack callback) { + if (this.headers.containsKey(ENVIRONMENT)) { + syncParams.put(ENVIRONMENT, this.headers.get(ENVIRONMENT)); } - + fetchFromNetwork(SYNCHRONISATION, syncParams, this.headers, callback); } - - - private void fetchContentTypes(String urlString, JSONObject content_type_param, HashMap headers, ContentTypesCallback callback) { - - if(callback != null) { - - HashMap urlParams = getUrlParams(content_type_param); - new CSBackgroundTask(this, CSController.FETCHCONTENTTYPES, urlString, headers, urlParams, new JSONObject(), CSAppConstants.callController.CONTENTTYPES.toString(), false, CSAppConstants.RequestMethod.GET, callback); + private void fetchContentTypes(String urlString, JSONObject contentTypeParam, HashMap headers, + ContentTypesCallback callback) { + if (callback != null) { + HashMap queryParam = getUrlParams(contentTypeParam); + String requestInfo = REQUEST_CONTROLLER.CONTENTTYPES.toString(); + new CSBackgroundTask(this, Constants.FETCHCONTENTTYPES, urlString, headers, queryParam, requestInfo, + callback); } } - - private void fetchFromNetwork(String urlString, JSONObject urlQueries, HashMap headers, SyncResultCallBack callback) { - - if(callback != null) { - + private void fetchFromNetwork(String urlString, JSONObject urlQueries, HashMap headers, + SyncResultCallBack callback) { + if (callback != null) { HashMap urlParams = getUrlParams(urlQueries); - new CSBackgroundTask(this, CSController.FETCHSYNC, urlString, headers, urlParams, new JSONObject(), CSAppConstants.callController.SYNC.toString(), false, CSAppConstants.RequestMethod.GET, callback); + String requestInfo = REQUEST_CONTROLLER.SYNC.toString(); + new CSBackgroundTask(this, Constants.FETCHSYNC, urlString, headers, urlParams, requestInfo, callback); } } - - private HashMap getUrlParams(JSONObject urlQueriesJSON) { - + private HashMap getUrlParams(JSONObject jsonQuery) { 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) { - logger.severe(e.getLocalizedMessage()); - } + if (jsonQuery != null && jsonQuery.length() > 0) { + Iterator iteString = jsonQuery.keys(); + while (iteString.hasNext()) { + String key = iteString.next(); + Object value = jsonQuery.opt(key); + hashMap.put(key, value); } - - return hashMap; } - - return null; + return hashMap; } - - private HashMap getHeader(HashMap localHeader) { - - HashMap mainHeader = headerGroup_app; - HashMap classHeaders = new HashMap<>(); - - 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 headerGroup_app; - } + /** + * The enum Publish type. + */ + public enum PublishType { + asset_deleted, asset_published, asset_unpublished, content_type_deleted, entry_deleted, entry_published, + entry_unpublished } - - } - diff --git a/src/main/java/com/contentstack/sdk/SyncResultCallBack.java b/src/main/java/com/contentstack/sdk/SyncResultCallBack.java index eb63af2c..52f6625b 100755 --- a/src/main/java/com/contentstack/sdk/SyncResultCallBack.java +++ b/src/main/java/com/contentstack/sdk/SyncResultCallBack.java @@ -1,22 +1,16 @@ package com.contentstack.sdk; +public abstract class SyncResultCallBack implements ResultCallBack { -public abstract class SyncResultCallBack extends ResultCallBack { + public abstract void onCompletion(SyncStack syncStack, Error error); - public abstract void onCompletion(SyncStack syncStack, Error error); + void onRequestFinish(SyncStack syncStack) { + onCompletion(syncStack, null); + } - void onRequestFinish(SyncStack syncStack){ - onCompletion( syncStack, null); - } - - @Override - void onRequestFail(ResponseType responseType, Error error) { - onCompletion(null, error); - } - - @Override - public void always() { - - } + @Override + public void onRequestFail(ResponseType responseType, Error error) { + onCompletion(null, error); + } } diff --git a/src/main/java/com/contentstack/sdk/SyncStack.java b/src/main/java/com/contentstack/sdk/SyncStack.java index c6628e0b..976ae711 100755 --- a/src/main/java/com/contentstack/sdk/SyncStack.java +++ b/src/main/java/com/contentstack/sdk/SyncStack.java @@ -1,33 +1,30 @@ package com.contentstack.sdk; +import org.jetbrains.annotations.NotNull; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; -import java.util.logging.Logger; +import java.util.List; /** - * Synchronization: - * The Sync API takes care of syncing your Contentstack data with your app and - * ensures that the data is always up-to-date by providing delta updates + * Synchronization: The Sync API takes care of syncing your Contentstack data + * with your app and ensures that the data is always up-to-date by providing + * delta updates */ - public class SyncStack { - public static final String REQUEST_URL = ""; - private static final Logger logger = Logger.getLogger(SyncStack.class.getSimpleName()); private JSONObject receiveJson; private int skip; private int limit; private int count; - private String URL; - private String pagination_token; - private String sync_token; + private String url; + private String paginationToken; + private String syncToken; private ArrayList syncItems; - - public String getURL() { - return this.URL; + public String getUrl() { + return this.url; } public JSONObject getJSONResponse() { @@ -47,62 +44,46 @@ public int getSkip() { } public String getPaginationToken() { - return this.pagination_token; + return this.paginationToken; } public String getSyncToken() { - return this.sync_token; + return this.syncToken; } - public ArrayList getItems() { + public List getItems() { return this.syncItems; } - protected void setJSON(JSONObject jsonobject) { - - if (jsonobject != null) { - receiveJson = jsonobject; - try { - if (receiveJson != null) { - - URL = REQUEST_URL; - - if (receiveJson.has("items")) { - JSONArray jsonarray = receiveJson.getJSONArray("items"); - if (jsonarray != null) { - syncItems = new ArrayList<>(); - for (int position = 0; position < jsonarray.length(); position++) { - syncItems.add(jsonarray.optJSONObject(position)); - } - } - } - - if (receiveJson.has("skip")) { - this.skip = receiveJson.optInt("skip"); - } - if (receiveJson.has("total_count")) { - this.count = receiveJson.optInt("total_count"); - } - if (receiveJson.has("limit")) { - this.limit = receiveJson.optInt("limit"); - } - if (receiveJson.has("pagination_token")) { - this.pagination_token = receiveJson.optString("pagination_token"); - } else { - this.pagination_token = null; - } - if (receiveJson.has("sync_token")) { - this.sync_token = receiveJson.optString("sync_token"); - } else { - this.sync_token = null; - } + protected void setJSON(@NotNull JSONObject jsonobject) { + this.receiveJson = jsonobject; + if (receiveJson.has("items")) { + JSONArray jsonarray = receiveJson.getJSONArray("items"); + if (jsonarray != null) { + syncItems = new ArrayList<>(); + for (int position = 0; position < jsonarray.length(); position++) { + syncItems.add(jsonarray.optJSONObject(position)); } - } catch (Exception e) { - logger.severe(e.getLocalizedMessage()); } + } + this.paginationToken = null; + this.syncToken = null; + if (receiveJson.has("skip")) { + this.skip = receiveJson.optInt("skip"); + } + if (receiveJson.has("total_count")) { + this.count = receiveJson.optInt("total_count"); + } + if (receiveJson.has("limit")) { + this.limit = receiveJson.optInt("limit"); + } + if (receiveJson.has("pagination_token")) { + this.paginationToken = receiveJson.optString("pagination_token"); + } + if (receiveJson.has("sync_token")) { + this.syncToken = receiveJson.optString("sync_token"); } } - } diff --git a/src/main/java/com/contentstack/sdk/utility/CSAppConstants.java b/src/main/java/com/contentstack/sdk/utility/CSAppConstants.java deleted file mode 100644 index 489c0259..00000000 --- a/src/main/java/com/contentstack/sdk/utility/CSAppConstants.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.contentstack.sdk.utility; - -/** - * Package Constants - */ -public class CSAppConstants { - - /** - * The constant SDK_VERSION. - */ - public static final String SDK_VERSION = "1.7.0"; - - /** - * The enum Request method. - */ - public static enum RequestMethod - { - /** - * Get request method. - */ - GET, - /** - * Post request method. - */ - POST, - /** - * Put request method. - */ - PUT, - /** - * Delete request method. - */ - DELETE - } - - /** - * The enum Call controller. - */ - public static enum callController { - - /** - * Query call controller. - */ - QUERY, - /** - * Entry call controller. - */ - ENTRY, - /** - * Asset call controller. - */ - ASSET, - /** - * Sync call controller. - */ - SYNC, - /** - * Contenttypes call controller. - */ - CONTENTTYPES, - /** - * Assetlibrary call controller. - */ - ASSETLIBRARY - } - - - /** - * The constant ErrorMessage_JsonNotProper. - */ -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - public final static String ErrorMessage_JsonNotProper = "Please provide valid JSON."; - /** - * The constant ErrorMessage_StackApiKeyIsNull. - */ - public final static String ErrorMessage_StackApiKeyIsNull = "Stack api key can not be null."; - /** - * The constant ErrorMessage_FormName. - */ - public final static String ErrorMessage_FormName = "Please set contentType name."; - /** - * The constant ErrorMessage_Stack_AccessToken_IsNull. - */ - public final static String ErrorMessage_Stack_AccessToken_IsNull = "Access token can not be null."; - /** - * The constant ErrorMessage_Stack_Environment_IsNull. - */ - public final static String ErrorMessage_Stack_Environment_IsNull = "Environment can not be null."; - /** - * The constant ErrorMessage_VolleyNoConnectionError. - */ - public final static String ErrorMessage_VolleyNoConnectionError = "Connection error"; - /** - * The constant ErrorMessage_VolleyAuthFailureError. - */ - public final static String ErrorMessage_VolleyAuthFailureError = "Authentication Not present."; - /** - * The constant ErrorMessage_VolleyParseError. - */ - public final static String ErrorMessage_VolleyParseError = "Parsing Error."; - /** - * The constant ErrorMessage_VolleyServerError. - */ - public final static String ErrorMessage_VolleyServerError = "Server interaction went wrong, Please try again."; - /** - * The constant ErrorMessage_Default. - */ - public final static String ErrorMessage_Default = "Oops! Something went wrong. Please try again."; - /** - * The constant ErrorMessage_NoNetwork. - */ - public final static String ErrorMessage_NoNetwork = "Network not available."; - /** - * The constant ErrorMessage_CalledDefaultMethod. - */ - public final static String ErrorMessage_CalledDefaultMethod = "You must called Contentstack.stack() first"; - /** - * The constant ErrorMessage_QueryFilterException. - */ - public final static String ErrorMessage_QueryFilterException = "Please provide valid params."; -} - diff --git a/src/main/java/com/contentstack/sdk/utility/CSAppUtils.java b/src/main/java/com/contentstack/sdk/utility/CSAppUtils.java deleted file mode 100644 index d3bad39b..00000000 --- a/src/main/java/com/contentstack/sdk/utility/CSAppUtils.java +++ /dev/null @@ -1,214 +0,0 @@ -package com.contentstack.sdk.utility; - -import org.json.JSONObject; - -import java.io.*; -import java.security.MessageDigest; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.TimeZone; - -/** - * Utilities for contentstack - */ -public class CSAppUtils { - - /** - * Instantiates a new Cs app utils. - */ - public CSAppUtils() { - } - - /** - * To retrieve data from cache. - * - * @param file cache file. - * @return cache data in JSON. - */ - public static JSONObject getJsonFromCacheFile(File file) { - - JSONObject json = null; - InputStream input = null; - ByteArrayOutputStream buffer = null; - try { - - input = new BufferedInputStream(new FileInputStream(file)); - buffer = new ByteArrayOutputStream(); - byte[] temp = new byte[1024]; - int read; - while ((read = input.read(temp)) > 0) { - buffer.write(temp, 0, read); - } - json = new JSONObject(buffer.toString("UTF-8")); - buffer.flush(); - buffer.close(); - input.close(); - return json; - - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - /** - * Converts the given date to the user's timezone. - * - * @param date {@link String} - * @param dateFormat {@link String} - * @param timeZone String - * @return Calendar calendar - * @throws ParseException

Example :
        CSAppUtils.parseDate(dateString, "yyyy-MM-dd'T'HH:mm:ssZ", TimeZone.getTimeZone("GMT")); 
- */ - public static Calendar parseDate(String date, String dateFormat, TimeZone timeZone) throws ParseException { - Date dateObject = null; - String month = ""; - String day = ""; - String year = ""; - String hourOfDay = ""; - String min = ""; - String sec = ""; - Calendar cal = Calendar.getInstance(); - - SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormat); - dateObject = dateFormatter.parse(date); - - month = new SimpleDateFormat("MM").format(dateObject); - day = new SimpleDateFormat("dd").format(dateObject); - year = new SimpleDateFormat("yyyy").format(dateObject); - hourOfDay = new SimpleDateFormat("HH").format(dateObject); - min = new SimpleDateFormat("mm").format(dateObject); - sec = new SimpleDateFormat("ss").format(dateObject); - - if (timeZone != null) { - cal.setTimeZone(timeZone); - } else { - cal.setTimeZone(TimeZone.getDefault()); - } - - cal.set(Integer.valueOf(year), Integer.valueOf(month) - 1, Integer.valueOf(day), Integer.valueOf(hourOfDay), Integer.valueOf(min), Integer.valueOf(sec)); - - month = null; - day = null; - year = null; - hourOfDay = null; - min = null; - sec = null; - dateObject = null; - - return cal; - } - - /** - * To check if required response within given time window available in cache - * - * @param file cache file. - * @param time time - * @return true if cache data available which satisfy given time condition. - */ - public boolean getResponseTimeFromCacheFile(File file, long time) { - try { - JSONObject jsonObj = getJsonFromCacheFile(file); - long responseDate = Long.parseLong(jsonObj.optString("timestamp")); - - Calendar responseCalendar = Calendar.getInstance(); - - responseCalendar.add(Calendar.MINUTE, 0); - responseCalendar.set(Calendar.SECOND, 0); - responseCalendar.set(Calendar.MILLISECOND, 0); - responseCalendar.setTimeInMillis(responseDate); - responseCalendar.getTimeInMillis(); - - - Calendar currentCalendar = Calendar.getInstance(); - currentCalendar.setTime(new Date()); - currentCalendar.getTimeInMillis(); - - long dateDiff = (currentCalendar.getTimeInMillis() - responseCalendar.getTimeInMillis()); - long dateDiffInMin = dateDiff / (60 * 1000); - - - if (dateDiffInMin > (time / 60000)) { - return true;// need to send call. - } else { - return false;// no need to send call. - } - - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - /** - * To encrypt given value. - * - * @param value string - * @return MD5 value - */ - public String getMD5FromString(String value) { - String output; - output = value.toString().trim(); - if (value.length() > 0) { - try { - // Create MD5 Hash - MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); - digest.reset(); - digest.update(output.getBytes()); - byte messageDigest[] = digest.digest(); - - // Create Hex String - StringBuffer hexString = new StringBuffer(); - for (int i = 0; i < messageDigest.length; i++) { - - String hex = Integer.toHexString(0xFF & messageDigest[i]); - if (hex.length() == 1) { - hexString.append('0'); - } - hexString.append(hex); - } - - return hexString.toString(); - - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } else { - return null; - } - } - - - /** - * Type to compare dates. - * - * @author Contentstack - */ - public static enum DateComapareType { - /** - * Week date comapare type. - */ - WEEK, - /** - * Day date comapare type. - */ - DAY, - /** - * Hours date comapare type. - */ - HOURS, - /** - * Minutes date comapare type. - */ - MINUTES, - /** - * Seconds date comapare type. - */ - SECONDS - } - - ; -} \ No newline at end of file diff --git a/src/main/java/com/contentstack/sdk/utility/CSController.java b/src/main/java/com/contentstack/sdk/utility/CSController.java deleted file mode 100644 index aaca70e8..00000000 --- a/src/main/java/com/contentstack/sdk/utility/CSController.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.contentstack.sdk.utility; - - -/** - * Controllers. - */ -public class CSController { - - /** - * The constant QUERYOBJECT. - */ - public static final String QUERYOBJECT = "getQueryEntries"; - - /** - * The constant SINGLEQUERYOBJECT. - */ - public static final String SINGLEQUERYOBJECT = "getSingleQueryEntries"; - - /** - * The constant FETCHENTRY. - */ - public static final String FETCHENTRY = "getEntry"; - - /** - * The constant FETCHALLASSETS. - */ - public static final String FETCHALLASSETS = "getAllAssets"; - - /** - * The constant FETCHASSETS. - */ - public static final String FETCHASSETS = "getAssets"; - - /** - * The constant FETCHSYNC. - */ - public static final String FETCHSYNC = "getSync"; - - /** - * The constant FETCHCONTENTTYPES. - */ - public static final String FETCHCONTENTTYPES = "getContentTypes"; -} diff --git a/src/main/java/com/contentstack/sdk/utility/ContentstackUtil.java b/src/main/java/com/contentstack/sdk/utility/ContentstackUtil.java deleted file mode 100644 index 1fb6eac0..00000000 --- a/src/main/java/com/contentstack/sdk/utility/ContentstackUtil.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.contentstack.sdk.utility; - - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.TimeZone; - -/** - * Used for the contentstack Utility - */ - -public class ContentstackUtil { - - /** - * Converts the given date to user's timezone. - * @param date date in ISO format. - * @param timeZone timezone selection - * @return {@link Calendar} object. - * @throws ParseException - * - *

Example :
- *
-     *   BuiltUtil.parseDate(dateString, TimeZone.getDefault());
-     * 
- * - */ - public static Calendar parseDate(String date, TimeZone timeZone) throws ParseException { - 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'"); - knownPatterns.add("yyyy-MM-dd'T'HH:mmZ"); - knownPatterns.add("yyyy-MM-dd'T'HH:mm'Z'"); - knownPatterns.add("yyyy-MM-dd'T'HH:mm'Z'"); - knownPatterns.add("yyyy-MM-dd'T'HH:mm:ss"); - knownPatterns.add("yyyy-MM-dd' 'HH:mm:ss"); - knownPatterns.add("yyyy-MM-dd"); - knownPatterns.add("HH:mm:ssZ"); - knownPatterns.add("HH:mm:ss'Z'"); - - for (String formatString : knownPatterns){ - try { - return parseDate(date, formatString, timeZone); - - }catch (ParseException e) {} - } - - return null; - } - - /** - * Converts the given date to the user's timezone. - * @param date date in string format. - * @param dateFormat date format. - * @param timeZone TimeZone. - * @return {@link Calendar} object. - * @throws ParseException - * - *

Example :
- *
-     *   BuiltUtil.parseDate(dateString, "yyyy-MM-dd'T'HH:mm:ssZ", TimeZone.getTimeZone("GMT"));
-     * 
- */ - - public static Calendar parseDate(String date, String dateFormat, TimeZone timeZone) throws ParseException { - Date dateObject = null; - String month = ""; - String day = ""; - String year = ""; - String hourOfDay = ""; - String min = ""; - String sec = ""; - Calendar cal = Calendar.getInstance(); - - SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormat); - dateObject = dateFormatter.parse(date); - - month = new SimpleDateFormat("MM").format(dateObject); - day = new SimpleDateFormat("dd").format(dateObject); - year = new SimpleDateFormat("yyyy").format(dateObject); - hourOfDay = new SimpleDateFormat("HH").format(dateObject); - min = new SimpleDateFormat("mm").format(dateObject); - sec = new SimpleDateFormat("ss").format(dateObject); - - if(timeZone != null){ - cal.setTimeZone(timeZone); - }else{ - cal.setTimeZone(TimeZone.getDefault()); - } - - cal.set(Integer.parseInt(year), Integer.parseInt(month)-1, Integer.parseInt(day), Integer.parseInt(hourOfDay), Integer.parseInt(min), Integer.parseInt(sec)); - - month = null; - day = null; - year = null; - hourOfDay = null; - min = null; - sec = null; - dateObject = null; - - return cal; - } - -} diff --git a/src/test/java/com/contentstack/sdk/AssetTestCase.java b/src/test/java/com/contentstack/sdk/AssetTestCase.java deleted file mode 100644 index 03052b9f..00000000 --- a/src/test/java/com/contentstack/sdk/AssetTestCase.java +++ /dev/null @@ -1,301 +0,0 @@ -package com.contentstack.sdk; - -import io.github.cdimascio.dotenv.Dotenv; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; - -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertTrue; - - -/** - * The type Asset test case. - */ -// Run testcase for the particular class -// run mvn -Dtest=TestAssetTestCase test -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class AssetTestCase { - - private static final Logger logger = Logger.getLogger(AssetTestCase.class.getName()); - private static String ASSET_UID = null; - private static Stack stack; - private static String DEFAULT_HOST; - - /** - * One time set up. - * - * @throws Exception the exception - */ - @BeforeClass - public static void oneTimeSetUp() throws Exception { - logger.setLevel(Level.FINE); - Dotenv dotenv = Dotenv.load(); - String DEFAULT_API_KEY = dotenv.get("API_KEY"); - String DEFAULT_DELIVERY_TOKEN = dotenv.get("DELIVERY_TOKEN"); - String DEFAULT_ENV = dotenv.get("ENVIRONMENT"); - DEFAULT_HOST = dotenv.get("HOST"); - Config config = new Config(); - config.setHost(DEFAULT_HOST); - assert DEFAULT_API_KEY != null; - stack = Contentstack.stack(DEFAULT_API_KEY, DEFAULT_DELIVERY_TOKEN, DEFAULT_ENV, config); - logger.info("Asset TestCase started..."); - } - - /** - * Sets up the test fixture. - * (Called before every test case method.) - */ - @BeforeClass - public static void beforeClass() { - // Get all the assets available - logger.info("Started Running asset testcases"); - final AssetLibrary assetLibrary = stack.assetLibrary(); - assetLibrary.fetchAll(new FetchAssetsCallback() { - public void onCompletion(ResponseType responseType, List assets, Error error) { - if (error == null) { - assets.stream().iterator().forEachRemaining(asset -> { - if (asset.getFileName().equalsIgnoreCase("phoenix2.jpg")) { - ASSET_UID = asset.getAssetUid(); - } - }); - } - } - }); - } - - /** - * After class. - */ - @AfterClass - public static void afterClass() { - logger.info("Ran all asset testcases"); - } - - /** - * Test a get all assets to set asset uid. - */ - @Test() - public void test_A_getAllAssetsToSetAssetUID() { - final AssetLibrary assetLibrary = stack.assetLibrary(); - assetLibrary.fetchAll(new FetchAssetsCallback() { - public void onCompletion(ResponseType responseType, List assets, Error error) { - if (error == null) { - logger.info("response: " + assets.get(0).getAssetUid()); - ASSET_UID = assets.get(0).getAssetUid(); - } - } - }); - } - - - /** - * Test b verify asset uid. - */ - @Test - public void test_B_VerifyAssetUID() { - - final Asset asset = stack.asset(ASSET_UID); - asset.fetch(new FetchResultCallback() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - // Success Block. - logger.info("response: " + asset.getAssetUid()); - assertEquals(ASSET_UID, asset.getAssetUid()); - } - } - }); - } - - /** - * Test c asset fetch. - */ - @Test - public void test_C_Asset_fetch() { - final Asset asset = stack.asset(ASSET_UID); - asset.fetch(new FetchResultCallback() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - assertEquals(ASSET_UID, asset.getAssetUid()); - assertEquals("image/jpeg", asset.getFileType()); - assertEquals("blt69a06b75160147adc2c8b3a9", asset.getCreatedBy()); - assertEquals("sys_blt309cacf8ab432f62", asset.getUpdatedBy()); - assertEquals("phoenix2.jpg", asset.getFileName()); - assertEquals("482141", asset.getFileSize()); - if (DEFAULT_HOST.equalsIgnoreCase("cdn.contentstack.io")) { - assertEquals("https://images.contentstack.io/v3/assets/blt12c8ad610ff4ddc2/blt5312f71416d6e2c8/5704eda29ebb5cce3597b877/phoenix2.jpg", asset.getUrl()); - } else { - assertEquals("https://stag-images.contentstack.io/v3/assets/blt12c8ad610ff4ddc2/blt5312f71416d6e2c8/5704eda29ebb5cce3597b877/phoenix2.jpg", asset.getUrl()); - } - } - } - }); - } - - /** - * Test d asset library fetch. - */ - @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 -> { - logger.info("----Test--Asset-D--Success----" + asset.toJSON()); - logger.info("----Test--Asset-D--Success----" + asset.getFileType()); - logger.info("----Test--Asset-D--Success----" + asset.getCreatedBy()); - logger.info("----Test--Asset-D--Success----" + asset.getUpdatedBy()); - logger.info("----Test--Asset-D--Success----" + asset.getFileName()); - logger.info("----Test--Asset-D--Success----" + asset.getFileSize()); - logger.info("----Test--Asset-D--Success----" + asset.getAssetUid()); - logger.info("----Test--Asset-D--Success----" + asset.getUrl()); - }); - } - } - }); - } - - /** - * Test e asset library include count fetch. - */ - @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) { - if (DEFAULT_HOST.equalsIgnoreCase("cdn.contentstack.io")) { - assertEquals(16, assetLibrary.getCount()); - } else { - assertEquals(20, assetLibrary.getCount()); - } - } - } - }); - } - - /** - * Test f asset library include relative url fetch. - */ - @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) { - assertEquals("/v3/assets/blt12c8ad610ff4ddc2/blt5312f71416d6e2c8/5704eda29ebb5cce3597b877/phoenix2.jpg", assets.get(0).getUrl()); - } - } - }); - } - - /** - * Test g stack get params. - */ - @Test - public void test_G_StackGetParams() { - final Asset asset = stack.asset(ASSET_UID); - asset.addParam("key", "some_value"); - asset.fetch(new FetchResultCallback() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - logger.warning(asset.getAssetUid()); - assertEquals(ASSET_UID, asset.getAssetUid()); - } else { - assertEquals(404, error.getErrorCode()); - } - } - }); - } - - /** - * Test h asset locale include fallback. - */ - @Test - public void test_H_Asset_Locale_Include_Fallback() { - final Asset asset = stack.asset(ASSET_UID); - asset.includeFallback(); - asset.fetch(new FetchResultCallback() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - logger.warning(asset.getAssetUid()); - } else { - assertEquals("Not Found", error.getErrorMessage()); - } - assertTrue(asset.urlQueries.has("include_fallback")); - } - }); - } - - /** - * Test h asset include dimension. - */ - @Test - public void test_H_Asset_Include_Dimension() { - final Asset asset = stack.asset(ASSET_UID); - asset.includeDimension(); - asset.fetch(new FetchResultCallback() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - logger.warning(asset.toJSON().optString("include_dimension")); - } else { - logger.warning(error.getErrorDetail()); - assertEquals(error.getErrorDetail(), "{\"uid\":[\"is not valid.\"]}"); - } - } - }); - } - - - /** - * Test i asset include dimension using add params. - */ - @Test - public void test_I_Asset_Include_Dimension_using_addParams() { - final Asset asset = stack.asset(ASSET_UID); - asset.addParam("include_dimension", "true"); - asset.fetch(new FetchResultCallback() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - logger.warning(asset.toJSON().optString("include_dimension")); - // assertEquals(assetUid, asset.getAssetUid()); - } - } - }); - } - - /** - * Test j include fallback. - */ - @Test() - public void test_J_include_fallback() { - final AssetLibrary assetLibrary = stack.assetLibrary(); - assetLibrary.includeFallback().fetchAll(new FetchAssetsCallback() { - public void onCompletion(ResponseType responseType, List assets, Error error) { - if (error == null) { - logger.info("response: " + assets.get(0).getAssetUid()); - assertTrue(assetLibrary.urlQueries.has("include_fallback")); - } - } - }); - } - -} diff --git a/src/test/java/com/contentstack/sdk/EntryTestCase.java b/src/test/java/com/contentstack/sdk/EntryTestCase.java deleted file mode 100644 index 7526782a..00000000 --- a/src/test/java/com/contentstack/sdk/EntryTestCase.java +++ /dev/null @@ -1,325 +0,0 @@ -package com.contentstack.sdk; - -import io.github.cdimascio.dotenv.Dotenv; -import junit.framework.TestCase; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; - -import java.util.ArrayList; -import java.util.logging.Logger; - -import static junit.framework.TestCase.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - - -/** - * The type Entry test case. - */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class EntryTestCase { - - private static final Logger logger = Logger.getLogger(EntryTestCase.class.getName()); - private static final String CONTENT_TYPE = "product"; - private static String entryUID = null; - private static Stack stack; - - - /** - * One time set up. - * - * @throws Exception the exception - */ - @BeforeClass - public static void oneTimeSetUp() throws Exception { - // Loading credentials - Dotenv dotenv = Dotenv.load(); - String DEFAULT_API_KEY = dotenv.get("API_KEY"); - String DEFAULT_DELIVERY_TOKEN = dotenv.get("DELIVERY_TOKEN"); - String DEFAULT_ENV = dotenv.get("ENVIRONMENT"); - String DEFAULT_HOST = dotenv.get("HOST"); - Config config = new Config(); - config.setHost(DEFAULT_HOST); - - assert DEFAULT_API_KEY != null; - stack = Contentstack.stack(DEFAULT_API_KEY, DEFAULT_DELIVERY_TOKEN, DEFAULT_ENV, config); - final Query query = stack.contentType(CONTENT_TYPE).query(); - query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - if (error == null) { - entryUID = queryresult.getResultObjects().get(15).getUid(); - System.out.println(entryUID); - } - } - }); - } - - - /** - * Test 01 find all entries. - */ - @Test - public void test_01_findAllEntries() { - final Query query = stack.contentType(CONTENT_TYPE).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 02 only fetch. - */ - @Test - public void test_02_only_fetch() { - final Entry entry = stack.contentType(CONTENT_TYPE).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().get("price")); - } - } - }); - } - - /** - * Test 03 except fetch. - */ - @Test - public void test_03_except_fetch() { - final Entry entry = stack.contentType(CONTENT_TYPE).entry(entryUID); - entry.except(new String[]{"title"}); - entry.fetch(new EntryResultCallBack() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - assertFalse(entry.toJSON().has("title")); - } else { - assertEquals(422, error.getErrorCode()); - } - } - }); - } - - /** - * Test 04 include reference fetch. - */ - @Test - public void test_04_includeReference_fetch() { - final Entry entry = stack.contentType(CONTENT_TYPE).entry(entryUID); - entry.includeReference(new String[]{"brand", "categories"}); - entry.fetch(new EntryResultCallBack() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - JSONArray categoryArray = entry.getJSONArray("category"); - categoryArray.forEach(object -> assertTrue(object.toString().contains("_content_type_uid"))); - } - } - }); - } - - /** - * Test 05 include reference only fetch. - */ - @Test - public void test_05_includeReferenceOnly_fetch() { - final Entry entry = stack.contentType(CONTENT_TYPE).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().getString("title")); - } - } - }); - - } - - - /** - * Test 06 include reference except fetch. - */ - @Test - public void test_06_includeReferenceExcept_fetch() { - final Entry entry = stack.contentType(CONTENT_TYPE).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) { - logger.info(entry.getTitle()); - } - }); - } - - - /** - * Test 07 get markdown fetch. - */ - @Test - public void test_07_getMarkdown_fetch() { - final Entry entry = stack.contentType("user").entry(entryUID); - entry.fetch(new EntryResultCallBack() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - logger.info(entry.getTitle()); - } - }); - } - - - /** - * Test 08 get. - */ - @Test - public void test_08_get() { - final Entry entry = stack.contentType("user").entry(entryUID); - entry.fetch(new EntryResultCallBack() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - logger.info(entry.getTitle()); - } - }); - } - - - /** - * Test 09 get param. - */ - @Test - public void test_09_getParam() { - 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) { - logger.info(entry.getTitle()); - } - }); - } - - - /** - * Test 10 include reference content type uid. - */ - @Test - public void test_10_IncludeReferenceContentTypeUID() { - 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) { - e.printStackTrace(); - } - } - } - }); - } - - - /** - * Test 11 locale. - */ - @Test - public void test_11_Locale() { - 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(); - logger.warning(checkResp); - } - } - }); - } - - /** - * Test 12 entry except. - */ - @Test - public void test_12_entry_except() { - 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(); - logger.warning(checkResp); - } - } - }); - } - - - /** - * Test 13 entry include fallback. - */ - @Test - public void test_13_entry_include_fallback() { - final Entry entry = stack.contentType("categories").entry(entryUID).setLocale("hi-in"); - entry.setLocale(""); - entry.includeFallback().fetch(new EntryResultCallBack() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - String checkResp = entry.getLocale(); - assertEquals("en-us", checkResp); - } - TestCase.assertTrue(entry.otherPostJSON.has("include_fallback")); - } - }); - } - - /** - * Test 14 entry include embedded items. - * - * @throws Exception the exception - */ - @Test - public void test_14_entry_include_embedded_items() throws Exception { - final Entry entry = stack.contentType("categories").entry(entryUID); - entry.includeEmbeddedItems().fetch(new EntryResultCallBack() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - boolean _embedded_items = entry.toJSON().has("_embedded_items"); - TestCase.assertTrue(_embedded_items); - } - TestCase.assertTrue(entry.otherPostJSON.has("include_embedded_items[]")); - } - }); - } - -} diff --git a/src/test/java/com/contentstack/sdk/ImageTransformTestcase.java b/src/test/java/com/contentstack/sdk/ImageTransformTestcase.java deleted file mode 100644 index d8aad2c2..00000000 --- a/src/test/java/com/contentstack/sdk/ImageTransformTestcase.java +++ /dev/null @@ -1,231 +0,0 @@ -package com.contentstack.sdk; - -import io.github.cdimascio.dotenv.Dotenv; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.JUnitCore; - -import java.util.LinkedHashMap; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * The type Image transform testcase. - */ -public class ImageTransformTestcase extends JUnitCore { - - private static final Logger logger = Logger.getLogger(ImageTransformTestcase.class.getName()); - private static Stack stack; - private final LinkedHashMap imageParams = new LinkedHashMap<>(); - private final String IMAGE_URL = "https://images.contentstack.io/v3/assets/blt903007d63561dea2/blt638399801b6bd23c/59afa6406c11eb860ddf04aa/download"; - - - /** - * One time set up. - * - * @throws Exception the exception - */ - @BeforeClass - public static void oneTimeSetUp() throws Exception { - logger.setLevel(Level.FINE); - Dotenv dotenv = Dotenv.load(); - String DEFAULT_API_KEY = dotenv.get("API_KEY"); - String DEFAULT_DELIVERY_TOKEN = dotenv.get("DELIVERY_TOKEN"); - String DEFAULT_ENV = dotenv.get("ENVIRONMENT"); - String DEFAULT_HOST = dotenv.get("HOST"); - Config config = new Config(); - config.setHost(DEFAULT_HOST); - assert DEFAULT_API_KEY != null; - stack = Contentstack.stack(DEFAULT_API_KEY, DEFAULT_DELIVERY_TOKEN, DEFAULT_ENV, config); - logger.info("test started..."); - } - - /** - * One time tear down. - */ - @AfterClass - public static void oneTimeTearDown() { - // one-time cleanup code - logger.info("When all the test cases of class finishes..."); - } - - - /** - * Tear down. - */ - @After - public void tearDown() { - logger.info("Runs after every testcase completes."); - } - - - /** - * Test 00 fetch all image transformation. - */ - @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; - /* 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]; - logger.info("pairs:--> " + keyValueParis); - ++counter; - } - } - } else { - logger.info("Testcases Failed"); - } - if (counter == imageParams.size()) { - logger.info("Testcases Passed"); - } else { - logger.info("Testcases Failed"); - } - } - - - /** - * Test 01 fetch all image transformation. - */ - @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.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]; - logger.info("pairs:--> " + keyValueParis); - ++counter; - } - } - } else { - logger.info("Testcases Failed"); - } - - if (counter == imageParams.size()) { - logger.info("Testcases Passed"); - } else { - logger.info("Testcases Failed"); - } - } - - - /** - * Test 02 fetch all image transformation. - */ - @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]; - logger.info("pairs:--> " + keyValueParis); - ++counter; - } - } - } else { - logger.info("Testcases Failed"); - - } - - if (counter == imageParams.size()) { - - logger.info("Testcases Passed"); - } else { - logger.info("Testcases Failed"); - - } - } - - - /** - * Test 03 fetch all image transformation. - */ - @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.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]; - logger.info("pairs:--> " + keyValueParis); - ++counter; - } - } - } else { - logger.info("Testcases Failed"); - - } - - if (counter == imageParams.size()) { - logger.info("Testcases Passed"); - } else { - logger.info("Testcases Failed"); - } - } -} diff --git a/src/test/java/com/contentstack/sdk/QueryTestCase.java b/src/test/java/com/contentstack/sdk/QueryTestCase.java index f0a4f06f..5cce1ac1 100644 --- a/src/test/java/com/contentstack/sdk/QueryTestCase.java +++ b/src/test/java/com/contentstack/sdk/QueryTestCase.java @@ -1,13 +1,9 @@ package com.contentstack.sdk; import io.github.cdimascio.dotenv.Dotenv; -import junit.framework.TestCase; import org.json.JSONArray; import org.json.JSONObject; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.*; import java.util.ArrayList; import java.util.Iterator; @@ -15,25 +11,20 @@ import java.util.logging.Level; import java.util.logging.Logger; -import static junit.framework.TestCase.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class QueryTestCase { -/** - * The type Query test case. - */ -public class QueryTestCase { + private final Logger logger = Logger.getLogger(QueryTestCase.class.getName()); + private Stack stack; + private Query query; + private String entryUid; - private static final Logger logger = Logger.getLogger(AssetTestCase.class.getName()); - private static Stack stack; - private static Query query, queryFallback; - - /** - * One time set up. - * - * @throws Exception the exception - */ - @BeforeClass - public static void oneTimeSetUp() throws Exception { + @BeforeAll + public void beforeAll() throws IllegalAccessException { logger.setLevel(Level.FINE); Dotenv dotenv = Dotenv.load(); String DEFAULT_API_KEY = dotenv.get("API_KEY"); @@ -42,62 +33,36 @@ public static void oneTimeSetUp() throws Exception { String DEFAULT_HOST = dotenv.get("HOST"); Config config = new Config(); config.setHost(DEFAULT_HOST); + config.setRegion(Config.ContentstackRegion.US); assert DEFAULT_API_KEY != null; stack = Contentstack.stack(DEFAULT_API_KEY, DEFAULT_DELIVERY_TOKEN, DEFAULT_ENV, config); - logger.info("Asset Test Case Running..."); - query = stack.contentType("product").query(); - queryFallback = stack.contentType("categories").query(); - logger.info("test started..."); } - /** - * One time tear down. - */ - @AfterClass() - public static void oneTimeTearDown() { - logger.info("When all the test cases of class finishes..."); - } - - /** - * Sets up the test fixture. - * (Called before every test case method.) - */ - @BeforeClass() - public static void setUp() { + @BeforeEach + public void beforeEach() { query = stack.contentType("product").query(); } - - /** - * Tears down the test fixture. - * (Called after every test case method.) - */ - @After() - public void tearDown() { - logger.info("Runs after every testcase completes."); - } - - - /** - * Test 01 fetch all entries. - */ - @Test() - public void test_01_fetchAllEntries() { + @Test + @Order(1) + void testAllEntries() { query.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { - logger.fine(queryresult.toString()); + entryUid = queryresult.getResultObjects().get(0).uid; + Assertions.assertNotNull(queryresult); + Assertions.assertEquals(27, queryresult.getResultObjects().size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - /** - * Test 02 fetch single entry. - */ @Test() - public void test_02_fetchSingleEntry() { + @Order(2) + void testWhereEquals() { Query query = stack.contentType("categories").query(); query.where("title", "Women"); query.find(new QueryResultsCallBack() { @@ -105,37 +70,52 @@ public void test_02_fetchSingleEntry() { public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { List titles = queryresult.getResultObjects(); - titles.forEach(title -> logger.info("title: " + title.getString("title"))); + Assertions.assertEquals("Women", titles.get(0).title); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } + @Test() + @Order(4) + void testWhereEqualsWithUid() { + query.where("uid", this.entryUid); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + List titles = queryresult.getResultObjects(); + Assertions.assertEquals("Blue Yellow", titles.get(0).title); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } - /** - * Test 03 fetch single non existing entry. - */ @Test() - public void test_03_fetchSingleNonExistingEntry() { - Query query = stack.contentType("categories").query(); - query.where("uid", "blta3b58d6893d8935b"); + @Order(3) + void testWhere() { + Query query = stack.contentType("product").query(); + query.where("title", "Blue Yellow"); query.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { List listOfEntries = queryresult.getResultObjects(); - logger.finest(listOfEntries.toString()); + Assertions.assertEquals("Blue Yellow", listOfEntries.get(0).title); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 04 fetch entry with include reference. - */ @Test - public void test_04_fetchEntryWithIncludeReference() { + @Order(4) + void testIncludeReference() { query.includeReference("category"); query.find(new QueryResultsCallBack() { @Override @@ -143,145 +123,137 @@ public void onCompletion(ResponseType responseType, QueryResult queryresult, Err if (error == null) { List listOfEntries = queryresult.getResultObjects(); logger.fine(listOfEntries.toString()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 05 fetch entry not contained in field. - */ @Test - public void test_05_fetchEntryNotContainedInField() { - String[] containArray = new String[]{"Roti Maker", "kids dress"}; + @Order(5) + void testNotContainedInField() { + 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(); - entries.forEach(entry -> logger.info(entry.getString("price"))); + Assertions.assertEquals(25, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 06 fetch entry contained in field. - */ @Test - public void test_06_fetchEntryContainedInField() { - String[] containArray = new String[]{"Roti Maker", "kids dress"}; + @Order(6) + void testContainedInField() { + String[] containArray = new String[] { "Roti Maker", "kids dress" }; query.containedIn("title", containArray); query.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { List entries = queryresult.getResultObjects(); - entries.forEach(entry -> logger.info(entry.getString("price"))); + Assertions.assertEquals(2, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 07 fetch entry not equal to field. - */ @Test - public void test_07_fetchEntryNotEqualToField() { + @Order(7) + void testNotEqualTo() { 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 -> logger.info(entry.getString("title"))); + Assertions.assertEquals(26, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 08 fetch entry greater than equal to field. - */ @Test - public void test_08_fetchEntryGreaterThanEqualToField() { + @Order(8) + void testGreaterThanOrEqualTo() { 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 -> logger.info(entry.getString("price"))); + Assertions.assertEquals(10, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 09 fetch entry greater than field. - */ @Test - public void test_09_fetchEntryGreaterThanField() { + @Order(9) + void testGreaterThanField() { 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 -> logger.info(entry.getString("price"))); + Assertions.assertEquals(9, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 10 fetch entry less than equal field. - */ @Test - public void test_10_fetchEntryLessThanEqualField() { + @Order(10) + void testLessThanEqualField() { 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(); - entries.forEach(entry -> logger.info(entry.getString("price"))); + Assertions.assertEquals(17, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 11 fetch entry less than field. - */ @Test - public void test_11_fetchEntryLessThanField() { + @Order(11) + void testLessThanField() { 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 -> logger.info("Is price less than 90..? " + entry.get("price"))); + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(0, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 12 fetch entries with or. - */ @Test - public void test_12_fetchEntriesWithOr() { + @Order(12) + void testEntriesWithOr() { ContentType ct = stack.contentType("product"); Query orQuery = ct.query(); @@ -290,7 +262,7 @@ public void test_12_fetchEntriesWithOr() { query.lessThan("price", 90); Query subQuery = ct.query(); - subQuery.containedIn("discount", new Integer[]{20, 45}); + subQuery.containedIn("discount", new Integer[] { 20, 45 }); ArrayList array = new ArrayList<>(); array.add(query); @@ -302,19 +274,18 @@ public void test_12_fetchEntriesWithOr() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { - List listOfEntries = queryresult.getResultObjects(); - logger.fine(listOfEntries.toString()); + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(18, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 13 fetch entries with and. - */ @Test - public void test_13_fetchEntriesWithAnd() { + @Order(13) + void testEntriesWithAnd() { ContentType ct = stack.contentType("product"); Query orQuery = ct.query(); @@ -323,7 +294,7 @@ public void test_13_fetchEntriesWithAnd() { query.lessThan("price", 90); Query subQuery = ct.query(); - subQuery.containedIn("discount", new Integer[]{20, 45}); + subQuery.containedIn("discount", new Integer[] { 20, 45 }); ArrayList array = new ArrayList<>(); array.add(query); @@ -334,74 +305,70 @@ public void test_13_fetchEntriesWithAnd() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { - List listOfEntries = queryresult.getResultObjects(); - logger.fine(listOfEntries.toString()); + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(2, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 14 add query. - */ @Test - public void test_14_addQuery() { + @Order(14) + void testAddQuery() { 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(); - logger.finest(listOfEntries.toString()); + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(8, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 15 remove query from query. - */ @Test - public void test_15_removeQueryFromQuery() { + @Order(15) + void testRemoveQueryFromQuery() { 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(); - logger.finest(listOfEntries.toString()); + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(27, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 16 include schema. - */ @Test - public void test_16_includeSchema() { + @Order(16) + void testIncludeSchema() { query.includeContentType(); query.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { - JSONObject contentTypeObj = queryresult.getContentType(); - logger.finest(contentTypeObj.toString()); + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(27, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 17 search. - */ @Test - public void test_17_search() { + @Order(17) + void testSearch() { query.search("dress"); query.find(new QueryResultsCallBack() { @Override @@ -413,275 +380,293 @@ public void onCompletion(ResponseType responseType, QueryResult queryresult, Err 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")) - logger.info(value.toString()); - } catch (Exception e) { - logger.info("----------------setQueryJson" + e.toString()); - } + Object value = jsonObject.opt(key); + Assertions.assertNotNull(value); } } + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 18 ascending. - */ @Test - public void test_18_ascending() { + @Order(18) + void testAscending() { 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) { - logger.info(entry.getString("title")); + for (int i = 0; i < entries.size(); i++) { + String previous = entries.get(i).getTitle(); // get first string + String next = entries.get(i + 1).getTitle(); // get second string + if (previous.compareTo(next) < 0) { // compare both if less than Zero then Ascending else + // descending + Assertions.assertTrue(true); + } else { + Assertions.fail("expected descending, found ascending"); + } } + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 19 descending. - */ @Test - public void test_19_descending() { + @Order(19) + void testDescending() { 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) { - logger.info(entry.getString("title")); + for (int i = 0; i < entries.size(); i++) { + String previous = entries.get(i).getTitle(); // get first string + String next = entries.get(i + 1).getTitle(); // get second string + if (previous.compareTo(next) < 0) { // compare both if less than Zero then Ascending else + // descending + Assertions.fail("expected descending, found ascending"); + } else { + Assertions.assertTrue(true); + } } + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 20 limit. - */ @Test - public void test_20_limit() { + @Order(20) + void testLimit() { 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) { - logger.info(" entry = [" + entry.getString("title") + "]"); - } + Assertions.assertEquals(3, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 21 skip. - */ @Test - public void test_21_skip() { + @Order(21) + void testSkip() { query.skip(3); query.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { List entries = queryresult.getResultObjects(); - logger.fine(entries.toString()); + Assertions.assertEquals(24, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 22 only. - */ @Test - public void test_22_only() { - query.only(new String[]{"price"}); + @Order(22) + void testOnly() { + 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(); - logger.fine(entries.toString()); + Assertions.assertEquals(0, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 23 except. - */ @Test - public void test_23_except() { - query.locale("en-eu"); - query.except(new String[]{"price", "chutiya"}); + @Order(23) + void testExcept() { + query.except(new String[] { "price" }); query.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { List entries = queryresult.getResultObjects(); - logger.fine(entries.toString()); + Assertions.assertEquals(27, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 24 count. - */ @Test - public void test_24_count() { + @Order(24) + @Deprecated + void testCount() { query.count(); query.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { - int count = queryresult.getCount(); - logger.fine("count: " + count); + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(0, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 25 regex. - */ @Test - public void test_25_regex() { + @Order(25) + void testRegex() { 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(); - logger.fine(entries.toString()); - } - } - }); - } - - - /** - * Test 26 exist. - */ - @Test - public void test_26_exist() { + Assertions.assertEquals(1, entries.size()); + // to add in the coverage code execution + Group group = new Group(stack, entries.get(0).toJSON()); + doSomeBackgroundTask(group); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + protected void doSomeBackgroundTask(Group group) { + JSONObject groupJsonObject = group.toJSON(); + Assertions.assertNotNull(groupJsonObject); + Assertions.assertNotNull(groupJsonObject); + Object titleObj = group.get("title"); + String titleStr = group.getString("title"); + Boolean titleBool = group.getBoolean("in_stock"); + JSONArray titleJSONArray = group.getJSONArray("image"); + JSONObject titleJSONObject = group.getJSONObject("publish_details"); + Object versionNum = group.getNumber("_version"); + Object versionInt = group.getInt("_version"); + Float versionFloat = group.getFloat("_version"); + Double versionDouble = group.getDouble("_version"); + long versionLong = group.getLong("_version"); + logger.fine("versionLong: " + versionLong); + Assertions.assertNotNull(titleObj); + Assertions.assertNotNull(titleStr); + Assertions.assertNotNull(titleBool); + Assertions.assertNotNull(titleJSONArray); + Assertions.assertNotNull(titleJSONObject); + Assertions.assertNotNull(versionNum); + Assertions.assertNotNull(versionInt); + Assertions.assertNotNull(versionFloat); + Assertions.assertNotNull(versionDouble); + } + + @Test + @Order(26) + void testExist() { query.exists("title"); query.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { List entries = queryresult.getResultObjects(); - logger.fine(entries.toString()); + Assertions.assertEquals(27, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 27 not exist. - */ @Test - public void test_27_notExist() { + @Order(27) + void testNotExist() { query.notExists("price1"); query.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { - int entryCount = queryresult.getCount(); - logger.fine("entry:" + entryCount); + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(27, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 28 tags. - */ @Test - public void test_28_tags() { - query.tags(new String[]{"pink"}); + @Order(28) + void testTags() { + 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(); - logger.fine(entries.toString()); + Assertions.assertEquals(1, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); - } - - /** - * Test 29 language. - */ @Test - public void test_29_language() { + @Order(29) + void testLanguage() { query.locale("en-us"); query.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { List entries = queryresult.getResultObjects(); - logger.fine(entries.toString()); + Assertions.assertEquals(27, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); - } - - /** - * Test 30 include count. - */ @Test - public void test_30_includeCount() { + @Order(30) + void testIncludeCount() { query.includeCount(); - query.where("uid", "blt3976eac6d3a0cb74"); query.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { - List entries = queryresult.getResultObjects(); - logger.fine(entries.toString()); + Assertions.assertTrue(queryresult.receiveJson.has("count")); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 31 include reference only fetch. - */ @Test - public void test_31_includeReferenceOnly_fetch() { + @Order(31) + void testIncludeReferenceOnly() { final Query query = stack.contentType("multifield").query(); - query.where("uid", "blt1b1cb4f26c4b682e"); + query.where("uid", "fakeIt"); ArrayList strings = new ArrayList<>(); strings.add("title"); @@ -700,21 +685,19 @@ public void test_31_includeReferenceOnly_fetch() { public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { List entries = queryresult.getResultObjects(); - logger.fine(entries.toString()); + Assertions.assertEquals(0, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); - } - - /** - * Test 32 include reference except fetch. - */ @Test - public void test_32_includeReferenceExcept_fetch() { - query = query.where("uid", "blt7801c5d40cbbe979"); + @Order(32) + void testIncludeReferenceExcept() { + query = query.where("uid", "fakeit"); ArrayList strings = new ArrayList<>(); strings.add("title"); query.exceptWithReferenceUid(strings, "category"); @@ -723,141 +706,110 @@ public void test_32_includeReferenceExcept_fetch() { public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { List entries = queryresult.getResultObjects(); - logger.fine(entries.toString()); + Assertions.assertEquals(0, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); - } - - /** - * Test 33 find one. - */ @Test - public void test_33_findOne() { + @Order(33) + void testFindOne() { query.includeCount(); query.where("in_stock", true); query.findOne(new SingleQueryResultCallback() { @Override public void onCompletion(ResponseType responseType, Entry entry, Error error) { if (error == null) { - logger.fine(entry.toJSON().getString("in_stock")); + String entries = entry.getTitle(); + Assertions.assertNotNull(entries); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 34 complex find. - */ @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.*******"); + @Order(34) + void testComplexFind() { + 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() { - private void accept(Entry entry) { - logger.info(entry.getTitle()); - } - @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { List entries = queryresult.getResultObjects(); - entries.forEach(this::accept); + Assertions.assertEquals(27, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 35 include schema. - */ @Test - public void test_35_includeSchema() { + @Order(35) + void testIncludeSchemaCheck() { query.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - JSONArray result; if (error == null) { - result = queryresult.getSchema(); - logger.fine(result.toString()); + JSONArray schema = queryresult.getSchema(); + Assertions.assertEquals(27, schema.length()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 36 include content type. - */ @Test - public void test_36_includeContentType() { + @Order(36) + void testIncludeContentType() { query.includeContentType(); query.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { - JSONObject entries = queryresult.getContentType(); - logger.fine(entries.toString()); - } - } - }); - } - - - /** - * Test 38 include content type. - */ - @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(); - logger.fine(result.toString()); + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(27, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 39 include content type. - */ @Test - public void test_39_include_content_type() { + @Order(37) + void testIncludeContentTypeFetch() { query.includeContentType(); query.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { - JSONObject entries = queryresult.getContentType(); - logger.fine(entries.toString()); + JSONObject contentType = queryresult.getContentType(); + Assertions.assertEquals("", contentType.optString("")); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - - /** - * Test 40 add params. - */ @Test - public void test_40_addParams() { - query.addParam("keyWithNull", null); + @Order(38) + void testAddParams() { + query.addParam("keyWithNull", "null"); query.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { - boolean result = query.urlQueries.has("keyWithNull"); - logger.info("result Key With Null exists: " + result); Object nullObject = query.urlQueries.opt("keyWithNull"); assertEquals("null", nullObject.toString()); } @@ -865,23 +817,21 @@ public void onCompletion(ResponseType responseType, QueryResult queryresult, Err }); } - - /** - * Test 41 include fallback. - */ @Test - public void test_41_include_fallback() { + @Order(39) + void testIncludeFallback() { + Query queryFallback = stack.contentType("categories").query(); queryFallback.locale("hi-in"); queryFallback.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { - assertEquals(0, queryresult.getResultObjects().size()); + assertEquals(9, queryresult.getResultObjects().size()); queryFallback.includeFallback().locale("hi-in"); queryFallback.find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { - assertEquals(8, queryresult.getResultObjects().size()); + assertEquals(9, queryresult.getResultObjects().size()); } }); } @@ -889,41 +839,148 @@ public void onCompletion(ResponseType responseType, QueryResult queryresult, Err }); } - /** - * Test 42 without include fallback. - */ @Test - public void test_42_without_include_fallback() { + @Order(40) + void testWithoutIncludeFallback() { + Query queryFallback = stack.contentType("categories").query(); queryFallback.locale("hi-in").find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { - assertEquals(0, queryresult.getResultObjects().size()); - logger.fine("total count: " + queryresult.getResultObjects().size()); + assertEquals(9, queryresult.getResultObjects().size()); + } else { + Assertions.fail("Failing, Verify credentials"); } } }); } - /** - * Test 43 entry include embedded items. - */ @Test - public void test_43_entry_include_embedded_items() { + @Order(41) + void testEntryIncludeEmbeddedItems() { final Query query = stack.contentType("categories").query(); query.includeEmbeddedItems().find(new QueryResultsCallBack() { @Override public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { if (error == null) { - List arryResult = queryresult.getResultObjects(); - for (Entry entry : arryResult) { - boolean _embedded_items = entry.toJSON().has("_embedded_items"); - //TestCase.assertTrue(_embedded_items); - } + assertTrue(query.urlQueries.has("include_embedded_items[]")); + } else { + Assertions.fail("Failing, Verify credentials"); } - TestCase.assertTrue(query.urlQueries.has("include_embedded_items[]")); } }); } + @Test + @Order(42) + void testError() { + Error error = new Error("Faking error information", 400, "{errors: invalid credential}"); + Assertions.assertNotNull(error.getErrorDetail()); + Assertions.assertEquals(400, error.getErrorCode()); + Assertions.assertNotNull(error.getErrorMessage()); + } + + // Unit testcases + // Running through the BeforeEach query instance + + @Test + void testUnitQuerySetHeader() { + query.setHeader("fakeHeaderKey", "fakeHeaderValue"); + Assertions.assertTrue(query.headers.containsKey("fakeHeaderKey")); + } + + @Test + void testUnitQueryRemoveHeader() { + query.setHeader("fakeHeaderKey", "fakeHeaderValue"); + query.removeHeader("fakeHeaderKey"); + Assertions.assertFalse(query.headers.containsKey("fakeHeaderKey")); + } + + @Test + void testUnitQueryWhere() { + query.where("title", "fakeTitle"); + Assertions.assertTrue(query.queryValueJSON.has("title")); + Assertions.assertEquals("fakeTitle", query.queryValueJSON.opt("title")); + } + + @Test + void testUnitAndQuery() { + ArrayList queryObj = new ArrayList<>(); + queryObj.add(query); + queryObj.add(query); + queryObj.add(query); + try { + query.and(queryObj); + Assertions.assertTrue(query.queryValueJSON.has("$and")); + } catch (Exception e) { + Assertions.assertTrue(query.queryValueJSON.has("$and")); + } + } + + @Test + void testUnitQueryOr() { + ArrayList queryObj = new ArrayList<>(); + queryObj.add(query); + queryObj.add(query); + queryObj.add(query); + try { + query.or(queryObj); + Assertions.assertTrue(query.queryValueJSON.has("$or")); + } catch (Exception e) { + Assertions.assertTrue(query.queryValueJSON.has("$or")); + } + } + + @Test + void testUnitQueryExcept() { + ArrayList queryObj = new ArrayList<>(); + queryObj.add("fakeQuery1"); + queryObj.add("fakeQuery2"); + queryObj.add("fakeQuery3"); + query.except(queryObj); + Assertions.assertEquals(3, query.objectUidForExcept.length()); + } + + @Test + void testUnitQueryOwner() { + query.includeOwner(); + Assertions.assertTrue(query.urlQueries.has("include_owner")); + } + + @Test + void testUnitQuerySkip() { + query.skip(5); + Assertions.assertTrue(query.urlQueries.has("skip")); + } + + @Test + void testUnitQueryLimit() { + query.limit(5); + Assertions.assertTrue(query.urlQueries.has("limit")); + } + + @Test + void testUnitQueryRegex() { + query.regex("regexKey", "regexValue"); + Assertions.assertTrue(query.queryValue.has("$regex")); + } + + @Test + void testUnitQueryIncludeReferenceContentTypUid() { + query.includeReferenceContentTypUid(); + Assertions.assertTrue(query.urlQueries.has("include_reference_content_type_uid")); + } + + @Test + void testUnitQueryWhereIn() { + query.whereIn("fakeIt", query); + Assertions.assertTrue(query.queryValueJSON.has("fakeIt")); + } + + @Test + void testUnitQueryWhereNotIn() { + query.whereNotIn("fakeIt", query); + Assertions.assertTrue(query.queryValueJSON.has("fakeIt")); + } + } \ No newline at end of file diff --git a/src/test/java/com/contentstack/sdk/TestAsset.java b/src/test/java/com/contentstack/sdk/TestAsset.java new file mode 100644 index 00000000..1ebb13b9 --- /dev/null +++ b/src/test/java/com/contentstack/sdk/TestAsset.java @@ -0,0 +1,185 @@ +package com.contentstack.sdk; + +import io.github.cdimascio.dotenv.Dotenv; +import org.json.JSONObject; +import org.junit.jupiter.api.*; + +import java.util.List; +import java.util.logging.Logger; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class TestAsset { + + protected String API_KEY, DELIVERY_TOKEN, ENV; + private final Logger logger = Logger.getLogger(TestAsset.class.getName()); + private String assetUid; + private Stack stack; + + @BeforeAll + public void initBeforeTests() throws IllegalAccessException { + Dotenv dotenv = Dotenv.load(); + API_KEY = dotenv.get("API_KEY"); + DELIVERY_TOKEN = dotenv.get("DELIVERY_TOKEN"); + ENV = dotenv.get("ENVIRONMENT"); + stack = Contentstack.stack(API_KEY, DELIVERY_TOKEN, ENV); + } + + @Test + @Order(1) + void testNewAssetLibrary() { + AssetLibrary assets = stack.assetLibrary(); + assets.fetchAll(new FetchAssetsCallback() { + @Override + public void onCompletion(ResponseType responseType, List assets, Error error) { + Asset model = assets.get(0); + assetUid = model.getAssetUid(); + Assertions.assertTrue(model.getAssetUid().startsWith("blt")); + Assertions.assertEquals("image/jpeg", model.getFileType()); + Assertions.assertEquals("482141", model.getFileSize()); + Assertions.assertEquals("phoenix2.jpg", model.getFileName()); + Assertions.assertTrue(model.getUrl().endsWith("phoenix2.jpg")); + Assertions.assertTrue(model.toJSON().has("created_at")); + Assertions.assertTrue(model.getCreatedBy().startsWith("blt")); + Assertions.assertEquals("gregory", model.getUpdateAt().getCalendarType()); + Assertions.assertTrue(model.getUpdatedBy().startsWith("sys")); + Assertions.assertNull(model.getDeleteAt()); + Assertions.assertEquals("", model.getDeletedBy()); + } + }); + } + + @Test + @Order(2) + void testNewAssetZOnlyForOrderByUid() { + String[] tags = { "black", "white", "red" }; + Asset asset = stack.asset(assetUid); + asset.includeFallback().addParam("fake@header", "fake@header").setTags(tags).fetch(new FetchResultCallback() { + @Override + public void onCompletion(ResponseType responseType, Error error) { + Assertions.assertTrue(asset.getAssetUid().startsWith("blt")); + Assertions.assertEquals("image/jpeg", asset.getFileType()); + Assertions.assertEquals("482141", asset.getFileSize()); + Assertions.assertEquals("phoenix2.jpg", asset.getFileName()); + Assertions.assertTrue(asset.getUrl().endsWith("phoenix2.jpg")); + Assertions.assertTrue(asset.toJSON().has("created_at")); + Assertions.assertTrue(asset.getCreatedBy().startsWith("blt")); + Assertions.assertEquals("gregory", asset.getUpdateAt().getCalendarType()); + Assertions.assertTrue(asset.getUpdatedBy().startsWith("sys")); + Assertions.assertNull(asset.getDeleteAt()); + Assertions.assertEquals("gregory", asset.getCreateAt().getCalendarType()); + Assertions.assertEquals("", asset.getDeletedBy()); + } + }); + } + + @Test + void testAssetDefaultConstructor() { + logger.fine("We are working with fake apis"); + Asset asset = new Asset(); + Assertions.assertNotNull(asset); + } + + @Test + void testAddHeader() { + String headerKey = "fakeKey"; + Asset assetInstance = stack.asset(); + assetInstance.setHeader(headerKey, "fakeValue"); + Assertions.assertTrue(assetInstance.headers.containsKey(headerKey)); + } + + @Test + void testRemoveHeader() { + String headerKey = "fakeKey"; + Asset assetInstance = stack.asset(); + assetInstance.removeHeader(headerKey); + Assertions.assertFalse(assetInstance.headers.containsKey(headerKey)); + } + + @Test + void testSetAssetUid() { + String headerKey = "asset@fakeuid"; + Asset assetInstance = stack.asset(); + assetInstance.setUid(headerKey); + Assertions.assertEquals(headerKey, assetInstance.assetUid); + } + + @Test + void testSetAssetTagsLength() { + String[] tags = { "gif", "img", "landscape", "portrait" }; + Asset assetInstance = stack.asset(); + assetInstance.setTags(tags); + Assertions.assertEquals(tags.length, assetInstance.tagsArray.length); + } + + @Test + void testGetAssetTags() { + String[] tags = { "gif", "img", "landscape", "portrait" }; + Asset assetInstance = stack.asset(); + assetInstance.setTags(tags); + Assertions.assertEquals(tags.length, assetInstance.getTags().length); + } + + @Test + void testAssetIncludeDimension() { + Asset assetInstance = stack.asset(); + assetInstance.includeDimension(); + Assertions.assertTrue(assetInstance.urlQueries.has("include_dimension")); + } + + @Test + void testAssetIncludeFallback() { + Asset assetInstance = stack.asset(); + assetInstance.includeFallback(); + Assertions.assertTrue(assetInstance.urlQueries.has("include_fallback")); + } + + @Test + void testAssetAddParam() { + Asset assetInstance = stack.asset(); + assetInstance.addParam("fake@Param", "fake@Param"); + Assertions.assertTrue(assetInstance.urlQueries.has("fake@Param")); + } + + @Test + void testNewAssetInstance() { + String fakeAssetUid = "fakeAssetUid"; + Asset assetInstance = stack.asset(fakeAssetUid); + Assertions.assertEquals(fakeAssetUid, assetInstance.assetUid); + } + + @Test + void assetConfigure() { + Asset assetInstance = stack.asset("assetuid@fake"); + Assertions.assertEquals("assetuid@fake", assetInstance.assetUid); + } + + JSONObject rawJson() { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("uid", "something@fake"); + jsonObject.put("created_at", "2016-04-06T11:06:10.601Z"); + jsonObject.put("updated_at", "2016-12-16T12:36:33.961Z"); + jsonObject.put("created_by", "something@fake"); + jsonObject.put("content_type", "image/jpeg"); + jsonObject.put("file_size", "482141"); + JSONObject jsonAsset = new JSONObject(); + jsonAsset.put("asset", jsonObject); + return jsonAsset; + } + + @Test + void testNewAssetConfigure() { + JSONObject assetObject = rawJson(); + Asset asset = stack.asset("fake@uid"); + asset.configure(assetObject); + Assertions.assertTrue(asset.json.has("asset")); + } + + @Test + void testAssetIncludeBranch() { + Asset asset = stack.asset("fake@uid"); + asset.includeBranch(); + Assertions.assertTrue(asset.urlQueries.has("include_branch")); + } + +} diff --git a/src/test/java/com/contentstack/sdk/TestAssetLibrary.java b/src/test/java/com/contentstack/sdk/TestAssetLibrary.java new file mode 100644 index 00000000..de23631f --- /dev/null +++ b/src/test/java/com/contentstack/sdk/TestAssetLibrary.java @@ -0,0 +1,116 @@ +package com.contentstack.sdk; + +import io.github.cdimascio.dotenv.Dotenv; +import org.junit.jupiter.api.*; + +import java.util.List; +import java.util.logging.Logger; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class TestAssetLibrary { + + protected String API_KEY, DELIVERY_TOKEN, ENV; + private final Logger logger = Logger.getLogger(TestAssetLibrary.class.getName()); + private Stack stack; + + @BeforeAll + public void initBeforeTests() throws IllegalAccessException { + Dotenv dotenv = Dotenv.load(); + API_KEY = dotenv.get("API_KEY"); + DELIVERY_TOKEN = dotenv.get("DELIVERY_TOKEN"); + ENV = dotenv.get("ENVIRONMENT"); + stack = Contentstack.stack(API_KEY, DELIVERY_TOKEN, ENV); + } + + @Test + @Order(1) + void testNewAssetLibrary() { + AssetLibrary assets = stack.assetLibrary(); + assets.fetchAll(new FetchAssetsCallback() { + @Override + public void onCompletion(ResponseType responseType, List assets, Error error) { + Asset model = assets.get(0); + Assertions.assertTrue(model.getAssetUid().startsWith("blt")); + assertEquals("image/jpeg", model.getFileType()); + assertEquals("482141", model.getFileSize()); + assertEquals("phoenix2.jpg", model.getFileName()); + Assertions.assertTrue(model.getUrl().endsWith("phoenix2.jpg")); + Assertions.assertTrue(model.toJSON().has("created_at")); + Assertions.assertTrue(model.getCreatedBy().startsWith("blt")); + assertEquals("gregory", model.getUpdateAt().getCalendarType()); + Assertions.assertTrue(model.getUpdatedBy().startsWith("sys")); + Assertions.assertNull(model.getDeleteAt()); + assertEquals("", model.getDeletedBy()); + logger.info("passed..."); + } + }); + } + + @Test + void testAssetSetHeader() { + AssetLibrary assetLibrary = stack.assetLibrary(); + assetLibrary.setHeader("headerKey", "headerValue"); + Assertions.assertTrue(assetLibrary.headers.containsKey("headerKey")); + logger.info("passed..."); + } + + @Test + void testAssetRemoveHeader() { + AssetLibrary assetLibrary = stack.assetLibrary(); + assetLibrary.setHeader("headerKey", "headerValue"); + assetLibrary.removeHeader("headerKey"); + Assertions.assertFalse(assetLibrary.headers.containsKey("headerKey")); + logger.info("passed..."); + } + + @Test + void testAssetSortAscending() { + AssetLibrary assetLibrary = stack.assetLibrary(); + assetLibrary.sort("ascending", AssetLibrary.ORDERBY.ASCENDING); + Assertions.assertFalse(assetLibrary.headers.containsKey("asc")); + logger.info("passed..."); + } + + @Test + void testAssetSortDescending() { + AssetLibrary assetLibrary = stack.assetLibrary(); + assetLibrary.sort("descending", AssetLibrary.ORDERBY.DESCENDING); + Assertions.assertFalse(assetLibrary.headers.containsKey("desc")); + logger.info("passed..."); + } + + @Test + void testAssetIncludeCount() { + AssetLibrary assetLibrary = stack.assetLibrary(); + assetLibrary.includeCount(); + Assertions.assertFalse(assetLibrary.headers.containsKey("include_count")); + logger.info("passed..."); + } + + @Test + void testAssetIncludeRelativeUrl() { + AssetLibrary assetLibrary = stack.assetLibrary(); + assetLibrary.includeRelativeUrl(); + Assertions.assertFalse(assetLibrary.headers.containsKey("relative_urls")); + logger.info("passed..."); + } + + @Test + void testAssetGetCount() { + AssetLibrary assetLibrary = stack.assetLibrary(); + assetLibrary.includeRelativeUrl(); + Assertions.assertEquals(0, assetLibrary.getCount()); + logger.info("passed..."); + } + + @Test + void testIncludeFallback() { + AssetLibrary assetLibrary = stack.assetLibrary(); + assetLibrary.includeFallback(); + Assertions.assertFalse(assetLibrary.headers.containsKey("include_fallback")); + logger.info("passed..."); + } +} diff --git a/src/test/java/com/contentstack/sdk/TestContentType.java b/src/test/java/com/contentstack/sdk/TestContentType.java new file mode 100644 index 00000000..890004ce --- /dev/null +++ b/src/test/java/com/contentstack/sdk/TestContentType.java @@ -0,0 +1,122 @@ +package com.contentstack.sdk; + +import io.github.cdimascio.dotenv.Dotenv; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.jupiter.api.*; + +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Logger; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class TestContentType { + + protected String API_KEY, DELIVERY_TOKEN, ENV; + private final Logger logger = Logger.getLogger(TestContentType.class.getName()); + private Stack stack; + + @BeforeAll + public void initBeforeTests() throws IllegalAccessException { + Dotenv dotenv = Dotenv.load(); + API_KEY = dotenv.get("API_KEY"); + DELIVERY_TOKEN = dotenv.get("DELIVERY_TOKEN"); + ENV = dotenv.get("ENVIRONMENT"); + stack = Contentstack.stack(API_KEY, DELIVERY_TOKEN, ENV); + } + + @Test + @Order(1) + void testPrivateAccess() { + try { + new ContentType(); + } catch (IllegalAccessException e) { + Assertions.assertEquals("Can Not Access Private Modifier", e.getLocalizedMessage()); + logger.info("passed..."); + } + } + + @Test + @Order(2) + void testContentType() { + ContentType contentType = stack.contentType("product"); + Assertions.assertEquals("product", contentType.contentTypeUid); + logger.info("passed..."); + } + + @Test + @Order(3) + void testContentTypeSetHeader() { + ContentType contentType = stack.contentType("product"); + contentType.setHeader("headerKey", "headerValue"); + Assertions.assertTrue(contentType.headers.containsKey("headerKey")); + logger.info("passed..."); + } + + @Test + void testContentRemoveHeader() { + ContentType contentType = stack.contentType("product"); + contentType.setHeader("headerKey", "headerValue"); + contentType.removeHeader("headerKey"); + Assertions.assertFalse(contentType.headers.containsKey("headerKey")); + logger.info("passed..."); + } + + @Test + void testEntryInstance() { + ContentType contentType = stack.contentType("product"); + Entry entry = contentType.entry("just-fake-it"); + Assertions.assertEquals("product", entry.getContentType()); + Assertions.assertEquals("just-fake-it", entry.uid); + Assertions.assertEquals(4, entry.headers.size()); + logger.info("passed..."); + } + + @Test + void testQueryInstance() { + ContentType contentType = stack.contentType("product"); + Query query = contentType.query(); + Assertions.assertEquals("product", query.getContentType()); + Assertions.assertEquals(4, query.headers.size()); + logger.info("passed..."); + } + + @Test + void testContentTypeFetch() { + ContentType contentType = stack.contentType("product"); + JSONObject paramObj = new JSONObject(); + paramObj.put("ctKeyOne", "ctKeyValue1"); + paramObj.put("ctKeyTwo", "ctKeyValue2"); + contentType.fetch(paramObj, new ContentTypesCallback() { + @Override + public void onCompletion(ContentTypesModel model, Error error) { + JSONObject resp = (JSONObject) model.getResponse(); + Assertions.assertTrue(resp.has("schema")); + } + }); + } + + @Test + void testContentTypesFetch() { + ContentType contentType = stack.contentType("product"); + JSONObject paramObj = new JSONObject(); + paramObj.put("ctKeyOne", "ctKeyValue1"); + paramObj.put("ctKeyTwo", "ctKeyValue2"); + contentType.fetch(paramObj, new ContentTypesCallback() { + @Override + public void onCompletion(ContentTypesModel model, Error error) { + JSONArray resp = model.getResultArray(); + Assertions.assertTrue(resp.isEmpty()); + } + }); + } + + @Test + void toCoverageCheckHeader() { + Map mapHeader = new HashMap<>(); + CSBackgroundTask backgroundTask = new CSBackgroundTask(); + backgroundTask.checkHeader(mapHeader); + } + +} diff --git a/src/test/java/com/contentstack/sdk/TestContentstack.java b/src/test/java/com/contentstack/sdk/TestContentstack.java new file mode 100644 index 00000000..1297966c --- /dev/null +++ b/src/test/java/com/contentstack/sdk/TestContentstack.java @@ -0,0 +1,112 @@ +package com.contentstack.sdk; + +import io.github.cdimascio.dotenv.Dotenv; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; + +import java.util.logging.Logger; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class TestContentstack { + + private String API_KEY, DELIVERY_TOKEN, ENV; + private final Logger logger = Logger.getLogger(TestContentstack.class.getName()); + + @BeforeAll + public void initBeforeTests() { + Dotenv dotenv = Dotenv.load(); + API_KEY = dotenv.get("API_KEY"); + DELIVERY_TOKEN = dotenv.get("DELIVERY_TOKEN"); + ENV = dotenv.get("ENVIRONMENT"); + } + + @Test + void initStackPrivateModifier() { + try { + new Contentstack(); + } catch (Exception e) { + logger.info(e.getLocalizedMessage()); + Assertions.assertEquals("Can Not Access Private Modifier", e.getLocalizedMessage()); + } + } + + @Test + void initStackWithNullAPIKey() { + try { + + Contentstack.stack(null, DELIVERY_TOKEN, ENV); + } catch (Exception e) { + logger.info(e.getLocalizedMessage()); + Assertions.assertEquals("API Key can not be null", e.getLocalizedMessage(), "Set APIKey Null"); + } + } + + @Test + void initStackWithNullDeliveryToken() { + try { + Contentstack.stack(API_KEY, null, ENV); + } catch (Exception e) { + logger.info(e.getLocalizedMessage()); + Assertions.assertEquals("Delivery Token can not be null", e.getLocalizedMessage(), + "Set deliveryToken Null"); + } + } + + @Test + void initStackWithNullEnvironment() { + try { + Contentstack.stack(API_KEY, DELIVERY_TOKEN, null); + } catch (Exception e) { + logger.info(e.getLocalizedMessage()); + Assertions.assertEquals("Environment can not be null", e.getLocalizedMessage(), "Set Environment Null"); + } + } + + @Test + void initStackWithEmptyAPIKey() { + try { + + Contentstack.stack("", DELIVERY_TOKEN, ENV); + } catch (Exception e) { + logger.info(e.getLocalizedMessage()); + Assertions.assertEquals("API Key can not be empty", e.getLocalizedMessage(), "Set APIKey Null"); + } + } + + @Test + void initStackWithEmptyDeliveryToken() { + try { + Contentstack.stack(API_KEY, "", ENV); + } catch (Exception e) { + logger.info(e.getLocalizedMessage()); + Assertions.assertEquals("Delivery Token can not be empty", e.getLocalizedMessage(), + "Set deliveryToken Null"); + } + } + + @Test + void initStackWithEmptyEnvironment() { + try { + Contentstack.stack(API_KEY, DELIVERY_TOKEN, ""); + } catch (Exception e) { + logger.info(e.getLocalizedMessage()); + Assertions.assertEquals("Environment can not be empty", e.getLocalizedMessage(), "Set Environment Null"); + } + } + + @Test + void initStackWithAllValidCredentials() throws IllegalAccessException { + Stack stack = Contentstack.stack(API_KEY, DELIVERY_TOKEN, ENV); + Assertions.assertNotNull(stack); + } + + @Test + void initStackWithConfigs() throws IllegalAccessException { + Config config = new Config(); + Stack stack = Contentstack.stack(API_KEY, DELIVERY_TOKEN, ENV, config); + Assertions.assertEquals("cdn.contentstack.io", config.host); + Assertions.assertNotNull(stack); + } +} diff --git a/src/test/java/com/contentstack/sdk/TestEntry.java b/src/test/java/com/contentstack/sdk/TestEntry.java new file mode 100644 index 00000000..263f3ae4 --- /dev/null +++ b/src/test/java/com/contentstack/sdk/TestEntry.java @@ -0,0 +1,553 @@ +package com.contentstack.sdk; + +import io.github.cdimascio.dotenv.Dotenv; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.jupiter.api.*; + +import java.text.ParseException; +import java.util.ArrayList; +import java.util.GregorianCalendar; +import java.util.TimeZone; +import java.util.logging.Logger; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class TestEntry { + + private final Logger logger = Logger.getLogger(TestEntry.class.getName()); + private String DEFAULT_API_KEY, DEFAULT_DELIVERY_TOKEN, DEFAULT_ENV; + private final String CONTENT_TYPE = "product"; + private String entryUid = "justFakeIt"; + private Stack stack; + private Entry entry; + + @BeforeAll + public void intOnceBeforeAll() throws Exception { + Dotenv dotenv = Dotenv.load(); + DEFAULT_API_KEY = dotenv.get("API_KEY"); + DEFAULT_DELIVERY_TOKEN = dotenv.get("DELIVERY_TOKEN"); + DEFAULT_ENV = dotenv.get("ENVIRONMENT"); + String DEFAULT_HOST = dotenv.get("HOST"); + Config config = new Config(); + config.setHost(DEFAULT_HOST); + assert DEFAULT_API_KEY != null; + stack = Contentstack.stack(DEFAULT_API_KEY, DEFAULT_DELIVERY_TOKEN, DEFAULT_ENV, config); + } + + @Test + @Order(1) + void entryCallingPrivateModifier() { + try { + new Entry(); + } catch (IllegalAccessException e) { + Assertions.assertEquals("Can Not Access Private Modifier", e.getLocalizedMessage()); + logger.info("passed."); + } + } + + @Test + @Order(2) + void runQueryToGetEntryUid() { + final Query query = stack.contentType(CONTENT_TYPE).query(); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + JSONObject array = (JSONObject) queryresult.receiveJson.optJSONArray("entries").get(0); + entryUid = array.optString("uid"); + assertTrue(entryUid.startsWith("blt")); + logger.info("passed.."); + } else { + Assertions.fail("Could not fetch the query data"); + logger.info("passed.."); + } + } + }); + } + + @Test + @Order(3) + void entryAPIFetch() { + entry = stack.contentType(CONTENT_TYPE).entry(entryUid); + entry.fetch(new EntryResultCallBack() { + @Override + public void onCompletion(ResponseType responseType, Error error) { + Assertions.assertEquals(entryUid, entry.getUid()); + } + }); + logger.info("passed.."); + } + + @Test + @Order(4) + void entryCalling() { + Assertions.assertEquals(4, entry.headers.size()); + logger.info("passed..."); + } + + @Test + @Order(5) + void entrySetHeader() { + entry.setHeader("headerKey", "headerValue"); + Assertions.assertTrue(entry.headers.containsKey("headerKey")); + logger.info("passed..."); + } + + @Test + @Order(6) + void entryRemoveHeader() { + entry.removeHeader("headerKey"); + Assertions.assertFalse(entry.headers.containsKey("headerKey")); + logger.info("passed..."); + } + + @Test + @Order(7) + void entryGetTitle() { + Assertions.assertEquals("Blue Yellow", entry.getTitle()); + logger.info("passed..."); + } + + @Test + @Order(8) + void entryGetURL() { + Assertions.assertNull(entry.getURL()); + logger.info("passed..."); + } + + @Test + @Order(9) + void entryGetTags() { + Assertions.assertNull(entry.getTags()); + logger.info("passed..."); + } + + @Test + @Order(10) + void entryGetContentType() { + Assertions.assertEquals("product", entry.getContentType()); + logger.info("passed..."); + } + + @Test + @Order(11) + void entryGetUID() { + Assertions.assertEquals(entryUid, entry.getUid()); + logger.info("passed..."); + } + + @Test + @Order(12) + void entryGetLocale() { + Assertions.assertEquals("en-us", entry.getLocale()); + logger.info("passed..."); + } + + @Test + @Order(13) + void entrySetLocale() { + entry.setLocale("hi"); + Assertions.assertEquals("hi", entry.params.optString("locale")); + logger.info("passed..."); + } + + @Test + @Order(14) + @Deprecated + void entryGetOwner() { + Assertions.assertNull(entry.getOwner()); + logger.info("passed..."); + } + + @Test + @Order(15) + void entryToJSON() { + boolean isJson = entry.toJSON() instanceof JSONObject; + Assertions.assertNotNull(entry.toJSON()); + Assertions.assertTrue(isJson); + logger.info("passed..."); + } + + @Test + @Order(16) + void entryGetObject() { + Object what = entry.get("short_description"); + Object invalidKey = entry.get("invalidKey"); + Assertions.assertNotNull(what); + Assertions.assertNull(invalidKey); + logger.info("passed..."); + } + + @Test + @Order(17) + void entryGetString() { + Object what = entry.getString("short_description"); + Object version = entry.getString("_version"); + Assertions.assertNotNull(what); + Assertions.assertNull(version); + logger.info("passed..."); + } + + @Test + @Order(18) + void entryGetBoolean() { + Boolean shortDescription = entry.getBoolean("short_description"); + Object inStock = entry.getBoolean("in_stock"); + Assertions.assertFalse(shortDescription); + Assertions.assertTrue(inStock instanceof Boolean); + logger.info("passed..."); + } + + @Test + @Order(19) + void entryGetJSONArray() { + Object image = entry.getJSONArray("image"); + Assertions.assertTrue(image instanceof JSONArray); + logger.info("passed..."); + } + + @Test + @Order(20) + void entryGetJSONArrayShouldResultNull() { + Object shouldBeNull = entry.getJSONArray("uid"); + Assertions.assertNull(shouldBeNull); + logger.info("passed..."); + } + + @Test + @Order(21) + void entryGetJSONObject() { + Object shouldBeNull = entry.getJSONObject("uid"); + Assertions.assertNull(shouldBeNull); + logger.info("passed..."); + } + + @Test + @Order(22) + void entryGetNumber() { + Object price = entry.getNumber("price"); + Assertions.assertTrue(price instanceof Number); + logger.info("passed..."); + } + + @Test + @Order(23) + void entryGetNumberNullExpected() { + Object price = entry.getNumber("short_description"); + Assertions.assertNull(price); + logger.info("passed..."); + } + + @Test + @Order(24) + void entryGetInt() { + Object price = entry.getInt("price"); + Assertions.assertTrue(price instanceof Integer); + logger.info("passed..."); + } + + @Test + @Order(25) + void entryGetIntNullExpected() { + Object updatedBy = entry.getInt("updated_by"); + Assertions.assertEquals(0, updatedBy); + logger.info("passed..."); + } + + @Test + @Order(26) + void entryGetFloat() { + Object price = entry.getFloat("price"); + Assertions.assertTrue(price instanceof Float); + logger.info("passed..."); + } + + @Test + @Order(27) + void entryGetFloatZeroExpected() { + Object updatedBy = entry.getFloat("updated_by"); + Assertions.assertNotNull(updatedBy); + logger.info("passed..."); + } + + @Test + @Order(28) + void entryGetDouble() { + Object price = entry.getDouble("price"); + Assertions.assertTrue(price instanceof Double); + logger.info("passed..."); + } + + @Test + @Order(29) + void entryGetDoubleZeroExpected() { + Object updatedBy = entry.getDouble("updated_by"); + Assertions.assertNotNull(updatedBy); + logger.info("passed..."); + } + + @Test + @Order(30) + void entryGetLong() { + Object price = entry.getLong("price"); + Assertions.assertTrue(price instanceof Long); + logger.info("passed..."); + } + + @Test + @Order(31) + void entryGetLongZeroExpected() { + Object updatedBy = entry.getLong("updated_by"); + Assertions.assertNotNull(updatedBy); + logger.info("passed..."); + } + + @Test + @Order(32) + void entryGetShort() { + Object updatedBy = entry.getShort("updated_by"); + Assertions.assertNotNull(updatedBy); + logger.info("passed..."); + } + + @Test + @Order(33) + void entryGetShortZeroExpected() { + Object updatedBy = entry.getShort("updated_by"); + Assertions.assertNotNull(updatedBy); + logger.info("passed..."); + } + + @Test + @Order(34) + void entryGetDate() throws ParseException { + Object updatedAt = entry.getDate("updated_at"); + Assertions.assertTrue(updatedAt instanceof GregorianCalendar); + logger.info("passed..."); + TimeZone zone = TimeZone.getTimeZone("Asia/Kolkata"); + String input = "Thu Jun 18 20:56:02 EDT 2009"; + Constants.parseDate(input, "EEE MMM d HH:mm:ss zzz yyyy", zone); + } + + @Test + @Order(35) + void entryGetCreateAt() { + Object updatedBy = entry.getCreateAt(); + Assertions.assertTrue(updatedBy instanceof GregorianCalendar); + logger.info("passed..."); + } + + @Test + @Order(36) + void entryGetCreatedBy() { + String createdBy = entry.getCreatedBy(); + Assertions.assertTrue(createdBy.startsWith("blt")); + logger.info("passed..."); + } + + @Test + @Order(37) + void entryGetUpdateAt() { + Object updateAt = entry.getUpdateAt(); + Assertions.assertTrue(updateAt instanceof GregorianCalendar); + logger.info("passed..."); + } + + @Test + @Order(38) + void entryGetUpdateBy() { + String updateAt = entry.getUpdatedBy(); + Assertions.assertTrue(updateAt.startsWith("blt")); + logger.info("passed..."); + } + + @Test + @Order(39) + void entryGetDeleteAt() { + Object deleteAt = entry.getDeleteAt(); + Assertions.assertNull(deleteAt); + logger.info("passed..."); + } + + @Test + @Order(40) + void entryGetDeletedBy() { + Object deletedBy = entry.getDeletedBy(); + Assertions.assertNull(deletedBy); + logger.info("passed..."); + } + + @Test + @Order(41) + void entryGetAsset() { + Object asset = entry.getAsset("image"); + Assertions.assertNotNull(asset); + logger.info("passed..."); + } + + /// Add few more tests + + @Test + @Order(42) + void entryExcept() { + String[] arrField = { "fieldOne", "fieldTwo", "fieldThree" }; + Entry initEntry = stack.contentType("product").entry(entryUid); + initEntry.except(arrField); + Assertions.assertEquals(3, initEntry.exceptFieldArray.length()); + logger.info("passed..."); + } + + @Test + @Order(43) + void entryIncludeReference() { + Entry initEntry = stack.contentType("product").entry(entryUid); + initEntry.includeReference("fieldOne"); + Assertions.assertEquals(1, initEntry.referenceArray.length()); + Assertions.assertTrue(initEntry.params.has("include[]")); + logger.info("passed..."); + } + + @Test + @Order(44) + void entryIncludeReferenceList() { + String[] arrField = { "fieldOne", "fieldTwo", "fieldThree" }; + Entry initEntry = stack.contentType("product").entry(entryUid); + initEntry.includeReference(arrField); + Assertions.assertEquals(3, initEntry.referenceArray.length()); + Assertions.assertTrue(initEntry.params.has("include[]")); + logger.info("passed..."); + } + + @Test + @Order(45) + void entryOnlyList() { + String[] arrField = { "fieldOne", "fieldTwo", "fieldThree" }; + Entry initEntry = stack.contentType("product").entry(entryUid); + initEntry.only(arrField); + Assertions.assertEquals(3, initEntry.objectUidForOnly.length()); + logger.info("passed..."); + } + + @Test + @Order(46) + void entryOnlyWithReferenceUid() { + ArrayList strList = new ArrayList<>(); + strList.add("fieldOne"); + strList.add("fieldTwo"); + strList.add("fieldThree"); + Entry initEntry = stack.contentType("product").entry(entryUid); + initEntry.onlyWithReferenceUid(strList, "reference@fakeit"); + Assertions.assertTrue(initEntry.onlyJsonObject.has("reference@fakeit")); + int size = initEntry.onlyJsonObject.optJSONArray("reference@fakeit").length(); + Assertions.assertEquals(strList.size(), size); + logger.info("passed..."); + } + + @Test + @Order(47) + void entryExceptWithReferenceUid() { + ArrayList strList = new ArrayList<>(); + strList.add("fieldOne"); + strList.add("fieldTwo"); + strList.add("fieldThree"); + Entry initEntry = stack.contentType("product").entry(entryUid); + initEntry.exceptWithReferenceUid(strList, "reference@fakeit"); + Assertions.assertTrue(initEntry.exceptJsonObject.has("reference@fakeit")); + int size = initEntry.exceptJsonObject.optJSONArray("reference@fakeit").length(); + Assertions.assertEquals(strList.size(), size); + logger.info("passed..."); + } + + @Test + @Order(48) + void entryAddParamMultiCheck() { + Entry initEntry = stack.contentType("product").entry(entryUid); + initEntry.addParam("fake@key", "fake@value"); + initEntry.addParam("fake@keyinit", "fake@valueinit"); + Assertions.assertTrue(initEntry.params.has("fake@key")); + Assertions.assertTrue(initEntry.params.has("fake@keyinit")); + Assertions.assertEquals(2, initEntry.params.length()); + logger.info("passed..."); + } + + @Test + @Order(49) + void entryIncludeReferenceContentTypeUID() { + Entry initEntry = stack.contentType("product").entry(entryUid); + initEntry.includeReferenceContentTypeUID(); + Assertions.assertTrue(initEntry.params.has("include_reference_content_type_uid")); + logger.info("passed..."); + } + + @Test + @Order(50) + void entryIncludeContentType() { + Entry initEntry = stack.contentType("product").entry(entryUid); + initEntry.addParam("include_schema", "true"); + initEntry.includeContentType(); + Assertions.assertTrue(initEntry.params.has("include_content_type")); + Assertions.assertTrue(initEntry.params.has("include_global_field_schema")); + logger.info("passed..."); + } + + @Test + @Order(51) + void entryIncludeContentTypeWithoutInclude_schema() { + Entry initEntry = stack.contentType("product").entry(entryUid); + initEntry.includeContentType(); + Assertions.assertTrue(initEntry.params.has("include_content_type")); + Assertions.assertTrue(initEntry.params.has("include_global_field_schema")); + logger.info("passed..."); + } + + @Test + @Order(52) + void entryIncludeFallback() { + Entry initEntry = stack.contentType("product").entry(entryUid); + initEntry.includeFallback(); + Assertions.assertTrue(initEntry.params.has("include_fallback")); + logger.info("passed..."); + } + + @Test + @Order(53) + void entryIncludeEmbeddedItems() { + Entry initEntry = stack.contentType("product").entry(entryUid); + initEntry.includeEmbeddedItems(); + Assertions.assertTrue(initEntry.params.has("include_embedded_items[]")); + logger.info("passed..."); + } + + @Test + @Order(54) + void testEntryIncludeBranch() { + Entry initEntry = stack.contentType("product").entry(entryUid); + initEntry.includeBranch(); + Assertions.assertTrue(initEntry.params.has("include_branch")); + Assertions.assertEquals(true, initEntry.params.opt("include_branch")); + logger.info("passed..."); + } + + @Test + @Order(55) + void testEntryPassConfigBranchIncludeBranch() throws IllegalAccessException { + Config config = new Config(); + config.setBranch("feature_branch"); + Stack branchStack = Contentstack.stack(DEFAULT_API_KEY, DEFAULT_DELIVERY_TOKEN, DEFAULT_ENV, config); + Entry entry = branchStack.contentType("product").entry(entryUid); + entry.includeBranch().fetch(new EntryResultCallBack() { + @Override + public void onCompletion(ResponseType responseType, Error error) { + logger.info(entry.headers + ""); + } + }); + Assertions.assertTrue(entry.params.has("include_branch")); + Assertions.assertEquals(true, entry.params.opt("include_branch")); + Assertions.assertTrue(entry.headers.containsKey("branch")); + logger.info("passed..."); + } + +} diff --git a/src/test/java/com/contentstack/sdk/TestLivePreview.java b/src/test/java/com/contentstack/sdk/TestLivePreview.java new file mode 100644 index 00000000..428bf624 --- /dev/null +++ b/src/test/java/com/contentstack/sdk/TestLivePreview.java @@ -0,0 +1,157 @@ +package com.contentstack.sdk; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * The type Config testcase. + */ +public class TestLivePreview { + + private static final Logger logger = Logger.getLogger(TestLivePreview.class.getName()); + private static Config config; + + /** + * One time set up. + */ + @BeforeAll + public static void setUp() { + logger.setLevel(Level.FINE); + config = new Config(); + } + + /** + * Test config test. + */ + @Test + void testConfigTest() { + Config livePreview = config.enableLivePreview(true).setLivePreviewHost("api.contentstack.com") + .setManagementToken("managementToken"); + Assertions.assertEquals("api.contentstack.com", livePreview.livePreviewHost); + Assertions.assertEquals("managementToken", livePreview.managementToken); + } + + /** + * Test config test. + */ + @Test() + void testEnableLivePreviewTrue() { + Config livePreview = config.enableLivePreview(true); + Assertions.assertTrue(livePreview.enableLivePreview); + } + + /** + * Test config test. + */ + @Test() + void testEnableLivePreviewFalse() { + Config livePreview = config.enableLivePreview(false); + Assertions.assertFalse(livePreview.enableLivePreview); + } + + @Test() + void testSetLivePreview() { + Config livePreview = config.setLivePreviewHost("api.contentstack.com"); + Assertions.assertEquals("api.contentstack.com", livePreview.livePreviewHost); + } + + @Test() + void testSetAuthorization() { + Config livePreview = config.setManagementToken("management_token"); + Assertions.assertEquals("management_token", livePreview.managementToken); + } + + @Test() + void testStackEnableLivePreviewQuery() throws Exception { + config.enableLivePreview(true).setLivePreviewHost("api.contentstack.com").setManagementToken("managementToken"); + Stack stack = Contentstack.stack("liveAPIKey", "liveAccessToken", "liveEnv", config); + HashMap hashMap = new HashMap<>(); + hashMap.put("live_preview", "hash167673"); + hashMap.put("content_type_uid", "contentType"); + stack.livePreviewQuery(hashMap); + ContentType contentType = stack.contentType("contentType"); + Query queryInstance = contentType.query(); + Assertions.assertNotNull(queryInstance); + } + + @Test() + void testStackEnableLivePreviewEntry() throws Exception { + config.enableLivePreview(true).setLivePreviewHost("live-preview.contentstack.com") + .setManagementToken("management_token_123456"); + Stack stack = Contentstack.stack("liveAPIKey", "liveAccessToken", "liveEnv", config); + HashMap hashMap = new HashMap<>(); + hashMap.put("live_preview", "hash167673"); + hashMap.put("content_type_uid", "contentType"); + stack.livePreviewQuery(hashMap); + ContentType contentType = stack.contentType("contentType"); + Entry entryInstance = contentType.entry("entryUid478748374"); + entryInstance.fetch(null); + Assertions.assertNotNull(entryInstance); + } + + @Test() + void testEnableLivePreviewWithoutRequiredParameters() { + Config livePreviewEnablerConfig = new Config().enableLivePreview(true); + try { + Contentstack.stack("liveAPIKey", "liveAccessToken", "liveEnv", livePreviewEnablerConfig); + } catch (Exception e) { + Assertions.assertEquals("managementToken is required", e.getLocalizedMessage()); + e.printStackTrace(); + } + } + + @Test() + void testExceptionWhenAllRequiredParamsNotProvided() { + Config livePreviewEnablerConfig = new Config().enableLivePreview(true) + .setLivePreviewHost("live-preview.contentstack.io"); + try { + Contentstack.stack("liveAPIKey", "liveAccessToken", "liveEnv", livePreviewEnablerConfig); + } catch (Exception e) { + Assertions.assertEquals("managementToken is required", e.getLocalizedMessage()); + e.printStackTrace(); + } + } + + @Test() + void testMissingHostToEnableLivePreview() { + Config livePreviewEnablerConfig = new Config().enableLivePreview(true) + .setManagementToken("management_token_123456"); + try { + Contentstack.stack("liveAPIKey", "liveAccessToken", "liveEnv", livePreviewEnablerConfig); + } catch (Exception e) { + Assertions.assertEquals("host is required", e.getLocalizedMessage()); + e.printStackTrace(); + } + } + + @Test() + void testCompleteLivePreview() throws Exception { + Config livePreviewEnablerConfig = new Config().enableLivePreview(true) + .setLivePreviewHost("live-preview.contentstack.io").setManagementToken("management_token_123456"); + Stack stack = Contentstack.stack("liveAPIKey", "liveAccessToken", "liveEnv", livePreviewEnablerConfig); + HashMap hashMap = new HashMap<>(); + hashMap.put("content_type_uid", "content_type_uid"); + stack.livePreviewQuery(hashMap); + Entry entry = stack.contentType("content_type_uid").entry("entry_uid"); + entry.fetch(null); + Assertions.assertNotNull(entry); + } + + @Test() + void testCompleteLivePreviewInQuery() throws Exception { + Config livePreviewEnablerConfig = new Config().enableLivePreview(true).setLivePreviewHost("cdn.contentstack.io") + .setManagementToken("fake@token"); + Stack stack = Contentstack.stack("liveAPIKey", "liveAccessToken", "liveEnv", livePreviewEnablerConfig); + HashMap hashMap = new HashMap<>(); + hashMap.put("content_type_uid", "content_type_uid"); + stack.livePreviewQuery(hashMap); + Query entry = stack.contentType("content_type_uid").query(); + entry.find(null); + Assertions.assertNotNull(entry); + } +} diff --git a/src/test/java/com/contentstack/sdk/TestQuery.java b/src/test/java/com/contentstack/sdk/TestQuery.java new file mode 100644 index 00000000..33d10d4e --- /dev/null +++ b/src/test/java/com/contentstack/sdk/TestQuery.java @@ -0,0 +1,893 @@ +package com.contentstack.sdk; + +import io.github.cdimascio.dotenv.Dotenv; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.jupiter.api.*; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class TestQuery { + + private final Logger logger = Logger.getLogger(TestQuery.class.getName()); + private String DEFAULT_API_KEY, DEFAULT_DELIVERY_TOKEN, DEFAULT_ENV; + private Stack stack; + private Query query; + private String entryUid; + + @BeforeAll + public void beforeAll() throws IllegalAccessException { + logger.setLevel(Level.FINE); + Dotenv dotenv = Dotenv.load(); + DEFAULT_API_KEY = dotenv.get("API_KEY"); + DEFAULT_DELIVERY_TOKEN = dotenv.get("DELIVERY_TOKEN"); + DEFAULT_ENV = dotenv.get("ENVIRONMENT"); + String DEFAULT_HOST = dotenv.get("HOST"); + Config config = new Config(); + config.setHost(DEFAULT_HOST); + assert DEFAULT_API_KEY != null; + stack = Contentstack.stack(DEFAULT_API_KEY, DEFAULT_DELIVERY_TOKEN, DEFAULT_ENV, config); + } + + @BeforeEach + public void beforeEach() { + query = stack.contentType("product").query(); + } + + @Test + @Order(1) + void testAllEntries() { + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + entryUid = queryresult.getResultObjects().get(0).uid; + Assertions.assertNotNull(queryresult); + Assertions.assertEquals(27, queryresult.getResultObjects().size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test() + @Order(2) + void testWhereEquals() { + Query query = stack.contentType("categories").query(); + query.where("title", "Women"); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + List titles = queryresult.getResultObjects(); + Assertions.assertEquals("Women", titles.get(0).title); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test() + @Order(4) + void testWhereEqualsWithUid() { + query.where("uid", this.entryUid); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + List titles = queryresult.getResultObjects(); + Assertions.assertEquals("Blue Yellow", titles.get(0).title); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test() + @Order(3) + void testWhere() { + Query query = stack.contentType("product").query(); + query.where("title", "Blue Yellow"); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + List listOfEntries = queryresult.getResultObjects(); + Assertions.assertEquals("Blue Yellow", listOfEntries.get(0).title); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(4) + void testIncludeReference() { + query.includeReference("category"); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + List listOfEntries = queryresult.getResultObjects(); + logger.fine(listOfEntries.toString()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(5) + void testNotContainedInField() { + 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(); + Assertions.assertEquals(25, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(6) + void testContainedInField() { + String[] containArray = new String[] { "Roti Maker", "kids dress" }; + query.containedIn("title", containArray); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(2, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(7) + void testNotEqualTo() { + 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(); + Assertions.assertEquals(26, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(8) + void testGreaterThanOrEqualTo() { + 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(); + Assertions.assertEquals(10, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(9) + void testGreaterThanField() { + 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(); + Assertions.assertEquals(9, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(10) + void testLessThanEqualField() { + 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(); + Assertions.assertEquals(17, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(11) + void testLessThanField() { + query.lessThan("price", "90"); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(0, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(12) + void testEntriesWithOr() { + + ContentType ct = stack.contentType("product"); + 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 entries = queryresult.getResultObjects(); + Assertions.assertEquals(18, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(13) + void testEntriesWithAnd() { + + ContentType ct = stack.contentType("product"); + 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 entries = queryresult.getResultObjects(); + Assertions.assertEquals(2, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(14) + void testAddQuery() { + query.addQuery("limit", "8"); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(8, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(15) + void testRemoveQueryFromQuery() { + 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 entries = queryresult.getResultObjects(); + Assertions.assertEquals(27, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(16) + void testIncludeSchema() { + query.includeContentType(); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(27, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(17) + void testSearch() { + 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(); + Object value = jsonObject.opt(key); + Assertions.assertNotNull(value); + } + } + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(18) + void testAscending() { + 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 (int i = 0; i < entries.size(); i++) { + String previous = entries.get(i).getTitle(); // get first string + String next = entries.get(i + 1).getTitle(); // get second string + if (previous.compareTo(next) < 0) { // compare both if less than Zero then Ascending else + // descending + Assertions.assertTrue(true); + } else { + Assertions.fail("expected descending, found ascending"); + } + } + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(19) + void testDescending() { + 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 (int i = 0; i < entries.size(); i++) { + String previous = entries.get(i).getTitle(); // get first string + String next = entries.get(i + 1).getTitle(); // get second string + if (previous.compareTo(next) < 0) { // compare both if less than Zero then Ascending else + // descending + Assertions.fail("expected descending, found ascending"); + } else { + Assertions.assertTrue(true); + } + } + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(20) + void testLimit() { + query.limit(3); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(3, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(21) + void testSkip() { + query.skip(3); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(24, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(22) + void testOnly() { + 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(); + Assertions.assertEquals(0, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(23) + void testExcept() { + query.except(new String[] { "price" }); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(27, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(24) + @Deprecated + void testCount() { + query.count(); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(0, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(25) + void testRegex() { + 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(); + Assertions.assertEquals(1, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(26) + void testExist() { + query.exists("title"); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(27, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(27) + void testNotExist() { + query.notExists("price1"); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(27, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(28) + void testTags() { + 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(); + Assertions.assertEquals(1, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + + } + + @Test + @Order(29) + void testLanguage() { + query.locale("en-us"); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(27, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + + } + + @Test + @Order(30) + void testIncludeCount() { + query.includeCount(); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + Assertions.assertTrue(queryresult.receiveJson.has("count")); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(31) + void testIncludeReferenceOnly() { + + final Query query = stack.contentType("multifield").query(); + query.where("uid", "fakeIt"); + + ArrayList strings = new ArrayList<>(); + strings.add("title"); + + ArrayList strings1 = new ArrayList<>(); + strings1.add("title"); + strings1.add("brief_description"); + strings1.add("discount"); + strings1.add("price"); + strings1.add("in_stock"); + + query.onlyWithReferenceUid(strings, "package_info.info_category"); + query.exceptWithReferenceUid(strings1, "product_ref"); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(0, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + + } + + @Test + @Order(32) + void testIncludeReferenceExcept() { + query = query.where("uid", "fakeit"); + ArrayList strings = new ArrayList<>(); + strings.add("title"); + query.exceptWithReferenceUid(strings, "category"); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(0, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + + } + + @Test + @Order(33) + void testFindOne() { + query.includeCount(); + query.where("in_stock", true); + query.findOne(new SingleQueryResultCallback() { + @Override + public void onCompletion(ResponseType responseType, Entry entry, Error error) { + if (error == null) { + String entries = entry.getTitle(); + Assertions.assertNotNull(entries); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(34) + void testComplexFind() { + 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(); + Assertions.assertEquals(27, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(35) + void testIncludeSchemaCheck() { + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + JSONArray schema = queryresult.getSchema(); + Assertions.assertEquals(27, schema.length()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(36) + void testIncludeContentType() { + query.includeContentType(); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + List entries = queryresult.getResultObjects(); + Assertions.assertEquals(27, entries.size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(37) + void testIncludeContentTypeFetch() { + query.includeContentType(); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + JSONObject contentType = queryresult.getContentType(); + Assertions.assertEquals("", contentType.optString("")); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(38) + void testAddParams() { + query.addParam("keyWithNull", "null"); + query.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + Object nullObject = query.urlQueries.opt("keyWithNull"); + assertEquals("null", nullObject.toString()); + } + } + }); + } + + @Test + @Order(39) + void testIncludeFallback() { + Query queryFallback = stack.contentType("categories").query(); + queryFallback.locale("hi-in"); + queryFallback.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + assertEquals(9, queryresult.getResultObjects().size()); + queryFallback.includeFallback().locale("hi-in"); + queryFallback.find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + assertEquals(9, queryresult.getResultObjects().size()); + } + }); + } + } + }); + } + + @Test + @Order(40) + void testWithoutIncludeFallback() { + Query queryFallback = stack.contentType("categories").query(); + queryFallback.locale("hi-in").find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + assertEquals(9, queryresult.getResultObjects().size()); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(41) + void testQueryIncludeEmbeddedItems() { + final Query query = stack.contentType("categories").query(); + query.includeEmbeddedItems().find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + assertTrue(query.urlQueries.has("include_embedded_items[]")); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(41) + void testQueryIncludeBranch() { + query.includeBranch().find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + if (error == null) { + assertTrue(query.urlQueries.has("include_branch")); + Assertions.assertEquals(true, query.urlQueries.opt("include_branch")); + } else { + Assertions.fail("Failing, Verify credentials"); + } + } + }); + } + + @Test + @Order(52) + void testQueryPassConfigBranchIncludeBranch() throws IllegalAccessException { + Config config = new Config(); + config.setBranch("feature_branch"); + Stack branchStack = Contentstack.stack(DEFAULT_API_KEY, DEFAULT_DELIVERY_TOKEN, DEFAULT_ENV, config); + Query query = branchStack.contentType("product").query(); + query.includeBranch().find(new QueryResultsCallBack() { + @Override + public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) { + logger.info("No result expected"); + } + }); + Assertions.assertTrue(query.urlQueries.has("include_branch")); + Assertions.assertEquals(true, query.urlQueries.opt("include_branch")); + Assertions.assertTrue(query.headers.containsKey("branch")); + logger.info("passed..."); + } + + // @Test @Order(53) + // void testIncludeBranchAPI() throws IllegalAccessException { + // Dotenv dotenv = Dotenv.load(); + // String apiKey = dotenv.get("apiKey"); + // String deliveryToken = dotenv.get("deliveryToken"); + // String env = dotenv.get("env"); + // Config config = new Config(); + // config.setHost("development"); + // Stack stack = Contentstack.stack(apiKey, deliveryToken, env, config); + // query = stack.contentType("menu").query(); + // query.includeBranch().find(null); + // } + +} \ No newline at end of file diff --git a/src/test/java/com/contentstack/sdk/TestStack.java b/src/test/java/com/contentstack/sdk/TestStack.java new file mode 100644 index 00000000..3c284f58 --- /dev/null +++ b/src/test/java/com/contentstack/sdk/TestStack.java @@ -0,0 +1,419 @@ +package com.contentstack.sdk; + +import io.github.cdimascio.dotenv.Dotenv; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.jupiter.api.*; + +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.logging.Logger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class TestStack { + + Stack stack; + protected String API_KEY, DELIVERY_TOKEN, ENV; + protected String paginationToken; + private final Logger logger = Logger.getLogger(TestStack.class.getName()); + + @BeforeEach + public void initBeforeTests() throws IllegalAccessException { + Dotenv dotenv = Dotenv.load(); + API_KEY = dotenv.get("API_KEY"); + DELIVERY_TOKEN = dotenv.get("DELIVERY_TOKEN"); + ENV = dotenv.get("ENVIRONMENT"); + stack = Contentstack.stack(API_KEY, DELIVERY_TOKEN, ENV); + } + + @Test + @Order(1) + void stackExceptionTesting() { + IllegalAccessException thrown = Assertions.assertThrows(IllegalAccessException.class, Stack::new, + "Can Not Access Private Modifier"); + assertEquals("Can Not Access Private Modifier", thrown.getLocalizedMessage()); + } + + @Test + @Order(2) + void testStackInitThrowErr() { + try { + stack = new Stack(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + assertEquals("Can Not Access Private Modifier", e.getLocalizedMessage()); + } + } + + @Test + @Order(3) + void testConstantConstructor() { + Assertions.assertNotNull(new Constants()); + } + + @Test + @Order(4) + void testStackAddHeader() { + stack.setHeader("abcd", "justForTesting"); + assertTrue(stack.headers.containsKey("abcd")); + } + + @Test + @Order(5) + void testStackRemoveHeader() { + stack.removeHeader("abcd"); + Assertions.assertFalse(stack.headers.containsKey("abcd")); + } + + @Test + @Order(6) + void testContentTypeInstance() { + stack.contentType("product"); + assertEquals("product", stack.contentType); + } + + @Test + @Order(7) + void testAssetWithUidInstance() { + Asset instance = stack.asset("fakeUid"); + Assertions.assertNotNull(instance); + } + + @Test + @Order(8) + void testAssetInstance() { + Asset instance = stack.asset(); + Assertions.assertNotNull(instance); + } + + @Test + @Order(9) + void testAssetLibraryInstance() { + AssetLibrary instance = stack.assetLibrary(); + Assertions.assertNotNull(instance); + } + + @Test + @Order(11) + void testGetApplicationKeyKey() { + assertTrue(stack.getApplicationKey().startsWith("blt")); + } + + @Test + @Order(12) + void testGetApiKey() { + assertTrue(stack.getApplicationKey().startsWith("blt")); + } + + @Test + @Order(13) + void testGetDeliveryToken() { + assertTrue(stack.getDeliveryToken().startsWith("blt")); + } + + @Test + @Deprecated + @Order(14) + void testGetAccessToken() { + assertTrue(stack.getAccessToken().startsWith("blt")); + } + + @Test + @Order(15) + void testRemoveHeader() { + stack.removeHeader("environment"); + Assertions.assertFalse(stack.headers.containsKey("environment")); + stack.setHeader("environment", ENV); + } + + @Test + @Order(16) + void testSetHeader() { + stack.setHeader("environment", ENV); + assertTrue(stack.headers.containsKey("environment")); + } + + @Test + @Order(17) + void testImageTransform() { + HashMap params = new HashMap<>(); + params.put("fakeKey", "fakeValue"); + String newUrl = stack.imageTransform("www.fakeurl.com/fakePath/fakeImage.png", params); + assertEquals("www.fakeurl.com/fakePath/fakeImage.png?fakeKey=fakeValue", newUrl); + } + + @Test + @Order(18) + void testImageTransformWithQuestionMark() { + LinkedHashMap linkedMap = new LinkedHashMap<>(); + linkedMap.put("fakeKey", "fakeValue"); + String newUrl = stack.imageTransform("www.fakeurl.com/fakePath/fakeImage.png?name=ishaileshmishra", linkedMap); + assertEquals("www.fakeurl.com/fakePath/fakeImage.png?name=ishaileshmishra&fakeKey=fakeValue", newUrl); + } + + @Test + @Order(19) + void testGetContentTypes() { + JSONObject params = new JSONObject(); + params.put("fakeKey", "fakeValue"); + params.put("fakeKey1", "fakeValue2"); + stack.getContentTypes(params, null); + assertEquals(4, params.length()); + } + + @Test + @Order(20) + void testSyncWithoutCallback() { + stack.sync(null); + assertEquals(2, stack.syncParams.length()); + assertTrue(stack.syncParams.has("init")); + } + + @Test + @Order(21) + void testSyncPaginationTokenWithoutCallback() { + stack.syncPaginationToken("justFakeToken", null); + assertEquals(3, stack.syncParams.length()); + assertEquals("justFakeToken", stack.syncParams.get("pagination_token")); + assertTrue(stack.syncParams.has("init")); + assertTrue(stack.syncParams.has("environment")); + } + + @Test + @Order(22) + void testSyncTokenWithoutCallback() { + stack.syncToken("justFakeToken", null); + assertEquals(3, stack.syncParams.length()); + assertEquals("justFakeToken", stack.syncParams.get("sync_token")); + assertTrue(stack.syncParams.has("init")); + assertTrue(stack.syncParams.has("environment")); + } + + @Test + @Order(23) + void testSyncFromDateWithoutCallback() { + Date date = new Date(); + stack.syncFromDate(date, null); + assertEquals(3, stack.syncParams.length()); + assertTrue(stack.syncParams.get("start_from").toString().endsWith("Z")); + assertTrue(stack.syncParams.has("init")); + assertTrue(stack.syncParams.has("environment")); + } + + @Test + @Order(24) + void testPrivateDateConverter() { + Date date = new Date(); + String newDate = stack.convertUTCToISO(date); + assertTrue(newDate.endsWith("Z")); + } + + @Test + @Order(25) + void testSyncContentTypeWithoutCallback() { + stack.syncContentType("fakeContentType", null); + assertEquals(3, stack.syncParams.length()); + assertEquals("fakeContentType", stack.syncParams.get("content_type_uid")); + assertTrue(stack.syncParams.has("init")); + assertTrue(stack.syncParams.has("environment")); + } + + @Test + @Order(27) + void testSyncLocaleWithoutCallback() { + stack.syncLocale("en-us", null); + assertEquals(3, stack.syncParams.length()); + assertEquals("en-us", stack.syncParams.get("locale")); + assertTrue(stack.syncParams.has("init")); + assertTrue(stack.syncParams.has("environment")); + } + + @Test + @Order(28) + void testSyncPublishTypeEntryPublished() { + stack.syncPublishType(Stack.PublishType.entry_published, null); + assertEquals(3, stack.syncParams.length()); + assertEquals("entry_published", stack.syncParams.get("type")); + assertTrue(stack.syncParams.has("init")); + assertTrue(stack.syncParams.has("environment")); + } + + @Test + @Order(29) + void testSyncPublishTypeAssetDeleted() { + stack.syncPublishType(Stack.PublishType.asset_deleted, null); + assertEquals(3, stack.syncParams.length()); + assertEquals("asset_deleted", stack.syncParams.get("type")); + assertTrue(stack.syncParams.has("init")); + assertTrue(stack.syncParams.has("environment")); + } + + @Test + @Order(30) + void testSyncPublishTypeAssetPublished() { + stack.syncPublishType(Stack.PublishType.asset_published, null); + assertEquals(3, stack.syncParams.length()); + assertEquals("asset_published", stack.syncParams.get("type")); + assertTrue(stack.syncParams.has("init")); + assertTrue(stack.syncParams.has("environment")); + } + + @Test + @Order(31) + void testSyncPublishTypeAssetUnPublished() { + stack.syncPublishType(Stack.PublishType.asset_unpublished, null); + assertEquals(3, stack.syncParams.length()); + assertEquals("asset_unpublished", stack.syncParams.get("type")); + assertTrue(stack.syncParams.has("init")); + assertTrue(stack.syncParams.has("environment")); + } + + @Test + @Order(32) + void testSyncPublishTypeContentTypeDeleted() { + stack.syncPublishType(Stack.PublishType.content_type_deleted, null); + assertEquals(3, stack.syncParams.length()); + assertEquals("content_type_deleted", stack.syncParams.get("type")); + assertTrue(stack.syncParams.has("init")); + assertTrue(stack.syncParams.has("environment")); + } + + @Test + @Order(33) + void testSyncPublishTypeEntryDeleted() { + stack.syncPublishType(Stack.PublishType.entry_deleted, null); + assertEquals(3, stack.syncParams.length()); + assertEquals("entry_deleted", stack.syncParams.get("type")); + assertTrue(stack.syncParams.has("init")); + assertTrue(stack.syncParams.has("environment")); + } + + @Test + @Order(34) + void testSyncPublishTypeEntryUnpublished() { + stack.syncPublishType(Stack.PublishType.entry_unpublished, null); + assertEquals(3, stack.syncParams.length()); + assertEquals("entry_unpublished", stack.syncParams.get("type")); + assertTrue(stack.syncParams.has("init")); + assertTrue(stack.syncParams.has("environment")); + } + + @Test + @Order(35) + void testSyncIncludingMultipleParams() { + Date newDate = new Date(); + String startFrom = stack.convertUTCToISO(newDate); + stack.sync("product", newDate, "en-us", Stack.PublishType.entry_published, null); + assertEquals(6, stack.syncParams.length()); + assertEquals("entry_published", stack.syncParams.get("type")); + assertEquals("en-us", stack.syncParams.get("locale")); + assertEquals("product", stack.syncParams.get("content_type_uid")); + assertEquals(startFrom, stack.syncParams.get("start_from")); + assertTrue(stack.syncParams.has("init")); + assertTrue(stack.syncParams.has("environment")); + } + + @Test + @Order(36) + void testGetAllContentTypes() { + JSONObject param = new JSONObject(); + stack.getContentTypes(param, new ContentTypesCallback() { + @Override + public void onCompletion(ContentTypesModel contentTypesModel, Error error) { + assertTrue(contentTypesModel.getResponse() instanceof JSONArray); + assertEquals(5, ((JSONArray) contentTypesModel.getResponse()).length()); + } + }); + } + + @Test + @Order(37) + void testSynchronization() { + stack.sync(new SyncResultCallBack() { + @Override + public void onCompletion(SyncStack syncStack, Error error) { + if (error == null) { + logger.info(syncStack.getPaginationToken()); + } else { + logger.info(error.errorMessage); + assertEquals(105, error.errorCode); + } + } + }); + } + + @Test + @Order(38) + void testConfigSetRegion() { + Config config = new Config(); + config.setRegion(Config.ContentstackRegion.US); + assertEquals("US", config.getRegion().toString()); + } + + @Test + @Order(39) + void testConfigGetRegion() { + Config config = new Config(); + assertEquals("US", config.getRegion().toString()); + } + + @Test + @Order(40) + void testConfigGetHost() { + Config config = new Config(); + assertEquals(config.host, config.getHost()); + } + + @Test + @Order(41) + void testSynchronizationAPIRequest() throws IllegalAccessException { + Dotenv dotenv = Dotenv.load(); + String apiKey = dotenv.get("apiKey"); + String deliveryToken = dotenv.get("deliveryToken"); + String env = dotenv.get("env"); + Stack stack = Contentstack.stack(apiKey, deliveryToken, env); + stack.sync(new SyncResultCallBack() { + @Override + public void onCompletion(SyncStack response, Error error) { + paginationToken = response.getPaginationToken(); + Assertions.assertNull(response.getUrl()); + Assertions.assertNotNull(response.getJSONResponse()); + Assertions.assertEquals(129, response.getCount()); + Assertions.assertEquals(100, response.getLimit()); + Assertions.assertEquals(0, response.getSkip()); + Assertions.assertNotNull(response.getPaginationToken()); + Assertions.assertNull(response.getSyncToken()); + Assertions.assertEquals(100, response.getItems().size()); + } + }); + } + + @Test + @Order(42) + void testSyncPaginationToken() throws IllegalAccessException { + Dotenv dotenv = Dotenv.load(); + String apiKey = dotenv.get("apiKey"); + String deliveryToken = dotenv.get("deliveryToken"); + String env = dotenv.get("env"); + Stack stack = Contentstack.stack(apiKey, deliveryToken, env); + stack.syncPaginationToken(paginationToken, new SyncResultCallBack() { + @Override + public void onCompletion(SyncStack response, Error error) { + Assertions.assertNull(response.getUrl()); + Assertions.assertNotNull(response.getJSONResponse()); + Assertions.assertEquals(29, response.getCount()); + Assertions.assertEquals(100, response.getLimit()); + Assertions.assertEquals(100, response.getSkip()); + Assertions.assertNull(response.getPaginationToken()); + Assertions.assertNotNull(response.getSyncToken()); + Assertions.assertEquals(29, response.getItems().size()); + } + }); + } + +} diff --git a/src/test/resources/assets/asset.json b/src/test/resources/assets/asset.json new file mode 100644 index 00000000..e204e502 --- /dev/null +++ b/src/test/resources/assets/asset.json @@ -0,0 +1,46 @@ +{ + "asset": { + "uid": "fake-uid-inserted", + "created_at": "2016-04-06T11:06:10.601Z", + "updated_at": "2016-12-16T12:36:33.961Z", + "created_by": "fake-crater", + "updated_by": "fake-crater", + "content_type": "image/jpeg", + "file_size": "482141", + "tags": [ + "abc", + "pqr", + "xyz" + ], + "filename": "phoenix2.jpg", + "url": "https://images.contentstack.io/v3/assets/phoenix2.jpg", + "ACL": { + "roles": [], + "others": { + "read": false, + "create": false, + "update": false, + "delete": false, + "sub_acl": { + "read": false, + "create": false, + "update": false, + "delete": false, + "publish": false + } + } + }, + "is_dir": false, + "_version": 1, + "title": "phoenix2.jpg", + "publish_details": [ + { + "environment": "fake-crater", + "locale": "en-us", + "version": 1, + "user": "fake-crater", + "time": "2016-12-16T12:36:35.781Z" + } + ] + } +} \ No newline at end of file