All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.contentstack.sdk.Entry Maven / Gradle / Ivy

There is a newer version: 2.0.1
Show newest version
package com.contentstack.sdk;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

import static com.contentstack.sdk.Constants.ENVIRONMENT;

/**
 * The Get a single
 * Entry request
 * fetches a particular entry of a content type.
 *
 * @author Shailesh Mishra
 * @version 1.0.0
 * @since 01-11-2017
 */
public class Entry {

    protected static final Logger logger = Logger.getLogger(Entry.class.getSimpleName());
    protected JSONObject params;
    protected LinkedHashMap headers = null;

    protected String uid = null;
    protected JSONObject publishDetails;
    protected JSONObject resultJson = null;
    protected String title = null;
    protected String url = null;
    protected String language = null;
    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.contentTypeUid = contentTypeName;
        this.params = new JSONObject();
    }

    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);
        this.resultJson = model.jsonObject;
        this.title = model.title;
        this.url = model.url;
        this.language = model.language;
        this.rteContent = model.rteContent;
        this.uid = model.uid;
        this.publishDetails = model.publishDetails;
        this.setTags(model.tags);
        return this;
    }

    /**
     * Set headers.
     *
     * @param key
     *         custom_header_key
     * @param value
     *         custom_header_value 
*
* Example :
* *
     *                                                                                         
*/ public void setHeader(String key, String value) { if (!key.isEmpty() && !value.isEmpty()) { this.headers.put(key, value); } } /** * Remove header key. * * @param key * custom_header_key
*
* Example :
* *
     *                                                                         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()) { this.headers.remove(key); } } /** * Get title string * * @return String @title
*
* Example :
* *
     *         String title = entry.getTitle();
     *         
*/ public String getTitle() { return title; } /** * Get url string * * @return String @url
*
* Example :
* *
     *         String url = entry.getURL();
     *         
*/ public String getURL() { return url; } /** * Get tags. * * @return String @tags
*
* Example :
* *
     *         String[] tags = entry.getURL();
     *         
*/ public String[] getTags() { return tags; } protected void setTags(String[] tags) { this.tags = tags; } /** * Get contentType name. * * @return String @contentTypeName
*
* Example :
* *
     *         String contentType = entry.getFileType();
     *         
*/ public String getContentType() { return contentTypeUid; } /** * Get uid. * * @return String @uid
*
* Example :
* *
     *         String uid = entry.getUid();
     *         
*/ public String getUid() { return uid; } protected void setUid(String uid) { this.uid = uid; } public String getLocale() { return this.language; } /** * @param locale * {@link String} * @return Entry
*
* Example :
* *
     *         Entry entry = entry.setLanguage();
     *         
*/ public Entry setLocale(@NotNull String locale) { params.put("locale", locale); return this; } /** * Get entry representation in json * * @return resultJson
*
* Example :
* *
     *         JSONObject json = entry.toJSON();
     *         
*/ public JSONObject toJSON() { return resultJson; } /** * Get object value for key. * * @param key * field_uid as key.
*
* Example :
* *
     *                                                                                                                                                                                                                                                                    Object obj = entry.get("key");
     *                                                                                                                                                                                                                                                                    
* @return Object @resultJson */ public Object get(@NotNull String key) { return resultJson.opt(key); } /** * Get string value for key. * * @param key * field_uid as key.
*
* Example :
* *
     *                                                                                                                                                                                                                                                                    String value = entry.getString("key");
     *                                                                                                                                                                                                                                                                    
* @return String @getString */ public String getString(@NotNull String key) { Object value = get(key); if (value instanceof String) { return (String) value; } return null; } /** * Get boolean value for key. * * @param key * field_uid as key.
*
* Example :
* *
     *                                                                                                                                                                                                                                                                    Boolean value = entry.getBoolean("key");
     *                                                                                                                                                                                                                                                                    
* @return boolean @getBoolean */ public Boolean getBoolean(@NotNull String key) { Object value = get(key); if (value instanceof Boolean) { return (Boolean) value; } return false; } /** * Get {@link JSONArray} value for key * * @param key * field_uid as key.
*
* Example :
* *
     *                                                                                                                                                                                                                                                                    JSONArray value = entry.getJSONArray("key");
     *                                                                                                                                                                                                                                                                    
* @return JSONArray @getJSONArray */ public JSONArray getJSONArray(@NotNull String key) { Object value = get(key); if (value instanceof JSONArray) { return (JSONArray) value; } return null; } /** * Get {@link JSONObject} value for key * * @param key * field_uid as key.
*
* Example :
* *
     *                                                                                                                                                                                                                                                                    JSONObject value = entry.getJSONObject("key");
     *                                                                                                                                                                                                                                                                    
* @return JSONObject @getJSONObject */ public JSONObject getJSONObject(@NotNull String key) { Object value = get(key); if (value instanceof JSONObject) { return (JSONObject) value; } return null; } /** * Get {@link JSONObject} value for key * * @param key * field_uid as key.
*
* Example :
* *
     *                                                                                                                                                                                                                                                                    JSONObject value = entry.getJSONObject("key");
     *                                                                                                                                                                                                                                                                    
* @return Number @getNumber */ public Number getNumber(@NotNull String key) { Object value = get(key); if (value instanceof Number) { return (Number) value; } return null; } /** * Get integer value for key * * @param key * field_uid as key.
*
* Example :
* *
     *                                                                                                                                                                                                                                                                    int value = entry.getInt("key");
     *                                                                                                                                                                                                                                                                    
* @return int @getInt */ public int getInt(@NotNull String key) { Object value = getNumber(key); if (value instanceof Integer) { return (Integer) value; } return 0; } /** * Get integer value for key * * @param key * field_uid as key. * @return float @getFloat
*
* Example :
* *
     *         float value = entry.getFloat("key");
     *         
*/ public float getFloat(@NotNull String key) { Object value = getNumber(key); if (value instanceof Float) { return (Float) value; } return 0; } /** * Get double value for key * * @param key * field_uid as key. * @return double @getDouble
*
* Example :
* *
     *         double value = entry.getDouble("key");
     *         
*/ public double getDouble(@NotNull String key) { Number value = getNumber(key); if (value != null) { return value.doubleValue(); } return 0; } /** * Get long value for key * * @param key * field_uid as key.
*
* Example :
* *
     *                                                                                 long value = entry.getLong("key");
     *                                                                                 
* @return long @getLong */ public long getLong(@NotNull String key) { Number value = getNumber(key); if (value != null) { return value.longValue(); } return 0; } /** * Get short value for key * * @param key * field_uid as key. * *
*
* Example :
* *
     *                                                                                                                                                                                                                                                                    short value = entry.getShort("key");
     *                                                                                                                                                                                                                                                                    
* @return short @getShort */ public short getShort(@NotNull String key) { Number value = getNumber(key); if (value != null) { return value.shortValue(); } return (short) 0; } /** * Get {@link Calendar} value for key * * @param key * field_uid as key.
*
* Example :
* *
     *                                                                                                                                                                                                                                                                    Calendar value = entry.getDate("key");
     *                                                                                                                                                                                                                                                                    
* @return Calendar @getDate */ public Calendar getDate(@NotNull String key) { try { String value = getString(key); return Constants.parseDate(value, null); } catch (Exception e) { logger.log(Level.SEVERE, e.getLocalizedMessage(), e); } return null; } /** * Get {@link Calendar} value of creation time of entry. * * @return Calendar @getCreateAt
*
* Example :
* *
     *         Calendar createdAt = entry.getCreateAt("key");
     *         
*/ public Calendar getCreateAt() { try { String value = getString("created_at"); return Constants.parseDate(value, null); } catch (Exception e) { logger.log(Level.SEVERE, e.getLocalizedMessage(), e); } return null; } /** * Get uid who created this entry. * * @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");
     *         
*/ public Calendar getUpdateAt() { try { String value = getString("updated_at"); return Constants.parseDate(value, null); } catch (Exception e) { logger.log(Level.SEVERE, e.getLocalizedMessage(), e); } return null; } /** * Get uid who updated this entry. * * @return String @getString
*
* Example :
* *
     *         String updatedBy_uid = entry.getUpdatedBy();
     *         
*/ public String getUpdatedBy() { return getString("updated_by"); } /** * Get {@link Calendar} value of deletion time of entry. * * @return Calendar * *
*
* Example :
* *
     *         Calendar updatedAt = entry.getUpdateAt("key");
     *         
*/ public Calendar getDeleteAt() { try { String value = getString("deleted_at"); return Constants.parseDate(value, null); } catch (Exception e) { logger.log(Level.SEVERE, e.getLocalizedMessage(), e); } return null; } /** * Get uid who deleted this entry. * * @return String
*
* Example :
* *
     *         String deletedBy_uid = entry.getDeletedBy();
     *         
*/ public String getDeletedBy() { return getString("deleted_by"); } /** * Get an asset from the entry * * @param key * field_uid as key. * @return Asset
*
* Example :
* *
     *         Asset asset = entry.getAsset("key");
     *         
*/ public Asset getAsset(String key) { JSONObject assetObject = getJSONObject(key); return contentType.stackInstance.asset().configure(assetObject); } /** * Get an assets from the entry. This works with multiple true fields
*
* Example :
* *
     * {
     *     @code
     *     List asset = entry.getAssets("key");
     * }
     * 
* * @param key * This is the String key * @return ArrayList This returns list of Assets. */ public List getAssets(String key) { List assets = new ArrayList<>(); JSONArray assetArray = getJSONArray(key); assetArray.forEach(model -> { if (model instanceof JSONObject) { JSONObject newModel = (JSONObject) model; Asset asset = contentType.stackInstance.asset().configure(newModel); assets.add(asset); } }); return assets; } /** * @param key * field_uid as key.
*
* Example :
* *
     *                                                                                                                                                                                                                                                                     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(contentType.stackInstance, resultJson.optJSONObject(key)); } return null; } /** * Get a list of group from entry. *

* 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");
     *         
*/ 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); array.forEach(model -> { JSONObject groupModel = (JSONObject) model; Group group = new Group(contentType.stackInstance, groupModel); groupList.add(group); }); } return groupList; } /** * Get value for the given reference 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 :
* *
     *          {@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){ * List<Entry> list = queryResult.getResultObjects(); * for (int i = 0; i < list.queueSize(); i++) { * Entry entry = list.get(i); * Entry taskEntry = entry.getAllEntries("for_task", "task"); * } * } * } * }); * }
*
*/ public List getAllEntries(String refKey, String refContentType) { 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.log(Level.SEVERE, e.getLocalizedMessage(), e); } entryInstance.setUid(model.uid); entryInstance.resultJson = model.jsonObject; entryInstance.setTags(model.tags); entryContainer.add(entryInstance); }); } } return entryContainer; } /** * Specifies list of field ids that would be 'excluded' from the response. * * @param fieldUid * field uid which get 'excluded' from the response. */ public Entry except(@NotNull String[] fieldUid) { if (fieldUid.length > 0) { if (exceptFieldArray == null) { exceptFieldArray = new JSONArray(); } for (String s : fieldUid) { exceptFieldArray.put(s); } } return this; } /** * Add a constraint that requires a particular reference key details. * * @param referenceField * key that to be constrained. */ public Entry includeReference(@NotNull String referenceField) { if (!referenceField.isEmpty()) { if (referenceArray == null) { referenceArray = new JSONArray(); } referenceArray.put(referenceField); params.put("include[]", referenceArray); } return this; } /** * Add a constraint that requires a particular reference key details. * * @param referenceFields * array key that to be constrained. */ public Entry includeReference(@NotNull String[] referenceFields) { if (referenceFields.length > 0) { if (referenceArray == null) { referenceArray = new JSONArray(); } 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. * * @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) { if (fieldUid != null && fieldUid.length > 0) { if (objectUidForOnly == null) { objectUidForOnly = new JSONArray(); } for (String field : fieldUid) { objectUidForOnly.put(field); } } return this; } /** * 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. */ public Entry onlyWithReferenceUid(@NotNull List fieldUid, @NotNull String referenceFieldUid) { if (onlyJsonObject == null) { onlyJsonObject = new JSONObject(); } JSONArray fieldValueArray = new JSONArray(); fieldUid.forEach(fieldValueArray::put); onlyJsonObject.put(referenceFieldUid, fieldValueArray); includeReference(referenceFieldUid); return this; } /** * 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. */ public Entry exceptWithReferenceUid(@NotNull List fieldUid, @NotNull String referenceFieldUid) { if (exceptJsonObject == null) { exceptJsonObject = new JSONObject(); } JSONArray fieldValueArray = new JSONArray(); fieldUid.forEach(fieldValueArray::put); 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 :
* *
     *                        {@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) { if (uid.isEmpty()) { // throws IllegalAccessException if uid is Empty try { throw new IllegalAccessException("Entry Uid is required"); } catch (IllegalAccessException e) { logger.log(Level.SEVERE, e.getLocalizedMessage(), e); } } String urlString = "content_types/" + contentTypeUid + "/entries/" + uid; JSONObject urlQueries = new JSONObject(); urlQueries.put(ENVIRONMENT, headers.get(ENVIRONMENT)); fetchFromNetwork(urlString, urlQueries, callback); } private void fetchFromNetwork(String urlString, JSONObject urlQueries, EntryResultCallBack callBack) { JSONObject mainJson = new JSONObject(); setIncludeJSON(urlQueries, callBack); mainJson.put("query", urlQueries); HashMap urlParams = getUrlParams(mainJson); new CSBackgroundTask(this, contentType.stackInstance, Constants.FETCHENTRY, urlString, this.headers, urlParams, Constants.REQUEST_CONTROLLER.ENTRY.toString(), callBack); } private LinkedHashMap getUrlParams(JSONObject jsonMain) { JSONObject queryJSON = jsonMain.optJSONObject("query"); LinkedHashMap hashMap = new LinkedHashMap<>(); if (queryJSON != null && queryJSON.length() > 0) { Iterator itr = queryJSON.keys(); while (itr.hasNext()) { String key = itr.next(); Object value = queryJSON.opt(key); hashMap.put(key, value); } } return hashMap; } private void setIncludeJSON(JSONObject mainJson, ResultCallBack callBack) { try { Iterator iterator = params.keys(); while (iterator.hasNext()) { String key = iterator.next(); Object value = params.get(key); mainJson.put(key, value); } if (objectUidForOnly != null && objectUidForOnly.length() > 0) { mainJson.put("only[BASE][]", objectUidForOnly); objectUidForOnly = 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; } } catch (Exception e) { throwException(null, e, (EntryResultCallBack) callBack); } } private void throwException(@Nullable 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); } /** * This method adds key and value to an Entry. * * @param key * The key as string which needs to be added to an Entry * @param value * The value as string which needs to be added to an Entry * @return {@link Entry} * *
*
* 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(@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 */ public Entry includeReferenceContentTypeUID() { params.put("include_reference_content_type_uid", "true"); return this; } /** * Include Content Type of all returned objects along with objects themselves. */ public Entry includeContentType() { 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 * * @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() { params.put("include_fallback", true); return this; } /** * includeEmbeddedItems instance of Entry Include Embedded Objects (Entries and Assets) along with entry/entries * details.
*/ public Entry includeEmbeddedItems() { 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; } /** * Includes Metadata 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.includeMetadata();
     *         
*/ public Entry includeMetadata() { params.put("include_metadata", true); return this; } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy