com.contentstack.sdk.Asset Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java Show documentation
Show all versions of java Show documentation
Java SDK for Contentstack Content Delivery API
package com.contentstack.sdk;
import com.contentstack.sdk.utility.CSAppConstants;
import com.contentstack.sdk.utility.CSController;
import com.contentstack.sdk.utility.ContentstackUtil;
import org.json.JSONObject;
import java.util.*;
/**
* MIT License
*
* Copyright (c) 2012 - 2019 Contentstack
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
public class Asset {
protected String assetUid = null;
protected String contentType = null;
protected String fileSize = null;
protected String fileName = null;
protected String uploadUrl = null;
protected JSONObject json = null;
protected String[] tagsArray = null;
protected LinkedHashMap headerGroup_app;
protected LinkedHashMap headerGroup_local;
protected com.contentstack.sdk.Stack stackInstance;
protected Asset(){
this.headerGroup_local = new LinkedHashMap<>();
this.headerGroup_app = new LinkedHashMap<>();
}
protected Asset(String assetUid){
this.assetUid = assetUid;
this.headerGroup_local = new LinkedHashMap<>();
this.headerGroup_app = new LinkedHashMap<>();
}
protected void setStackInstance(Stack stack) {
this.stackInstance = stack;
this.headerGroup_app = stack.localHeader;
}
/**
* Creates new instance of {@link Asset} from valid {@link JSONObject}.
* If JSON object is not appropriate then it will return null.
* @param jsonObject json object of particular file attached in the built object.
* {@link Asset} can be generate using of data filled {@link Entry}
* and
* {@link #configure(JSONObject)}.
*
*
Example :
*
1. Single Attachment :-
*
* //'blt5d4sample2633b' is a dummy Application API key
* Stack stack = Contentstack.stack(context, "blt5d4sample2633b", "bltdtsample_accessToken767vv", config);
* Asset assetObject = stack.asset("assetUid");
* assetObject.configure(entryObject.getJSONObject(attached_image_field_uid));
*
*
2. Multiple Attachment :-
*
* JSONArray array = entryObject.getJSONArray(Attach_Image_Field_Uid);
*
{@code for (int i = 0; i < array.length(); i++)} {
* Asset assetObject = stack.asset("assetUid");
* assetObject.configure(entryObject.getJSONObject(attached_image_field_uid));
* }
*
* @return {@link Asset} instance.
*/
public Asset configure(JSONObject jsonObject){
AssetModel model = null;
model = new AssetModel(jsonObject, true, false);
this.contentType = model.contentType;
this.fileSize = model.fileSize;
this.uploadUrl = model.uploadUrl;
this.fileName = model.fileName;
this.json = model.json;
this.assetUid = model.uploadedUid;
this.setTags(model.tags);
model = null;
return this;
}
protected Asset setTags(String[] tags){
tagsArray = tags;
return this;
}
/**
* To set headers for Contentstack rest calls.
*
* Scope is limited to this object only.
* @param key header name.
* @param value header value against given header name.
*
Example :
*
* //'blt5d4sample2633b' is a dummy Application API key
* Asset assetObject = Contentstack.stack(context, "blt5d4sample2633b", "bltdtsample_accessToken767vv", config).asset("assetUid");
* assetObject.setHeader("custom_header_key", "custom_header_value");
*
*/
public void setHeader(String key, String value){
if(!key.isEmpty() && !value.isEmpty()){
removeHeader(key);
headerGroup_local.put(key, value);
}
}
/**
* Remove a header for a given key from headers.
*
* Scope is limited to this object only
* @param key header key.
*
Example :
*
* //'blt5d4sample2633b' is a dummy Application API key
* Asset assetObject = Contentstack.stack(context, "blt5d4sample2633b", "bltdtsample_accessToken767vv", config).asset("assetUid");
* assetObject.removeHeader("custom_header_key");
*
*/
public void removeHeader(String key){
if(headerGroup_local != null){
if(!key.isEmpty()){
if(headerGroup_local.containsKey(key)){
headerGroup_local.remove(key);
}
}
}
}
/**
* To set uid of media file which is uploaded on Contentstack server.
* @param assetUid
* upload uid.
*
Example :
*
* //'blt5d4sample2633b' is a dummy Application API key
* Asset assetObject = Contentstack.stack(context, "blt5d4sample2633b", "bltdtsample_accessToken767vv", config).asset("assetUid");
* assetObject.setUid("upload_uid");
*
*
*/
protected void setUid(String assetUid) {
if(!assetUid.isEmpty()){
this.assetUid = assetUid;
}
}
/**
*
* @return String @assetUid
*
Example :
*
* String uid = assetObject.getAssetUid();
* return String of @uid
*
*/
public String getAssetUid() {
return assetUid;
}
/**
* @return String @contentType
*
Example :
*
* String contentType = assetObject.getFileType();
*
*/
public String getFileType() {
return contentType;
}
/**
*
* @return String @fileSize
*
Note :
file size will receive in bytes number.
*
Example :
*
* String queueSize = assetObject.getFileSize();
*
*/
public String getFileSize(){
return fileSize;
}
/**
* @return String @fileName
*
Example :
*
* String fileName = assetObject.getFileName();
*
*
*/
public String getFileName(){
return fileName;
}
/**
* @return String @uploadUrl by which you can download media file uploaded on Contentstack server.
* You will get uploaded url after uploading media file on Contentstack server.
*
Example :
*
* String url = assetObject.getUrl();
*
*
*/
public String getUrl(){
return uploadUrl;
}
/**
*
* @return JSON @json representation of this {@link Asset} instance data.
*
Example :
*
* JSONObject json = assetObject.toJSON();
*
*
*/
public JSONObject toJSON() {
return json;
}
/**
* @return Calendar @{@link java.util.Date}
* Get {@link Calendar} value of creation time of entry.
*
Example :
*
* Calendar createdAt = assetObject.getCreateAt("key");
*
*/
public Calendar getCreateAt(){
try {
String value = json.optString("created_at");
return ContentstackUtil.parseDate(value, null);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String getCreatedBy(){
return json.optString("created_by");
}
/**
* Get {@link Calendar} value of updating time of entry.
* @return Calendar @{@link java.util.Date}
*
Example :
*
* Calendar updatedAt = assetObject.getUpdateAt("key");
*
*/
public Calendar getUpdateAt(){
try {
String value = json.optString("updated_at");
return ContentstackUtil.parseDate(value, null);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Get uid who updated this entry.
* @return String @getUpdatedBy
*
Example :
*
* String updatedBy_uid = assetObject.getUpdatedBy();
*
*/
public String getUpdatedBy(){
return json.optString("updated_by");
}
/**
* Get {@link Calendar} value of deletion time of entry
* @return Calendar @{@link java.util.Date}
*
*
Example :
*
* Calendar updatedAt = entry.getUpdateAt("key");
*
*/
public Calendar getDeleteAt(){
try {
String value = json.optString("deleted_at");
return ContentstackUtil.parseDate(value, null);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Get uid who deleted this entry.
*
* @return String @getDeletedBy
*
Example :
*
* String deletedBy_uid = assetObject.getDeletedBy();
*
*/
public String getDeletedBy(){
return json.optString("deleted_by");
}
/**
* Get tags.
* @return String @tagsArray
*
Example :
*
* String[] tags = assetObject.getURL();
*
*/
public String[] getTags() {
return tagsArray;
}
/**
* Fetch a particular asset using uid.
* @param callback
* {@link FetchResultCallback} instance for success and failure result.
*
Example :
*
* Asset asset = stack.asset("blt5312f71416d6e2c8");
* asset.fetch(new FetchResultCallback() {
* @Override
* public void onCompletion(ResponseType responseType, Error error) {
* if(error == null){
* //Success Block.
* }else {
* //Fail Block.
* }
* }
* });
*
*/
public void fetch(FetchResultCallback callback){
try {
String URL = "/" + stackInstance.VERSION + "/assets/" + assetUid;
LinkedHashMap headers = getHeader(headerGroup_local);
JSONObject urlQueries = new JSONObject();
if (headers.containsKey("environment")) {
urlQueries.put("environment", headers.get("environment"));
}
fetchFromNetwork(URL, urlQueries, headers, callback);
}catch (Exception e){
Error error = new Error();
error.setErrorMessage(CSAppConstants.ErrorMessage_JsonNotProper);
callback.onRequestFail(ResponseType.UNKNOWN, error);
}
}
private void fetchFromNetwork(String URL, JSONObject urlQueries, LinkedHashMap headers, FetchResultCallback callback) {
if(callback != null) {
HashMap urlParams = getUrlParams(urlQueries);
new CSBackgroundTask(this, stackInstance, CSController.FETCHASSETS, URL, headers, urlParams, new JSONObject(), CSAppConstants.callController.ASSET.toString(), false, CSAppConstants.RequestMethod.GET, callback);
}
}
private HashMap getUrlParams(JSONObject urlQueriesJSON) {
HashMap hashMap = new HashMap<>();
if(urlQueriesJSON != null && urlQueriesJSON.length() > 0){
Iterator iter = urlQueriesJSON.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = urlQueriesJSON.opt(key);
hashMap.put(key, value);
} catch (Exception e) {
e.printStackTrace();
}
}
return hashMap;
}
return null;
}
private LinkedHashMap getHeader(LinkedHashMap localHeader) {
LinkedHashMap mainHeader = headerGroup_app;
LinkedHashMap classHeaders = new LinkedHashMap<>();
if(localHeader != null && localHeader.size() > 0){
if(mainHeader != null && mainHeader.size() > 0) {
for (Map.Entry entry : localHeader.entrySet()) {
String key = entry.getKey();
classHeaders.put(key, entry.getValue());
}
for (Map.Entry entry : mainHeader.entrySet()) {
String key = entry.getKey();
if(!classHeaders.containsKey(key)) {
classHeaders.put(key, entry.getValue());
}
}
return classHeaders;
}else{
return localHeader;
}
}else{
return headerGroup_app;
}
}
/**
* This method adds key and value to an Entry.
* @param key The key as string which needs to be added to an Asset
* @param value The value as string which needs to be added to an Asset
* @return {@link Asset}
*
*
Example :
*
* final Asset asset = stack.asset("blt5312f71416d6e2c8");
asset.addParam("key", "some_value");
* asset.fetch(new FetchResultCallback() {
* @Override
* public void onCompletion(ResponseType responseType, Error error) {
* if(error == null){
* //Success Block.
* }else {
* //Fail Block.
* }
* }
* });
*
*
*
*/
public Asset addParam(String key, String value){
if(key != null && value != null){
headerGroup_local.put(key, value);
}
return this;
}
}