diff --git a/CHANGELOG.md b/CHANGELOG.md index 137dc5f2..6f202ece 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,15 @@ # CHANGELOG -## v1.12.3 + +## v1.13.0 + +### Date: 18-Dec-2023 + +- Taxonomy Query Support +- Updated Latest version of Utils SDK to 1.2.6 +- Snyk Issues fixed +- Updated dependencies +- Added support for early access feature ### Date: 28-SEP-2023 diff --git a/pom.xml b/pom.xml index d326775a..0a0afd80 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ 4.0.0 com.contentstack.sdk java - 1.12.3 + 1.13.0 jar contentstack-java Java SDK for Contentstack Content Delivery API @@ -25,7 +25,7 @@ 5.0.0-alpha.11 0.8.5 1.18.30 - 5.10.0 + 5.10.1 5.8.0-M1 2.8.8 1.1.1 @@ -33,10 +33,10 @@ 1.5 3.8.1 1.6.13 - 20230618 + 20231013 0.8.7 2.5.3 - 1.2.4 + 1.2.6 diff --git a/src/main/java/com/contentstack/sdk/APIService.java b/src/main/java/com/contentstack/sdk/APIService.java index a537f0d8..5bf3462b 100644 --- a/src/main/java/com/contentstack/sdk/APIService.java +++ b/src/main/java/com/contentstack/sdk/APIService.java @@ -4,9 +4,11 @@ import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.HeaderMap; +import retrofit2.http.Query; import retrofit2.http.Url; import java.util.LinkedHashMap; +import java.util.Map; /** * @author Shailesh Mishra @@ -15,5 +17,11 @@ */ public interface APIService { @GET - Call getRequest(@Url String url, @HeaderMap LinkedHashMap headers); + Call getRequest( + @Url String url, @HeaderMap LinkedHashMap headers); + + @GET("v3/taxonomies/entries") + Call getTaxonomy( + @HeaderMap Map headers, + @Query("query") String query); } diff --git a/src/main/java/com/contentstack/sdk/CSHttpConnection.java b/src/main/java/com/contentstack/sdk/CSHttpConnection.java index 38792649..9eda41c0 100644 --- a/src/main/java/com/contentstack/sdk/CSHttpConnection.java +++ b/src/main/java/com/contentstack/sdk/CSHttpConnection.java @@ -186,7 +186,8 @@ public void send() { } private void getService(String requestUrl) throws IOException { - this.headers.put(X_USER_AGENT_KEY, "contentstack-java/" + SDK_VERSION); + + this.headers.put(X_USER_AGENT_KEY, "contentstack-delivery-java/" + SDK_VERSION); this.headers.put(USER_AGENT_KEY, USER_AGENT); this.headers.put(CONTENT_TYPE, APPLICATION_JSON); @@ -260,7 +261,6 @@ void handleJSONObject(JSONArray arrayEntry, JSONObject jsonObj, int idx) { } 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)); diff --git a/src/main/java/com/contentstack/sdk/Config.java b/src/main/java/com/contentstack/sdk/Config.java index fd736a6d..5d436901 100644 --- a/src/main/java/com/contentstack/sdk/Config.java +++ b/src/main/java/com/contentstack/sdk/Config.java @@ -1,5 +1,7 @@ package com.contentstack.sdk; +import lombok.Getter; +import lombok.Setter; import okhttp3.ConnectionPool; import org.jetbrains.annotations.NotNull; import org.json.JSONObject; @@ -26,12 +28,19 @@ public class Config { protected JSONObject livePreviewEntry = null; protected ContentstackRegion region = ContentstackRegion.US; protected String managementToken; + @Setter + @Getter protected String branch; + @Setter protected Proxy proxy = null; protected ConnectionPool connectionPool = new ConnectionPool(); protected List plugins = null; + + /** + * -- GETTER -- + * The configuration for the contentstack that contains support for public String getBranch() { return branch; } @@ -55,9 +64,8 @@ public void setBranch(String branch) { * config = new Config(); config.setProxy(proxy); * */ - public void setProxy(Proxy proxy) { - this.proxy = proxy; - } + @Getter + protected String[] earlyAccess; /** * Returns the Proxy instance @@ -73,12 +81,9 @@ public Proxy getProxy() { * {@link okhttp3.Address} may share a {@link okhttp3.Connection}. This class implements the policy * of which * connections to keep open for future use. * - * @param maxIdleConnections - * the maxIdleConnections default value is 5 - * @param keepAliveDuration - * the keepAliveDuration default value is 5 - * @param timeUnit - * the timeUnit default value is TimeUnit. MINUTES + * @param maxIdleConnections the maxIdleConnections default value is 5 + * @param keepAliveDuration the keepAliveDuration default value is 5 + * @param timeUnit the timeUnit default value is TimeUnit. MINUTES * @return ConnectionPool */ public ConnectionPool connectionPool(int maxIdleConnections, long keepAliveDuration, TimeUnit timeUnit) { @@ -98,8 +103,7 @@ public ContentstackRegion getRegion() { /** * Sets region. * - * @param region - * the region + * @param region the region * @return the region */ public ContentstackRegion setRegion(ContentstackRegion region) { @@ -119,20 +123,10 @@ public void setPlugins(List plugins) { this.plugins = plugins; } - /** - * Gets host. - * - * @return the host - */ - public String getHost() { - return host; - } - /** * Sets host. * - * @param hostName - * the host name + * @param hostName the host name */ public void setHost(String hostName) { if (hostName != null && !hostName.isEmpty()) { @@ -152,8 +146,7 @@ public String getVersion() { /** * Enable live preview config. * - * @param enableLivePreview - * to enable live preview + * @param enableLivePreview to enable live preview * @return the config */ public Config enableLivePreview(boolean enableLivePreview) { @@ -164,8 +157,7 @@ public Config enableLivePreview(boolean enableLivePreview) { /** * Sets live preview host. * - * @param livePreviewHost - * the live preview host + * @param livePreviewHost the live preview host * @return the live preview host */ public Config setLivePreviewHost(@NotNull String livePreviewHost) { @@ -181,8 +173,7 @@ protected Config setLivePreviewEntry(@NotNull JSONObject livePreviewEntry) { /** * Sets management token. * - * @param managementToken - * the management token + * @param managementToken the management token * @return the management token */ public Config setManagementToken(@NotNull String managementToken) { @@ -197,4 +188,24 @@ public enum ContentstackRegion { US, EU, AZURE_NA, AZURE_EU } + + /** + * To initialize the SDK with the latest features offered in the early access phase, + * include the early access parameter as shown in the following code: + * + * @param earlyAccessFeatures The list of Early Access Features + * {@code + * Config config = new Config(); + * String[] earlyAccess = {"Taxonomy", "Teams", "Terms", "LivePreview"}; + * config.earlyAccess(earlyAccess); + * Stack stack = Contentstack.stack(API_KEY, DELIVERY_TOKEN, ENV, config); + *

+ * } + * @return Config + */ + public Config earlyAccess(@NotNull String[] earlyAccessFeatures) { + this.earlyAccess = earlyAccessFeatures; + return this; + } + } diff --git a/src/main/java/com/contentstack/sdk/Constants.java b/src/main/java/com/contentstack/sdk/Constants.java index fcb5fab9..24917225 100644 --- a/src/main/java/com/contentstack/sdk/Constants.java +++ b/src/main/java/com/contentstack/sdk/Constants.java @@ -21,7 +21,7 @@ public class Constants { private static final Logger logger = Logger.getLogger(Constants.class.getSimpleName()); - protected static final String SDK_VERSION = "1.12.3"; + protected static final String SDK_VERSION = "1.13.0"; protected static final String ENVIRONMENT = "environment"; protected static final String CONTENT_TYPE_UID = "content_type_uid"; protected static final String ENTRY_UID = "entry_uid"; diff --git a/src/main/java/com/contentstack/sdk/Contentstack.java b/src/main/java/com/contentstack/sdk/Contentstack.java index aa7fe895..c12ebf3a 100644 --- a/src/main/java/com/contentstack/sdk/Contentstack.java +++ b/src/main/java/com/contentstack/sdk/Contentstack.java @@ -31,27 +31,23 @@ protected Contentstack() throws IllegalAccessException { * 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 + * @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 environment the environment for the stack * @return the stack - * @throws IllegalAccessException - * the illegal access exception + * @throws IllegalAccessException the illegal access exception *

* Example * *

-     *                                {
-     *                                    @Code
-     *                                    Stack stack = contentstack.Stack("apiKey", "deliveryToken", "environment");
-     *                                }
+     *                                                                                              {
+     *                                                                                                  @Code
+     *                                                                                                  Stack stack = contentstack.Stack("apiKey", "deliveryToken", "environment");
+     *                                                                                              }
      *
-     *                                
+ * */ public static Stack stack(String stackApiKey, String deliveryToken, String environment) throws IllegalAccessException { @@ -66,6 +62,7 @@ public static Stack stack(String stackApiKey, String deliveryToken, String envir * create content structures, content entries, users, etc. related to the * project. * + * @param stackApiKey * The API Key is a unique key assigned to each stack. * @param deliveryToken @@ -115,6 +112,10 @@ private static Stack initializeStack(String stackApiKey, String deliveryToken, S if (config.getBranch() != null && !config.getBranch().isEmpty()) { stack.setHeader("branch", config.getBranch()); } + if (config.getEarlyAccess() != null && config.getEarlyAccess().length > 0) { + String eaValues = String.join(",", config.earlyAccess).replace("\"", ""); + stack.setHeader("x-header-ea", eaValues); + } stack.setConfig(config); return stack; } diff --git a/src/main/java/com/contentstack/sdk/Query.java b/src/main/java/com/contentstack/sdk/Query.java index ce2c63ea..526f6df9 100644 --- a/src/main/java/com/contentstack/sdk/Query.java +++ b/src/main/java/com/contentstack/sdk/Query.java @@ -63,21 +63,21 @@ protected void setContentTypeInstance(ContentType contentTypeInstance) { /** * 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 :
- *

- * tack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment"); Query query = - * stack.contentType("contentTypeUid").query(); query.setHeader("custom_key", "custom_value"); - * Example :
- *

- * Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment"); Query csQuery = - * stack.contentType("contentTypeUid").query(); csQuery.setHeader("custom_key", "custom_value"); + * @param key header name. + * @param value header value against given header name.
+ * + *
+ *
+ * Example :
+ *

+     *                                            Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment");
+     *                                            
+ * Query query = stack.contentType("contentTypeUid").query(); query.setHeader("custom_key", "custom_value"); + *
+ * Stack stack = Contentstack.stack( "apiKey", "deliveryToken", "environment"); + *
+ * Query csQuery = stack.contentType("contentTypeUid").query();
csQuery.setHeader("custom_key", "custom_value"); + *
*/ public Query setHeader(@NotNull String key, @NotNull String value) { if (!key.isEmpty() && !value.isEmpty()) { @@ -95,6 +95,7 @@ public Query setHeader(@NotNull String key, @NotNull String value) { *

* Stack stack = Contentstack..stack( "apiKey", "deliveryToken", "environment"); Query csQuery = * stack.contentType("contentTypeUid").query();
csQuery.removeHeader("custom_key"); + */ public Query removeHeader(@NotNull String key) { if (!key.isEmpty()) { @@ -110,10 +111,8 @@ public String getContentType() { /** * 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. + * @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 @@ -138,10 +137,8 @@ public Query where(@NotNull String key, Object value) { /** * Add a custom query against specified key. * - * @param key - * key. - * @param value - * value. + * @param key key. + * @param value value. * @return {@link Query} object, so you can chain this call. * *
@@ -164,8 +161,7 @@ public Query addQuery(@NotNull String key, String value) { /** * Remove provided query key from custom query if existed. * - * @param key - * Query name to remove. + * @param key Query name to remove. * @return {@linkplain Query} object, so you can chain this call.
* *
@@ -186,8 +182,7 @@ public Query removeQuery(@NotNull String key) { /** * 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. * *
@@ -221,8 +216,7 @@ public Query and(@NotNull List queryObjects) { /** * 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. * *
@@ -262,10 +256,8 @@ public Query or(List queryObjects) { /** * 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. + * @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.
* *
@@ -280,7 +272,7 @@ public Query or(List queryObjects) { */ public Query lessThan(@NotNull String key, @NotNull Object value) { if (queryValueJSON.isNull(key)) { - if (queryValue.length() > 0) { + if (!queryValue.isEmpty()) { queryValue = new JSONObject(); } queryValue.put("$lt", value); @@ -296,10 +288,8 @@ public Query lessThan(@NotNull String key, @NotNull Object 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. + * @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. * *
@@ -314,7 +304,7 @@ public Query lessThan(@NotNull String key, @NotNull Object value) { */ public Query lessThanOrEqualTo(@NotNull String key, Object value) { if (queryValueJSON.isNull(key)) { - if (queryValue.length() > 0) { + if (!queryValue.isEmpty()) { queryValue = new JSONObject(); } queryValue.put("$lte", value); @@ -329,10 +319,8 @@ public Query lessThanOrEqualTo(@NotNull String key, Object 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 a lower bound. + * @param key The key to be constrained. + * @param value The value that provides a lower bound. * @return {@link Query} object, so you can chain this call. * *
@@ -347,7 +335,7 @@ public Query lessThanOrEqualTo(@NotNull String key, Object value) { */ public Query greaterThan(@NotNull String key, Object value) { if (queryValueJSON.isNull(key)) { - if (queryValue.length() > 0) { + if (!queryValue.isEmpty()) { queryValue = new JSONObject(); } queryValue.put("$gt", value); @@ -363,10 +351,8 @@ public Query greaterThan(@NotNull String key, Object 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 a lower bound. + * @param key The key to be constrained. + * @param value The value that provides a lower bound. * @return {@link Query} object, so you can chain this call. * *
@@ -396,10 +382,8 @@ public Query greaterThanOrEqualTo(String key, Object 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. + * @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. * *
@@ -429,10 +413,8 @@ public Query notEqualTo(@NotNull String key, Object value) { /** * 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. + * @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.
* *
@@ -467,10 +449,8 @@ public Query containedIn(@NotNull String key, Object[] values) { * Add a constraint to the query that requires a particular key entry's value not be contained in the provided * array. * - * @param key - * The key to be constrained. - * @param values - * The list of values the key object should not be. + * @param key The key to be constrained. + * @param values The list of values the key object should not be. * @return {@link Query} object, so you can chain this call. * *
@@ -504,8 +484,7 @@ public Query notContainedIn(@NotNull String key, Object[] values) { /** * Add a constraint that requires, a specified key exists in response. * - * @param key - * The key to be constrained. + * @param key The key to be constrained. * @return {@link Query} object, so you can chain this call. * *
@@ -535,8 +514,7 @@ public Query exists(@NotNull String key) { /** * Add a constraint that requires, a specified key does not exist in response. * - * @param key - * The key to be constrained. + * @param key The key to be constrained. * @return {@link Query} object, so you can chain this call.
* * @@ -568,8 +546,7 @@ public Query notExists(@NotNull String key) { /** * Add a constraint that requires a particular reference key details. * - * @param key - * key that to be constrained. + * @param key key that to be constrained. * @return {@link Query} object, so you can chain this call. * *
@@ -593,8 +570,7 @@ public Query includeReference(String key) { /** * Include tags with which to search entries. * - * @param tags - * Comma separated array of 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.
* *
@@ -617,8 +593,7 @@ public Query tags(@NotNull String[] tags) { * 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. + * @param key The key to order by. * @return {@link Query} object, so you can chain this call.
* *
@@ -641,8 +616,7 @@ public Query ascending(@NotNull String 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. + * @param key The key to order by. * @return {@link Query} object, so you can chain this call.
* *
@@ -663,8 +637,7 @@ public Query descending(@NotNull String key) { /** * Specifies list of field ids 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. * *
@@ -695,8 +668,7 @@ public Query except(@NotNull List fieldUid) { /** * Specifies list of field ids that would be 'excluded' from the response. * - * @param fieldIds - * field uid which get 'excluded' from the response. + * @param fieldIds field uid which get 'excluded' from the response. * @return {@link Query} object, so you can chain this call.
* *
@@ -724,8 +696,7 @@ public Query except(@NotNull String[] fieldIds) { /** * 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. + * @param fieldUid Array of the 'only' reference keys to be included in response. * @return {@link Query} object, so you can chain this call.
* *
@@ -753,10 +724,8 @@ public Query only(@NotNull String[] fieldUid) { /** * 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 referenceFieldUid - * Key who has reference to some other class object. + * @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.
* * @@ -792,10 +761,8 @@ public Query onlyWithReferenceUid(@NotNull List fieldUid, @NotNull Strin /** * 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 referenceFieldUid - * Key who has reference to some other class object. + * @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.
* *
@@ -897,8 +864,7 @@ public Query includeContentType() { /** * The number of objects to skip before returning any. * - * @param number - * No of objects to skip from returned objects + * @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, @@ -922,8 +888,7 @@ public Query skip(int number) { /** * A limit on the number of objects to return. * - * @param number - * No of objects to limit. + * @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, " @@ -948,10 +913,8 @@ public Query limit(int number) { * 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 key The key to be constrained. + * @param regex The regular expression pattern to match. * @return {@link Query} object, so you can chain this call.
* *
@@ -983,21 +946,18 @@ public Query regex(@NotNull String key, @NotNull String regex) { * 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 - *

+ * @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.
* *
@@ -1038,8 +998,7 @@ public Query regex(@NotNull String key, @NotNull String regex, String modifiers) /** * set Language using locale code. * - * @param locale - * {@link String} value + * @param locale {@link String} value * @return {@link Query} object, so you can chain this call
*
*
@@ -1059,8 +1018,7 @@ public Query locale(@NotNull String locale) { /** * This method provides only the entries matching the specified value. * - * @param value - * value used to match or compare + * @param value value used to match or compare * @return {@link Query} object, so you can chain this call.
* *
@@ -1084,8 +1042,7 @@ public Query search(@NotNull String value) { /** * Execute a Query and Caches its result (Optional) * - * @param callback - * {@link QueryResultsCallBack} object to notify the application when the request has completed. + * @param callback {@link QueryResultsCallBack} object to notify the application when the request has completed. * @return {@linkplain Query} object, so you can chain this call.
* * @@ -1123,8 +1080,7 @@ public Query find(QueryResultsCallBack callback) { /** * Execute a Query and Caches its result (Optional) * - * @param callBack - * {@link QueryResultsCallBack} object to notify the application when the request has completed. + * @param callBack {@link QueryResultsCallBack} object to notify the application when the request has completed. * @return {@linkplain Query} object, so you can chain this call.
* *
@@ -1294,10 +1250,8 @@ public void getResultObject(List objects, JSONObject jsonObject, boolean /** * 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 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 * @return - Query * *
@@ -1349,10 +1303,8 @@ public Query includeReferenceContentTypUid() { * 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 queryObject - * {@link Query} object, so you can chain this call + * @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
* *
@@ -1376,10 +1328,8 @@ public Query whereIn(@NotNull String key, Query queryObject) { * 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 + * @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 * *
diff --git a/src/main/java/com/contentstack/sdk/Stack.java b/src/main/java/com/contentstack/sdk/Stack.java index 4902a541..f2142155 100644 --- a/src/main/java/com/contentstack/sdk/Stack.java +++ b/src/main/java/com/contentstack/sdk/Stack.java @@ -105,8 +105,7 @@ private void includeLivePreview() { * 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} + * @param query the query of type {@link HashMap} * @return stack *

* Example @@ -117,8 +116,7 @@ private void includeLivePreview() { *

* stack.livePreviewQuery(queryMap) *

- * @throws IOException - * IO Exception + * @throws IOException IO Exception */ public Stack livePreviewQuery(Map query) throws IOException { config.livePreviewHash = query.get(LIVE_PREVIEW); @@ -154,9 +152,8 @@ public Stack livePreviewQuery(Map query) throws IOException { * 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. + * @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 @@ -179,8 +176,7 @@ public ContentType contentType(String contentTypeUid) { * The Get a single asset request fetches the latest version of a specific asset of a particular stack. *

* - * @param uid - * uid of {@link Asset} + * @param uid uid of {@link Asset} * @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. @@ -241,10 +237,9 @@ public String getDeliveryToken() { /** * Removes Header by key * - * @param headerKey - * of the header - *

- * Example: stack.removeHeader("delivery_token"); + * @param headerKey of the header + *

+ * Example: stack.removeHeader("delivery_token"); */ public void removeHeader(String headerKey) { headers.remove(headerKey); @@ -253,10 +248,8 @@ public void removeHeader(String headerKey) { /** * Adds header to the stack * - * @param headerKey - * the header key - * @param headerValue - * the header value + * @param headerKey the header key + * @param headerValue the header value */ public void setHeader(@NotNull String headerKey, @NotNull String headerValue) { if (!headerKey.isEmpty() && !headerValue.isEmpty()) { @@ -269,14 +262,12 @@ public void setHeader(@NotNull String headerKey, @NotNull String headerValue) { * 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} + * @param imageUrl the image url + * @param parameters the parameters {@link LinkedHashMap} * @return the string */ public String imageTransform(@NotNull String imageUrl, @NotNull Map parameters) { - if (parameters.size() == 0) { + if (parameters.isEmpty()) { return imageUrl; } String query = getQueryParam(parameters); @@ -296,11 +287,9 @@ protected String getQueryParam(Map params) { * The Get all content types call returns comprehensive information of all the content types available in a * particular stack in your account.. * - * @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. + * @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 getContentTypes(@NotNull JSONObject params, final ContentTypesCallback callback) { Iterator keys = params.keys(); @@ -321,8 +310,7 @@ public void getContentTypes(@NotNull JSONObject params, final ContentTypesCallba * 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 syncCallBack - * returns callback for sync result. + * @param syncCallBack returns callback for sync result. */ public void sync(SyncResultCallBack syncCallBack) { syncParams = new JSONObject(); @@ -358,21 +346,17 @@ public void syncPaginationToken(@NotNull String paginationToken, SyncResultCallB /** * 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 stack = contentstack.Stack("apiKey", "deliveryToken", "environment");
-     *                                                                                                                                                                                                                                                                                             stack.syncToken("syncToken")
-     *                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     stack.syncToken(sync_token, new SyncResultCallBack()                                                                                                                                                                                                               ){ }
-     *                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
+ + * @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 stack = contentstack.Stack("apiKey", "deliveryToken", "environment");                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
*/ public void syncToken(String syncToken, SyncResultCallBack syncCallBack) { syncParams = new JSONObject(); @@ -383,17 +367,15 @@ public void syncToken(String syncToken, SyncResultCallBack 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 :
- * Stack stack = contentstack.Stack("apiKey", "deliveryToken", "environment"); - * stack.syncFromDate("fromDate") + * @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 :
+ * Stack stack = contentstack.Stack("apiKey", "deliveryToken", "environment"); + * stack.syncFromDate("fromDate") */ public void syncFromDate(@NotNull Date fromDate, SyncResultCallBack syncCallBack) { String newFromDate = convertUTCToISO(fromDate); @@ -413,18 +395,16 @@ protected String convertUTCToISO(Date date) { /** * Sync 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 : - *

- * stack.syncContentType(String content_type, new SyncResultCallBack()){ } + * @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 : + *

+ * stack.syncContentType(String content_type, new SyncResultCallBack()){ } */ public void syncContentType(@NotNull String contentType, SyncResultCallBack syncCallBack) { syncParams = new JSONObject(); @@ -436,18 +416,16 @@ public void syncContentType(@NotNull String contentType, SyncResultCallBack sync /** * Sync locale. * - * @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 :
- * Stack stack = contentstack.Stack("apiKey", "deliveryToken", "environment"); stack.syncContentType(String - * content_type, new SyncResultCallBack()){ } + * @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 :
+ * Stack stack = contentstack.Stack("apiKey", "deliveryToken", "environment"); stack.syncContentType(String + * content_type, new SyncResultCallBack()){ } */ public void syncLocale(String localeCode, SyncResultCallBack syncCallBack) { syncParams = new JSONObject(); @@ -459,25 +437,23 @@ public void syncLocale(String localeCode, SyncResultCallBack syncCallBack) { /** * 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 :
- * - * Stack stack = contentstack.Stack("apiKey", "deliveryToken", "environment"); * - * stack.syncPublishType(PublishType) - * + * @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 :
+ * + * Stack stack = contentstack.Stack("apiKey", "deliveryToken", "environment"); * + * stack.syncPublishType(PublishType) + * */ public void syncPublishType(PublishType publishType, SyncResultCallBack syncCallBack) { syncParams = new JSONObject(); @@ -489,22 +465,17 @@ public void syncPublishType(PublishType publishType, SyncResultCallBack syncCall /** * Sync. * - * @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 :
+ * @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 :
*/ public void sync(String contentType, Date fromDate, String localeCode, PublishType publishType, SyncResultCallBack syncCallBack) { @@ -547,7 +518,7 @@ private void fetchFromNetwork(String urlString, JSONObject urlQueries, private HashMap getUrlParams(JSONObject jsonQuery) { HashMap hashMap = new HashMap<>(); - if (jsonQuery != null && jsonQuery.length() > 0) { + if (jsonQuery != null && !jsonQuery.isEmpty()) { Iterator iteString = jsonQuery.keys(); while (iteString.hasNext()) { String key = iteString.next(); @@ -558,8 +529,15 @@ private HashMap getUrlParams(JSONObject jsonQuery) { return hashMap; } + + public Taxonomy taxonomy() { + return new Taxonomy(this.service,this.config, this.headers); + } + + /** * The enum Publish type. + * @since v3.11.0 */ public enum PublishType { //asset_deleted, asset_published, asset_unpublished, content_type_deleted, entry_deleted, entry_published, diff --git a/src/main/java/com/contentstack/sdk/Taxonomy.java b/src/main/java/com/contentstack/sdk/Taxonomy.java new file mode 100644 index 00000000..cdb7da2e --- /dev/null +++ b/src/main/java/com/contentstack/sdk/Taxonomy.java @@ -0,0 +1,330 @@ +package com.contentstack.sdk; + +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; +import org.json.JSONObject; +import retrofit2.Call; +import retrofit2.Response; + +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.List; + +/** + * @author Shailesh Mishra + *
+ * Taxonomy : + * Taxonomy, currently in the Early Access Phase simplifies + * the process of organizing content in your system, making + * it effortless to find and retrieve information. + * @implSpec To implement the taxonomy use below code + *

+ *     {@code
+ *     Stack stack = Contentstack.stack("API_KEY", "DELIVERY_TOKEN", "ENVIRONMENT");
+ *     Taxonomy taxonomy = stack.taxonomy()
+ *     }
+ * 
+ * @see headers; + protected APIService service; + protected JSONObject query = new JSONObject(); + protected Config config; + + /** + * Instantiates a new Taxonomy. + * + * @param service the service of type {@link APIService} + * @param config the config of type {@link Config} + * @param headers the headers of the {@link LinkedHashMap} + */ + protected Taxonomy(APIService service, Config config, LinkedHashMap headers) { + this.service = service; + this.headers = headers; + this.config = config; + } + + + /** + * Get all entries for a specific taxonomy that satisfy the given conditions provided in the '$in' query. + * Your query should be as follows: + *

+ *

+     * {"taxonomies.taxonomy_uid" : { "$in" : ["term_uid1" , "term_uid2" ] }}
+     * 
+ *

+ * Example: If you want to retrieve entries with the color taxonomy applied and linked to the term red and/or yellow. + *

+ *

+     * {"taxonomies.color" : { "$in" : ["red" , "yellow" ] }}
+     * 
+ * + * @param taxonomy the key of the taxonomy to query + * @param listOfItems the list of taxonomy fields + * @return an instance of the Taxonomy with the specified conditions added to the query + */ + public Taxonomy in(String taxonomy, List listOfItems) { + JSONObject innerObj = new JSONObject(); + innerObj.put("$in", listOfItems); + this.query.put(taxonomy, innerObj); + return this; + } + + + /** + * OR Operator : + *

+ * Get all entries for a specific taxonomy that satisfy at least one of the given conditions provided in the “$or” query. + *

+ * Your query should be as follows: + *

+ *

+     *
+     * { $or: [
+     * { "taxonomies.taxonomy_uid_1" : "term_uid1" },
+     * { "taxonomies.taxonomy_uid_2" : "term_uid2" }
+     * ]}
+     *
+     * 
+ * Example: If you want to retrieve entries with either the color or size taxonomy applied and linked to the terms yellow and small, respectively. + *
+ *
+     *
+     * { $or: [
+     * { "taxonomies.color" : "yellow" },
+     * { "taxonomies.size" : "small" }
+     * ]}
+     *
+     * 
+ * + * @param listOfItems the list of items + * @return instance {@link Taxonomy} + */ + public Taxonomy or(@NotNull List listOfItems) { + this.query.put("$or", listOfItems); + return this; + } + + + /** + * AND Operator : + *

+ * Get all entries for a specific taxonomy that satisfy all the conditions provided in the “$and” query. + *

+ * Your query should be as follows: + * + *

+     * {
+     * $and: [
+     * { "taxonomies.taxonomy_uid_1" : "term_uid1" },
+     * { "taxonomies.taxonomy_uid_2" : "term_uid2" }
+     * ]
+     * }
+     * 
+ * Example: If you want to retrieve entries with the color and computers taxonomies applied and linked to the terms red and laptop, respectively. + * + *
+     * {
+     * $and: [
+     * { "taxonomies.color" : "red" },
+     * { "taxonomies.computers" : "laptop" }
+     * ]
+     * }
+     * 
+ * + * @param listOfItems the list of items to that you want to include in the query string + * @return instance of the Taxonomy + */ + public Taxonomy and(@NotNull List listOfItems) { + this.query.put("$and", listOfItems.toString()); + return this; + } + + + /** + * Exists Operator : + *

+ * Get all entries for a specific taxonomy that if the value of the field, mentioned in the condition, exists. + *

+ * Your query should be as follows: + *

+     * {"taxonomies.taxonomy_uid" : { "$exists": true }}
+     * 
+ * Example: If you want to retrieve entries with the color taxonomy applied. + *
+     * {"taxonomies.color" : { "$exists": true }}
+     * 
+ * + * @param taxonomy the taxonomy + * @param value the value of the field + * @return instance of Taxonomy + */ + public Taxonomy exists(@NotNull String taxonomy, @NotNull Boolean value) { + JSONObject json = new JSONObject(); + json.put("$exists", value); + this.query.put(taxonomy, json); + return this; + } + + + /** + * Equal and Below Operator : + *

+ * Get all entries for a specific taxonomy that match a specific term and all its descendant terms, requiring only the target term and a specified level. + *

+ * Note: If you don't specify the level, the default behavior is to retrieve terms up to level 10. + * + *

{"taxonomies.taxonomy_uid" : { "$eq_below": "term_uid", "level" : 2}}
+ * + * Example: If you want to retrieve all entries with terms nested under blue, such as navy blue and sky blue, while also matching entries with the target term blue. + * + *
{"taxonomies.color" : { "$eq_below": "blue" }}
+ * + * @param taxonomy the taxonomy + * @param termsUid the term uid + * @return instance of Taxonomy + */ + public Taxonomy equalAndBelow(@NotNull String taxonomy, @NotNull String termsUid) { + JSONObject param = new JSONObject(); + param.put("$eq_below", termsUid); + this.query.put(taxonomy, param); + return this; + } + + /** + * Note: If you don't specify the level, the default behavior is to retrieve terms up to level 10. + * + * @param taxonomy the taxonomy + * @param termsUid the terms + * @param level the level to retrieve terms up to mentioned level + * @return instance of Taxonomy + */ + public Taxonomy equalAndBelowWithLevel(@NotNull String taxonomy, @NotNull String termsUid, @NotNull int level) { + JSONObject innerMap = new JSONObject(); + innerMap.put("$eq_below", termsUid + ", level: " + level); + this.query.put(taxonomy, innerMap); + return this; + } + + + /** + * Below Operator + *
+ *

+ * Get all entries for a specific taxonomy that match all of their descendant terms by specifying only the target term and a specific level. + *
+ * Note: If you don't specify the level, the default behavior is to retrieve terms up to level 10. + *
+ *

{"taxonomies.taxonomy_uid" : { "$below": "term_uid", "level" : 2}}
+ * + * Example: If you want to retrieve all entries containing terms nested under blue, such as navy blue and sky blue, but exclude entries that solely have the target term blue. + * + *
{"taxonomies.color" : { "$below": "blue" }}
+ * + * @param taxonomy the taxonomy + * @param termsUid the terms uid + * @return instance of Taxonomy + */ + public Taxonomy below(@NotNull String taxonomy, @NotNull String termsUid) { + JSONObject param = new JSONObject(); + param.put("$below", termsUid); + this.query.put(taxonomy, param); + return this; + } + + + /** + * Equal and Above Operator : + *

+ * Get all entries for a specific taxonomy that match a specific term and all its ancestor terms, requiring only the target term and a specified level. + * + * Note: If you don't specify the level, the default behavior is to retrieve terms up to level 10. + *

+ *

{"taxonomies.taxonomy_uid": { "$eq_above": "term_uid", "level": 2 }}
+ *

+ * Example: If you want to obtain all entries that include the term led and its parent term tv. + *

+ *

{"taxonomies.appliances": { "$eq_above": "led"}}
+ * + * @param taxonomy the taxonomy + * @param termUid the term uid + * @return instance of Taxonomy + */ + public Taxonomy equalAbove(@NotNull String taxonomy, @NotNull String termUid) { + JSONObject innerMap = new JSONObject(); + innerMap.put("$eq_above", termUid); + this.query.put(taxonomy, innerMap); + return this; + } + + + /** + * Above Operator : + *

+ * Get all entries for a specific taxonomy that match only the parent term(s) of a specified target term, excluding the target term itself. You can also specify a specific level. + *

+ * Note: If you don't specify the level, the default behavior is to retrieve terms up to level 10. + * + *

{ "taxonomies.taxonomy_uid": { "$above": "term_uid", "level": 2 }}
+ *

+ * Example: If you wish to match entries with the term tv but exclude the target term led. + * + *

{"taxonomies.appliances": { "$above": "led" }}
+ * + * @param taxonomy the taxonomy + * @param termUid the term uid + * @return instance of {@link Taxonomy} + */ + public Taxonomy above(@NotNull String taxonomy, @NotNull String termUid) { + JSONObject innerMap = new JSONObject(); + innerMap.put("$above", termUid); + this.query.put(taxonomy, innerMap); + return this; + } + + + /** + * To verify the payload + * + * @return instance of Call + */ + protected Call makeRequest() { + return this.service.getTaxonomy(this.headers, this.query.toString()); + } + + + /** + * Find. + * + * @param callback the callback + */ + public void find(TaxonomyCallback callback) { + try { + Response response = makeRequest().execute(); + + if (response.isSuccessful()) { + JSONObject responseJSON = new JSONObject(response.body().string()); + callback.onResponse(responseJSON, null); + } else { + JSONObject responseJSON = new JSONObject(response.errorBody().string()); + Error error = new Error(); + error.setErrorMessage(responseJSON.optString("error_message")); + error.setErrorCode(responseJSON.optInt("error_code")); + error.setErrorDetail(responseJSON.optString("errors")); + + callback.onResponse(null, error); + } + + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + +} + + diff --git a/src/main/java/com/contentstack/sdk/TaxonomyCallback.java b/src/main/java/com/contentstack/sdk/TaxonomyCallback.java new file mode 100644 index 00000000..8bf88217 --- /dev/null +++ b/src/main/java/com/contentstack/sdk/TaxonomyCallback.java @@ -0,0 +1,10 @@ +package com.contentstack.sdk; + +import okhttp3.ResponseBody; +import org.json.JSONObject; + +public interface TaxonomyCallback { + + void onResponse(JSONObject response, Error error); + +} \ No newline at end of file diff --git a/src/test/java/com/contentstack/sdk/Credentials.java b/src/test/java/com/contentstack/sdk/Credentials.java index 9b5bb2c5..4c99fcc3 100644 --- a/src/test/java/com/contentstack/sdk/Credentials.java +++ b/src/test/java/com/contentstack/sdk/Credentials.java @@ -2,9 +2,6 @@ import io.github.cdimascio.dotenv.Dotenv; import io.github.cdimascio.dotenv.DotenvException; -import lombok.var; - -import java.io.File; import java.rmi.AccessException; public class Credentials { @@ -13,19 +10,18 @@ public class Credentials { private static String envChecker() { String githubActions = System.getenv("GITHUB_ACTIONS"); if (githubActions != null && githubActions.equals("true")) { + return "GitHub"; + } else { System.out.println("Tests are running in GitHub Actions environment."); String mySecretKey = System.getenv("API_KEY"); System.out.println("My Secret Key: " + mySecretKey); return "GitHub"; } else { - System.out.println("Tests are running in a local environment."); return "local"; } } public static Dotenv getEnv() { - String currentDirectory = System.getProperty("user.dir"); - File envFile = new File(currentDirectory, "env"); env = Dotenv.configure() .directory("src/test/resources") .filename("env") // instead of '.env', use 'env' @@ -33,16 +29,7 @@ public static Dotenv getEnv() { try { env = Dotenv.load(); } catch (DotenvException ex) { - System.out.println("Could not load from local .env"); -// File envFile = new File(currentDirectory, ".env"); -// try { -// // Create .env file in the current directory -// envFile.createNewFile(); -// } catch (IOException e) { -// System.err.println("An error occurred while creating .env file."); -// e.printStackTrace(); -// } - } + ex.getLocalizedMessage(); return env; } @@ -64,8 +51,7 @@ private Credentials() throws AccessException { public static Stack getStack() { if (stack == null) { - var envCheck = envChecker(); - System.out.println(envCheck); + envChecker(); synchronized (Credentials.class) { if (stack == null) { try { diff --git a/src/test/java/com/contentstack/sdk/TaxonomyTest.java b/src/test/java/com/contentstack/sdk/TaxonomyTest.java new file mode 100644 index 00000000..126e57d9 --- /dev/null +++ b/src/test/java/com/contentstack/sdk/TaxonomyTest.java @@ -0,0 +1,136 @@ +package com.contentstack.sdk; + +import okhttp3.Request; +import okhttp3.ResponseBody; +import org.json.JSONObject; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + + +public class TaxonomyTest { + + private final Stack stack = Credentials.getStack(); + + @Test + void testInstance() { + Assertions.assertNotNull(stack); + } + + @Test + void operationIn() { + Taxonomy taxonomy = stack.taxonomy(); + List listOfItems = new ArrayList<>(); + listOfItems.add("red"); + listOfItems.add("yellow"); + Request req = taxonomy.in("taxonomies.color", listOfItems).makeRequest().request(); + //Assertions.assertEquals(3, req.headers().size()); + Assertions.assertEquals("GET", req.method()); + Assertions.assertEquals("cdn.contentstack.io", req.url().host()); + Assertions.assertEquals("/v3/taxonomies/entries", req.url().encodedPath()); + Assertions.assertEquals("query={\"taxonomies.color\":{\"$in\":[\"red\",\"yellow\"]}}", req.url().query()); + } + + + @Test + void operationOr() { + +// query={ $or: [ +// { "taxonomies.taxonomy_uid_1" : "term_uid1" }, +// { "taxonomies.taxonomy_uid_2" : "term_uid2" } +// ]} + + Taxonomy taxonomy = stack.taxonomy(); + + List listOfItems = new ArrayList<>(); + JSONObject item1 = new JSONObject(); + item1.put("taxonomies.color", "yellow"); + JSONObject item2 = new JSONObject(); + item2.put("taxonomies.size", "small"); + listOfItems.add(item1); + listOfItems.add(item2); + taxonomy.or(listOfItems); + Request req = taxonomy.makeRequest().request(); + + Assertions.assertEquals("query={\"$or\":[{\"taxonomies.color\":\"yellow\"},{\"taxonomies.size\":\"small\"}]}", req.url().query()); + + } + + @Test + void operatorAnd() { + Taxonomy taxonomy = stack.taxonomy(); + List listOfItems = new ArrayList<>(); + JSONObject items1 = new JSONObject(); + items1.put("taxonomies.color", "green"); + JSONObject items2 = new JSONObject(); + items2.put("taxonomies.computers", "laptop"); + listOfItems.add(items1); + listOfItems.add(items2); + taxonomy.and(listOfItems); + + // {$and: [{"taxonomies.color" : "green" }, { "taxonomies.computers" : "laptop" }]} + Request req = taxonomy.makeRequest().request(); + Assertions.assertEquals("query={\"$and\":\"[{\\\"taxonomies.color\\\":\\\"green\\\"}, {\\\"taxonomies.computers\\\":\\\"laptop\\\"}]\"}", req.url().query()); + } + + + @Test + void operationExists() { + // create instance of taxonomy + Taxonomy taxonomy = stack.taxonomy().exists("taxonomies.color", true); + Request req = taxonomy.makeRequest().request(); + //{"taxonomies.color" : { "$exists": true }} + //{"taxonomies.color":{"$exists":true}} + Assertions.assertEquals("query={\"taxonomies.color\":{\"$exists\":true}}", req.url().query()); + } + + + @Test + void operationEqualAndBelow() { + // create instance of taxonomy + Taxonomy taxonomy = stack.taxonomy().equalAndBelow("taxonomies.color", "blue"); + Request req = taxonomy.makeRequest().request(); + // {"taxonomies.color" : { "$eq_below": "blue" }} + Assertions.assertEquals("query={\"taxonomies.color\":{\"$eq_below\":\"blue\"}}", req.url().query()); + } + + + @Test + void operationBelowWithLevel() { + Taxonomy taxonomy = stack.taxonomy().equalAndBelowWithLevel("taxonomies.color", "blue", 3); + Request req = taxonomy.makeRequest().request(); + Assertions.assertEquals("query={\"taxonomies.color\":{\"$eq_below\":\"blue, level: 3\"}}", req.url().query()); + + } + + + @Test + void operationEqualAbove() { + Taxonomy taxonomy = stack.taxonomy().equalAbove("taxonomies.appliances", "led"); + Request req = taxonomy.makeRequest().request(); + Assertions.assertEquals("query={\"taxonomies.appliances\":{\"$eq_above\":\"led\"}}", req.url().query()); + + } + + + @Test + void above() { + Taxonomy taxonomy = stack.taxonomy().above("taxonomies.appliances", "led"); + Request req = taxonomy.makeRequest().request(); + Assertions.assertEquals("query={\"taxonomies.appliances\":{\"$above\":\"led\"}}", req.url().query()); + } + + @Test + void aboveAPI() { + Taxonomy taxonomy = stack.taxonomy().above("taxonomies.appliances", "led"); + taxonomy.find((response, error) -> { + System.out.println("Successful: " + response); + System.out.println("Error: " + error.errorMessage); + }); + //Assertions.assertEquals("query={\"taxonomies.appliances\":{\"$above\":\"led\"}}", req.url().query()); + } + + +} diff --git a/src/test/java/com/contentstack/sdk/TestAsset.java b/src/test/java/com/contentstack/sdk/TestAsset.java index 0991b583..2f77679e 100644 --- a/src/test/java/com/contentstack/sdk/TestAsset.java +++ b/src/test/java/com/contentstack/sdk/TestAsset.java @@ -14,16 +14,12 @@ class TestAsset { private String assetUid; private final Stack stack = Credentials.getStack(); - private String envChecker() { + private void envChecker() { String githubActions = System.getenv("GITHUB_ACTIONS"); if (githubActions != null && githubActions.equals("true")) { System.out.println("Tests are running in GitHub Actions environment."); - String mySecretKey = System.getenv("API_KEY"); - System.out.println("My Secret Key: " + mySecretKey); - return "GitHub"; } else { System.out.println("Tests are running in a local environment."); - return "local"; } } diff --git a/src/test/java/com/contentstack/sdk/TestContentstack.java b/src/test/java/com/contentstack/sdk/TestContentstack.java index c4c20d98..78663d1b 100644 --- a/src/test/java/com/contentstack/sdk/TestContentstack.java +++ b/src/test/java/com/contentstack/sdk/TestContentstack.java @@ -105,4 +105,29 @@ void initStackWithConfigs() throws IllegalAccessException { Assertions.assertEquals("cdn.contentstack.io", config.host); Assertions.assertNotNull(stack); } + + + @Test + void testConfigEarlyAccessSingleFeature() throws IllegalAccessException { + Config config = new Config(); + String[] earlyAccess = {"Taxonomy"}; + config.earlyAccess(earlyAccess); + Stack stack = Contentstack.stack(API_KEY, DELIVERY_TOKEN, ENV, config); + Assertions.assertEquals(earlyAccess[0], config.earlyAccess[0]); + Assertions.assertNotNull(stack.headers.containsKey("x-header-ea")); + Assertions.assertEquals("Taxonomy", stack.headers.get("x-header-ea")); + + } + + @Test + void testConfigEarlyAccessMultipleFeature() throws IllegalAccessException { + Config config = new Config(); + String[] earlyAccess = {"Taxonomy", "Teams", "Terms", "LivePreview"}; + config.earlyAccess(earlyAccess); + Stack stack = Contentstack.stack(API_KEY, DELIVERY_TOKEN, ENV, config); + Assertions.assertEquals(4, stack.headers.keySet().size()); + Assertions.assertEquals(earlyAccess[1], config.earlyAccess[1]); + Assertions.assertTrue(stack.headers.containsKey("x-header-ea")); + Assertions.assertEquals("Taxonomy,Teams,Terms,LivePreview", stack.headers.get("x-header-ea")); + } }