Skip to content

Commit 622b532

Browse files
Merge pull request #201 from contentstack/staging
DX | 26-05-2025 | Release
2 parents ca31a89 + 71f296f commit 622b532

File tree

11 files changed

+309
-3
lines changed

11 files changed

+309
-3
lines changed

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
# CHANGELOG
22

3+
## v2.1.2
4+
5+
### Date: 26-May-2025
6+
7+
- Global field implementation
8+
39
## v2.1.1
410

511
### Date: 1-Apr-2025

pom.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
<modelVersion>4.0.0</modelVersion>
66
<groupId>com.contentstack.sdk</groupId>
77
<artifactId>java</artifactId>
8-
<version>2.1.1</version>
8+
<version>2.1.2</version>
99
<packaging>jar</packaging>
1010
<name>contentstack-java</name>
1111
<description>Java SDK for Contentstack Content Delivery API</description>

src/main/java/com/contentstack/sdk/CSBackgroundTask.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,4 +100,15 @@ protected void checkHeader(@NotNull Map<String, Object> headers) {
100100
}
101101
}
102102

103+
protected CSBackgroundTask(GlobalField globalField, Stack stackInstance, String controller, String url,
104+
HashMap<String, Object> headers, HashMap<String, Object> urlParams, String requestInfo,
105+
ResultCallBack callback) {
106+
checkHeader(headers);
107+
String completeUrl = stackInstance.config.getEndpoint() + url;
108+
CSConnectionRequest csConnectionRequest = new CSConnectionRequest(globalField);
109+
csConnectionRequest.setURLQueries(urlParams);
110+
this.service = stackInstance.service;
111+
csConnectionRequest.setParams(completeUrl, headers, controller, requestInfo, callback, this.service, stackInstance);
112+
}
113+
103114
}

src/main/java/com/contentstack/sdk/CSConnectionRequest.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,10 @@ public CSConnectionRequest(ContentType contentType) {
5353
this.endpoint = contentType.stackInstance.config.getEndpoint();
5454
}
5555

56+
public CSConnectionRequest(GlobalField globalField) {
57+
this.endpoint = globalField.stackInstance.config.getEndpoint();
58+
}
59+
5660
public void setQueryInstance(Query queryInstance) {
5761
this.endpoint = queryInstance.contentTypeInstance.stackInstance.config.getEndpoint();
5862
}
@@ -167,6 +171,12 @@ public synchronized void onRequestFinished(CSHttpConnection request) {
167171
if (request.getCallBackObject() != null) {
168172
((ContentTypesCallback) request.getCallBackObject()).onRequestFinish(model);
169173
}
174+
} else if (request.getController().equalsIgnoreCase(Constants.FETCHGLOBALFIELDS)) {
175+
GlobalFieldsModel model = new GlobalFieldsModel();
176+
model.setJSON(jsonResponse);
177+
if (request.getCallBackObject() != null) {
178+
((GlobalFieldsCallback) request.getCallBackObject()).onRequestFinish(model);
179+
}
170180
}
171181
}
172182

src/main/java/com/contentstack/sdk/Constants.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ protected Constants() {
5454
*/
5555
// REQUEST_CONTROLLER
5656
public enum REQUEST_CONTROLLER {
57-
QUERY, ENTRY, ASSET, SYNC, CONTENTTYPES, ASSETLIBRARY
57+
QUERY, ENTRY, ASSET, SYNC, CONTENTTYPES, ASSETLIBRARY, GLOBALFIELDS
5858
}
5959

6060
// GET REQUEST TYPE
@@ -65,6 +65,7 @@ public enum REQUEST_CONTROLLER {
6565
public static final String FETCHASSETS = "getAssets";
6666
public static final String FETCHSYNC = "getSync";
6767
public static final String FETCHCONTENTTYPES = "getContentTypes";
68+
public static final String FETCHGLOBALFIELDS = "getGlobalFields";
6869

6970
public static final String CONTENT_TYPE_NAME = "Please set contentType name.";
7071
public static final String QUERY_EXCEPTION = "Please provide valid params.";
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
package com.contentstack.sdk;
2+
3+
import org.jetbrains.annotations.NotNull;
4+
import org.json.JSONObject;
5+
6+
import java.util.HashMap;
7+
import java.util.Iterator;
8+
import java.util.LinkedHashMap;
9+
import java.util.logging.Logger;
10+
11+
/**
12+
* This call returns information of a specific global field. It returns the
13+
* global field schema.
14+
*
15+
*/
16+
public class GlobalField {
17+
18+
protected static final Logger logger = Logger.getLogger(GlobalField.class.getSimpleName());
19+
protected String globalFieldUid;
20+
protected Stack stackInstance = null;
21+
protected JSONObject params = new JSONObject();
22+
protected LinkedHashMap<String, Object> headers = null;
23+
24+
protected GlobalField() {
25+
this.headers = new LinkedHashMap<>();
26+
}
27+
28+
protected GlobalField(@NotNull String globalFieldUid) {
29+
this.globalFieldUid = globalFieldUid;
30+
this.headers = new LinkedHashMap<>();
31+
}
32+
33+
protected void setStackInstance(Stack stack) {
34+
this.stackInstance = stack;
35+
this.headers = stack.headers;
36+
}
37+
38+
/**
39+
* Sets header on {@link Stack}.
40+
*
41+
* @param headerKey
42+
* the header key
43+
* @param headerValue
44+
* the header value
45+
*/
46+
public void setHeader(String headerKey, String headerValue) {
47+
if (!headerKey.isEmpty() && !headerValue.isEmpty()) {
48+
this.headers.put(headerKey, headerValue);
49+
}
50+
}
51+
52+
/**
53+
* Remove header from {@link Stack}
54+
*
55+
* @param headerKey
56+
* the header key
57+
*/
58+
public void removeHeader(String headerKey) {
59+
if (!headerKey.isEmpty()) {
60+
this.headers.remove(headerKey);
61+
}
62+
}
63+
64+
/**
65+
* Fetch.
66+
*
67+
* @param params
68+
* the params
69+
* @param callback
70+
* the callback
71+
* @throws IllegalAccessException
72+
* illegal access exception
73+
*/
74+
75+
public GlobalField includeBranch() {
76+
this.params.put("include_branch", true);
77+
return this;
78+
}
79+
80+
public GlobalField includeGlobalFieldSchema() {
81+
this.params.put("include_global_field_schema", true);
82+
return this;
83+
}
84+
85+
public void fetch(final GlobalFieldsCallback callback) throws IllegalAccessException {
86+
String urlString = "global_fields/" + globalFieldUid;
87+
if (globalFieldUid == null || globalFieldUid.isEmpty()) {
88+
throw new IllegalAccessException("globalFieldUid is required");
89+
}
90+
fetchGlobalFields(urlString, this.params, this.headers, callback);
91+
}
92+
93+
public void findAll(final GlobalFieldsCallback callback) {
94+
String urlString = "global_fields";
95+
fetchGlobalFields(urlString, this.params, this.headers, callback);
96+
}
97+
98+
private void fetchGlobalFields(String urlString, JSONObject params, HashMap<String, Object> headers,
99+
GlobalFieldsCallback callback) {
100+
if (callback != null) {
101+
HashMap<String, Object> urlParams = getUrlParams(params);
102+
new CSBackgroundTask(this, stackInstance, Constants.FETCHGLOBALFIELDS, urlString, headers, urlParams,
103+
Constants.REQUEST_CONTROLLER.GLOBALFIELDS.toString(), callback);
104+
}
105+
}
106+
107+
private HashMap<String, Object> getUrlParams(JSONObject urlQueriesJSON) {
108+
HashMap<String, Object> hashMap = new HashMap<>();
109+
if (urlQueriesJSON != null && urlQueriesJSON.length() > 0) {
110+
Iterator<String> itStr = urlQueriesJSON.keys();
111+
while (itStr.hasNext()) {
112+
String key = itStr.next();
113+
Object value = urlQueriesJSON.opt(key);
114+
hashMap.put(key, value);
115+
}
116+
}
117+
return hashMap;
118+
}
119+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.contentstack.sdk;
2+
3+
/**
4+
* The callback for Content Types that contains GlobalFieldsModel and Error
5+
*/
6+
public abstract class GlobalFieldsCallback implements ResultCallBack {
7+
8+
public abstract void onCompletion(GlobalFieldsModel globalFieldsModel, Error error);
9+
10+
void onRequestFinish(GlobalFieldsModel globalFieldsModel) {
11+
onCompletion(globalFieldsModel, null);
12+
}
13+
14+
@Override
15+
public void onRequestFail(ResponseType responseType, Error error) {
16+
onCompletion(null, error);
17+
}
18+
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.contentstack.sdk;
2+
3+
import java.util.ArrayList;
4+
import java.util.LinkedHashMap;
5+
import java.util.List;
6+
import org.json.JSONArray;
7+
import org.json.JSONObject;
8+
9+
/**
10+
* The GlobalFieldsModel that contains global fields response
11+
*/
12+
public class GlobalFieldsModel {
13+
14+
private Object response;
15+
private JSONArray responseJSONArray = new JSONArray();
16+
17+
public void setJSON(JSONObject responseJSON) {
18+
if (responseJSON != null) {
19+
String gfKey = "global_field";
20+
if (responseJSON.has(gfKey) && responseJSON.opt(gfKey) instanceof LinkedHashMap) {
21+
try {
22+
this.response = new JSONObject((LinkedHashMap<?, ?>) responseJSON.get(gfKey));
23+
} catch (Exception e) {
24+
System.err.println("Error processing 'global_field': " + e.getMessage());
25+
}
26+
}
27+
String gfListKey = "global_fields";
28+
if (responseJSON.has(gfListKey) && responseJSON.opt(gfListKey) instanceof ArrayList) {
29+
try {
30+
ArrayList<LinkedHashMap<?, ?>> globalFields = (ArrayList) responseJSON.get(gfListKey);
31+
List<Object> objectList = new ArrayList<>();
32+
if (!globalFields.isEmpty()) {
33+
globalFields.forEach(model -> {
34+
if (model instanceof LinkedHashMap) {
35+
// Convert LinkedHashMap to JSONObject
36+
JSONObject jsonModel = new JSONObject((LinkedHashMap<?, ?>) model);
37+
objectList.add(jsonModel);
38+
} else {
39+
System.err.println("Invalid type in 'global_fields' list. Expected LinkedHashMap.");
40+
}
41+
});
42+
}
43+
this.response = new JSONArray(objectList);
44+
this.responseJSONArray = new JSONArray(objectList);
45+
} catch (Exception e) {
46+
System.err.println("Error processing 'global_fields': " + e.getMessage());
47+
}
48+
}
49+
}
50+
}
51+
52+
public Object getResponse() {
53+
return this.response;
54+
}
55+
56+
public JSONArray getResultArray() {
57+
return responseJSONArray;
58+
}
59+
}

src/main/java/com/contentstack/sdk/Stack.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ public class Stack {
3232
protected LinkedHashMap<String, Object> headers;
3333
protected Config config;
3434
protected String contentType;
35+
protected String globalField;
3536
protected String livePreviewEndpoint;
3637
protected APIService service;
3738
protected String apiKey;
@@ -212,6 +213,19 @@ public ContentType contentType(String contentTypeUid) {
212213
return ct;
213214
}
214215

216+
public GlobalField globalField(@NotNull String globalFieldUid) {
217+
this.globalField = globalFieldUid;
218+
GlobalField gf = new GlobalField(globalFieldUid);
219+
gf.setStackInstance(this);
220+
return gf;
221+
}
222+
223+
public GlobalField globalField() {
224+
GlobalField gf = new GlobalField();
225+
gf.setStackInstance(this);
226+
return gf;
227+
}
228+
215229
/**
216230
* Assets refer to all the media files (images, videos, PDFs, audio files, and so on) uploaded in your Contentstack
217231
* repository for future use. These files can be attached and used in multiple entries.

src/test/java/com/contentstack/sdk/TestEntry.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ public void onCompletion(ResponseType responseType, QueryResult queryresult, Err
4242
if (error == null) {
4343
List<LinkedHashMap<?, ?>> list = (ArrayList)queryresult.receiveJson.get("entries");
4444
LinkedHashMap<?, ?> firstObj = list.get(0);
45-
entryUid = (String)firstObj.get("uid");
45+
// entryUid = (String)firstObj.get("uid");
4646
assertTrue(entryUid.startsWith("blt"));
4747
logger.info("passed..");
4848
} else {
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package com.contentstack.sdk;
2+
import org.json.JSONArray;
3+
import org.json.JSONObject;
4+
import org.junit.jupiter.api.Assertions;
5+
import org.junit.jupiter.api.BeforeEach;
6+
import org.junit.jupiter.api.Test;
7+
import static org.junit.jupiter.api.Assertions.*;
8+
9+
public class TestGlobalFields {
10+
11+
private GlobalFieldsModel globalFieldsModel;
12+
private final Stack stack = Credentials.getStack();
13+
14+
@BeforeEach
15+
void setUp() {
16+
globalFieldsModel = new GlobalFieldsModel();
17+
}
18+
19+
@Test
20+
void testSetJSONWithNull() {
21+
globalFieldsModel.setJSON(null);
22+
assertNull(globalFieldsModel.getResponse());
23+
assertEquals(0, globalFieldsModel.getResultArray().length());
24+
}
25+
26+
@Test
27+
void testSetJSONWithEmptyObject() {
28+
globalFieldsModel.setJSON(new JSONObject());
29+
assertNull(globalFieldsModel.getResponse());
30+
assertEquals(0, globalFieldsModel.getResultArray().length());
31+
}
32+
33+
@Test
34+
void testFetchGlobalFieldByUid() throws IllegalAccessException {
35+
GlobalField globalField = stack.globalField("specific_gf_uid");
36+
globalField.fetch(new GlobalFieldsCallback() {
37+
@Override
38+
public void onCompletion(GlobalFieldsModel model, Error error) {
39+
JSONArray resp = model.getResultArray();
40+
Assertions.assertTrue(resp.isEmpty());
41+
}
42+
});
43+
}
44+
45+
@Test
46+
void testFindGlobalFieldsIncludeBranch() {
47+
GlobalField globalField = stack.globalField().includeBranch();
48+
globalField.findAll(new GlobalFieldsCallback() {
49+
@Override
50+
public void onCompletion(GlobalFieldsModel globalFieldsModel, Error error) {
51+
assertTrue(globalFieldsModel.getResultArray() instanceof JSONArray);
52+
assertNotNull(((JSONArray) globalFieldsModel.getResponse()).length());
53+
}
54+
});
55+
}
56+
57+
@Test
58+
void testFindGlobalFields() throws IllegalAccessException {
59+
GlobalField globalField = stack.globalField().includeBranch();
60+
globalField.findAll(new GlobalFieldsCallback() {
61+
@Override
62+
public void onCompletion(GlobalFieldsModel globalFieldsModel, Error error) {
63+
assertTrue(globalFieldsModel.getResultArray() instanceof JSONArray);
64+
assertNotNull(((JSONArray) globalFieldsModel.getResponse()).length());
65+
}
66+
});
67+
}
68+
}

0 commit comments

Comments
 (0)