Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 17 additions & 8 deletions src/main/java/com/contentstack/sdk/AssetLibrary.java
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,11 @@ public AssetLibrary addParam(@NotNull String paramKey, @NotNull Object paramValu
if (isValidKey(paramKey) && isValidValue(paramValue)) {
urlQueries.put(paramKey, paramValue);
} else {
logger.warning("Invalid key or value");
if (!isValidKey(paramKey)) {
logger.warning(ErrorMessages.INVALID_PARAMETER_KEY);
} else {
logger.warning(ErrorMessages.INVALID_PARAMETER_VALUE);
}
}
return this;
}
Expand Down Expand Up @@ -310,9 +314,10 @@ public void getResultObject(List<Object> objects, JSONObject jsonObject, boolean

List<Asset> assets = new ArrayList<>();

// if (objects == null || objects.isEmpty()) {
// System.out.println("Objects list is null or empty");
// }
if (objects == null || objects.isEmpty()) {
logger.warning(ErrorMessages.MISSING_ASSETS_LIST);
return;
}

if (objects != null && !objects.isEmpty()) {
for (Object object : objects) {
Expand All @@ -328,9 +333,9 @@ public void getResultObject(List<Object> objects, JSONObject jsonObject, boolean
assets.add(asset);
}
}
// else {
// System.out.println("Object is not an instance of AssetModel");
// }
else {
logger.warning(ErrorMessages.INVALID_OBJECT_TYPE_ASSET_MODEL);
}

if (callback != null) {
callback.onRequestFinish(ResponseType.NETWORK, assets);
Expand All @@ -351,7 +356,11 @@ public AssetLibrary where(String key, String value) {
queryParams.put(key,value);
urlQueries.put("query", queryParams);
} else {
throw new IllegalArgumentException("Invalid key or value");
if (!isValidKey(key)) {
throw new IllegalArgumentException(ErrorMessages.INVALID_PARAMETER_KEY);
} else {
throw new IllegalArgumentException(ErrorMessages.INVALID_PARAMETER_VALUE);
}
}
return this;
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/contentstack/sdk/AssetsModel.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public AssetsModel(JSONObject response) {
List<?> assetsList = (List<?>) rawAssets;
listResponse = new JSONArray(assetsList); // Convert to JSONArray
} else if (rawAssets != null) {
throw new IllegalArgumentException("Invalid type for 'assets' key: " + rawAssets.getClass().getName());
throw new IllegalArgumentException(ErrorMessages.INVALID_ASSETS_TYPE);
}
if (listResponse != null) {
listResponse.forEach(model -> {
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/contentstack/sdk/CSBackgroundTask.java
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ protected void checkHeader(@NotNull Map<String, Object> headers) {
final Logger logger = Logger.getLogger("CSBackgroundTask");
if (headers.size() == 0) {
try {
throw new IllegalAccessException("CSBackgroundTask Header Exception");
throw new IllegalAccessException(ErrorMessages.MISSING_REQUEST_HEADERS);
} catch (IllegalAccessException e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/com/contentstack/sdk/CSHttpConnection.java
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ private String getParams(HashMap<String, Object> params) {
urlParams += urlParams.equals("?") ? key + "=" + value : "&" + key + "=" + value;
}
} catch (Exception e1) {
logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1);
logger.log(Level.SEVERE, ErrorMessages.URL_PARAMETER_ENCODING_FAILED, e1);
}
}
return urlParams;
Expand Down Expand Up @@ -187,7 +187,7 @@ public void send() {
try {
getService(url);
} catch (IOException | JSONException e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
logger.log(Level.SEVERE, ErrorMessages.URL_PARAMETER_ENCODING_FAILED, e);
}
}

Expand Down Expand Up @@ -238,7 +238,7 @@ private void getService(String requestUrl) throws IOException {
connectionRequest.onRequestFinished(CSHttpConnection.this);
} catch (JSONException e) {
// Handle non-JSON response
setError("Invalid JSON response");
setError(ErrorMessages.INVALID_JSON_RESPONSE);
}
} else {
assert response.errorBody() != null;
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/contentstack/sdk/ContentType.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public class ContentType {
public JSONObject contentTypeData;

protected ContentType() throws IllegalAccessException {
throw new IllegalAccessException("Can Not Access Private Modifier");
throw new IllegalAccessException(ErrorMessages.DIRECT_INSTANTIATION_CONTENT_TYPE);
}

protected ContentType(String contentTypeUid) {
Expand Down Expand Up @@ -158,7 +158,7 @@ public void fetch(@NotNull JSONObject params, final ContentTypesCallback callbac
}
params.put("environment", headers.get("environment"));
if (contentTypeUid == null || contentTypeUid.isEmpty()) {
throw new IllegalAccessException("contentTypeUid is required");
throw new IllegalAccessException(ErrorMessages.CONTENT_TYPE_UID_REQUIRED);
}
fetchContentTypes(urlString, params, headers, callback);
}
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/com/contentstack/sdk/ContentTypesModel.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public void setJSON(JSONObject responseJSON) {
try {
this.response = new JSONObject((LinkedHashMap<?, ?>) responseJSON.get(ctKey));
} catch (Exception e) {
System.err.println("Error processing 'content_type': " + e.getMessage());
System.err.println(ErrorMessages.INVALID_CONTENT_TYPE_DATA + " Technical details: " + e.getMessage());
}
}
String ctListKey = "content_types";
Expand All @@ -44,14 +44,14 @@ public void setJSON(JSONObject responseJSON) {
JSONObject jsonModel = new JSONObject((LinkedHashMap<?, ?>) model);
objectList.add(jsonModel);
} else {
System.err.println("Invalid type in 'content_types' list. Expected LinkedHashMap.");
System.err.println(ErrorMessages.INVALID_CONTENT_TYPES_LIST);
}
});
}
this.response = new JSONArray(objectList);
this.responseJSONArray = new JSONArray(objectList);
} catch (Exception e) {
System.err.println("Error processing 'content_types': " + e.getMessage());
System.err.println(ErrorMessages.INVALID_CONTENT_TYPE_DATA + " Technical details: " + e.getMessage());
}
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/main/java/com/contentstack/sdk/Contentstack.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class Contentstack {

// Modifier Protected
protected Contentstack() throws IllegalAccessException {
throw new IllegalAccessException("Can Not Access Private Modifier");
throw new IllegalAccessException(ErrorMessages.DIRECT_INSTANTIATION_CONTENTSTACK);
}

/**
Expand Down Expand Up @@ -88,13 +88,13 @@ private static void validateCredentials(String stackApiKey, String deliveryToken
Objects.requireNonNull(environment, "Environment can not be null");

if (stackApiKey.isEmpty()) {
throw new IllegalAccessException("API Key can not be empty");
throw new IllegalAccessException(ErrorMessages.MISSING_API_KEY);
}
if (deliveryToken.isEmpty()) {
throw new IllegalAccessException("Delivery Token can not be empty");
throw new IllegalAccessException(ErrorMessages.MISSING_DELIVERY_TOKEN);
}
if (environment.isEmpty()) {
throw new IllegalAccessException("Environment can not be empty");
throw new IllegalAccessException(ErrorMessages.MISSING_ENVIRONMENT);
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/contentstack/sdk/EntriesModel.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ protected EntriesModel(JSONObject responseJSON) {
}
} catch (Exception e) {
Logger logger = Logger.getLogger(EntriesModel.class.getSimpleName());
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
logger.log(Level.SEVERE, ErrorMessages.ENTRIES_PROCESSING_FAILED, e);
}

}
Expand Down
16 changes: 8 additions & 8 deletions src/main/java/com/contentstack/sdk/Entry.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public class Entry {
protected String rteContent = null;

protected Entry() throws IllegalAccessException {
throw new IllegalAccessException("Can Not Access Private Modifier");
throw new IllegalAccessException(ErrorMessages.DIRECT_INSTANTIATION_ENTRY);
}

protected Entry(String contentTypeName) {
Expand Down Expand Up @@ -503,7 +503,7 @@ public Calendar getDate(@NotNull String key) {
String value = getString(key);
return Constants.parseDate(value, null);
} catch (Exception e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
logger.log(Level.SEVERE, ErrorMessages.INVALID_DATE_FORMAT, e);
}
return null;
}
Expand All @@ -525,7 +525,7 @@ public Calendar getCreateAt() {
String value = getString("created_at");
return Constants.parseDate(value, null);
} catch (Exception e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
logger.log(Level.SEVERE, ErrorMessages.INVALID_DATE_FORMAT, e);
}
return null;
}
Expand Down Expand Up @@ -562,7 +562,7 @@ public Calendar getUpdateAt() {
String value = getString("updated_at");
return Constants.parseDate(value, null);
} catch (Exception e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
logger.log(Level.SEVERE, ErrorMessages.INVALID_DATE_FORMAT, e);
}
return null;
}
Expand Down Expand Up @@ -601,7 +601,7 @@ public Calendar getDeleteAt() {
String value = getString("deleted_at");
return Constants.parseDate(value, null);
} catch (Exception e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
logger.log(Level.SEVERE, ErrorMessages.INVALID_DATE_FORMAT, e);
}
return null;
}
Expand Down Expand Up @@ -764,7 +764,7 @@ public List<Entry> getAllEntries(String refKey, String refContentType) {
entryInstance = contentType.stackInstance.contentType(refContentType).entry();
} catch (Exception e) {
entryInstance = new Entry(refContentType);
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
logger.log(Level.SEVERE, ErrorMessages.INVALID_DATE_FORMAT, e);
}
entryInstance.setUid(model.uid);
entryInstance.resultJson = model.jsonObject;
Expand Down Expand Up @@ -928,9 +928,9 @@ public Entry exceptWithReferenceUid(@NotNull List<String> fieldUid, @NotNull Str
public void fetch(EntryResultCallBack callback) {
if (uid.isEmpty()) { // throws IllegalAccessException if uid is Empty
try {
throw new IllegalAccessException("Entry Uid is required");
throw new IllegalAccessException(ErrorMessages.ENTRY_UID_REQUIRED);
} catch (IllegalAccessException e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
logger.log(Level.SEVERE, ErrorMessages.ENTRY_FETCH_FAILED, e);
}
}
String urlString = "content_types/" + contentTypeUid + "/entries/" + uid;
Expand Down
76 changes: 76 additions & 0 deletions src/main/java/com/contentstack/sdk/ErrorMessages.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package com.contentstack.sdk;

/**
* Centralized error messages for the Contentstack SDK.
* This class contains all user-facing error messages to ensure consistency
* and make maintenance easier.
*/
public final class ErrorMessages {

// Prevent instantiation
private ErrorMessages() {
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
}

// ========== AUTHENTICATION & ACCESS ERRORS ==========

public static final String MISSING_API_KEY = "Missing API key. Provide a valid key from your Contentstack stack settings and try again.";
public static final String MISSING_DELIVERY_TOKEN = "Missing delivery token. Provide a valid token from your Contentstack stack settings and try again.";
public static final String MISSING_ENVIRONMENT = "Missing environment. Provide a valid environment name and try again.";
public static final String MISSING_REQUEST_HEADERS = "Missing request headers. Provide api_key, access_token, and environment, then try again.";

// ========== DIRECT INSTANTIATION ERRORS ==========

public static final String DIRECT_INSTANTIATION_STACK = "Direct instantiation of Stack is not allowed. Use Contentstack.stack() to create an instance.";
public static final String DIRECT_INSTANTIATION_CONTENTSTACK = "Direct instantiation of Stack is not allowed. Use Contentstack.stack() to create an instance.";
public static final String DIRECT_INSTANTIATION_CONTENT_TYPE = "Direct instantiation of ContentType is not allowed. Use Stack.contentType(uid) to create an instance.";
public static final String DIRECT_INSTANTIATION_ENTRY = "Direct instantiation of Entry is not allowed. Use ContentType.entry(uid) to create an instance.";

// ========== REQUIRED FIELD ERRORS ==========

public static final String CONTENT_TYPE_UID_REQUIRED = "Content type UID is required. Provide a valid UID and try again.";
public static final String ENTRY_UID_REQUIRED = "Missing entry UID. Provide a valid UID and try again.";
public static final String GLOBAL_FIELD_UID_REQUIRED = "Missing global field UID. Provide a valid UID and try again.";

// ========== DATA VALIDATION ERRORS ==========

public static final String INVALID_PARAMETER_KEY = "Invalid parameter key. Use only alphanumeric characters, underscores, and dots.";
public static final String INVALID_PARAMETER_VALUE = "Invalid parameter value. Remove unsupported characters and try again.";
public static final String INVALID_QUERY_URL = "Invalid query URL. Use a valid URL and try again.";
public static final String INVALID_DATE_FORMAT = "Invalid date format for field. Provide the date in ISO format and try again.";

// ========== DATA TYPE ERRORS ==========

public static final String INVALID_ASSETS_TYPE = "Invalid type for 'assets' key. Provide assets as a List or ArrayList and try again.";
public static final String INVALID_OBJECT_TYPE_ASSET_MODEL = "Invalid object type. Use an AssetModel object and try again.";
public static final String INVALID_CONTENT_TYPE_DATA = "Invalid content type data. Provide a LinkedHashMap structure and try again.";
public static final String INVALID_CONTENT_TYPES_LIST = "Invalid type in content types list. Use a LinkedHashMap and try again.";
public static final String INVALID_GLOBAL_FIELD_DATA = "Invalid global field data. Provide a LinkedHashMap structure and try again.";
public static final String INVALID_GLOBAL_FIELDS_LIST = "Invalid type in global fields list. Use a LinkedHashMap and try again.";

// ========== MISSING DATA ERRORS ==========

public static final String MISSING_ASSETS_LIST = "Missing assets list. Provide a valid list of assets and try again.";
public static final String MISSING_JSON_OBJECT_SYNC = "Missing JSON object for sync operation. Provide a valid JSON object with sync parameters and try again.";

// ========== NETWORK & CONNECTION ERRORS ==========

public static final String URL_PARAMETER_ENCODING_FAILED = "URL parameter encoding failed. Provide a valid key and value, then try again.";
public static final String LIVE_PREVIEW_URL_FAILED = "Failed to execute the Live Preview URL. Check your connection and try again.";
public static final String TAXONOMY_QUERY_FAILED = "Failed to execute taxonomy query. Check your network connection and verify taxonomy parameters.";
public static final String INVALID_JSON_RESPONSE = "Invalid JSON response. Check the server response format and try again.";

// ========== CONFIGURATION ERRORS ==========

public static final String MISSING_PREVIEW_TOKEN = "Missing preview token for rest-preview.contentstack.com. Set the preview token in your configuration to use Live Preview.";
public static final String LIVE_PREVIEW_NOT_ENABLED = "Live Preview is not enabled in the configuration. Enable it and try again.";
public static final String EMBEDDED_ITEMS_NOT_INCLUDED = "Embedded items are not included in the entry. Call includeEmbeddedItems() and try again.";

// ========== OPERATION ERRORS ==========

public static final String ENTRY_FETCH_FAILED = "Entry fetch operation failed due to missing UID. Provide a valid UID and try again.";
public static final String QUERY_EXECUTION_FAILED = "Query execution failed. Check the query and try again.";
public static final String ENTRIES_PROCESSING_FAILED = "Failed to process entries data. Check the entries format and try again.";
public static final String GROUP_DATE_PARSING_FAILED = "Failed to parse date from group field. Provide a valid date format and try again.";
public static final String QUERY_RESULT_PROCESSING_FAILED = "Failed to process query result data. Check the response format and try again.";
}
2 changes: 1 addition & 1 deletion src/main/java/com/contentstack/sdk/GlobalField.java
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public GlobalField includeGlobalFieldSchema() {
public void fetch(final GlobalFieldsCallback callback) throws IllegalAccessException {
String urlString = "global_fields/" + globalFieldUid;
if (globalFieldUid == null || globalFieldUid.isEmpty()) {
throw new IllegalAccessException("globalFieldUid is required");
throw new IllegalAccessException(ErrorMessages.GLOBAL_FIELD_UID_REQUIRED);
}
fetchGlobalFields(urlString, this.params, this.headers, callback);
}
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/com/contentstack/sdk/GlobalFieldsModel.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public void setJSON(JSONObject responseJSON) {
try {
this.response = new JSONObject((LinkedHashMap<?, ?>) responseJSON.get(gfKey));
} catch (Exception e) {
System.err.println("Error processing 'global_field': " + e.getMessage());
System.err.println(ErrorMessages.INVALID_GLOBAL_FIELD_DATA + " Technical details: " + e.getMessage());
}
}
String gfListKey = "global_fields";
Expand All @@ -36,14 +36,14 @@ public void setJSON(JSONObject responseJSON) {
JSONObject jsonModel = new JSONObject((LinkedHashMap<?, ?>) model);
objectList.add(jsonModel);
} else {
System.err.println("Invalid type in 'global_fields' list. Expected LinkedHashMap.");
System.err.println(ErrorMessages.INVALID_GLOBAL_FIELDS_LIST);
}
});
}
this.response = new JSONArray(objectList);
this.responseJSONArray = new JSONArray(objectList);
} catch (Exception e) {
System.err.println("Error processing 'global_fields': " + e.getMessage());
System.err.println(ErrorMessages.INVALID_GLOBAL_FIELD_DATA + " Technical details: " + e.getMessage());
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/contentstack/sdk/Group.java
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ public Calendar getDate(String key) {
String value = getString(key);
return Constants.parseDate(value, null);
} catch (Exception e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
logger.log(Level.SEVERE, ErrorMessages.GROUP_DATE_PARSING_FAILED, e);
}
return null;
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/contentstack/sdk/Query.java
Original file line number Diff line number Diff line change
Expand Up @@ -1235,7 +1235,7 @@ private void throwException(String queryName, String messageString, @Nullable Ex
}
errorHashMap.put("detail", messageString);
assert e != null;
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
logger.log(Level.SEVERE, ErrorMessages.QUERY_EXECUTION_FAILED, e);
}

protected void setQueryJson() {
Expand Down
Loading
Loading