October 13, 2020
Estimated Post Reading Time ~

Read/Write data in Json file of DAM in AEM + Making Rest API Call.



This is the frequently searched query on Google by AEM Developers.
So I will provide you the code in which we can use Asset and AssetManager API to read and write the data to any file in out DAM structure.
For this we need System User to be created which has read and write permission of DAM folder using which we will access the resource in our code.
So following is the code with required comments.

For better understanding copy the following code/paste in notepad++ or eclipse and format it:

package com.ab.internal.servlets;

//Java program to read JSON from a file
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

import javax.servlet.Servlet;
import javax.servlet.ServletException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.json.JSONException;
import org.json.JSONObject;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.day.cq.dam.api.Asset;

@Component(service = Servlet.class, property = {
Constants.SERVICE_DESCRIPTION
+ “= Servlet to save data in AEM from Holiday Calendar API”,
“sling.servlet.paths=” + “/apps/ab/holidayCalendar” })
public class HolidayCalendar extends SlingSafeMethodsServlet {

private static final long serialVersionUID = 1L;

protected static final Logger LOGGER = LoggerFactory
.getLogger(HolidayCalendar.class);

@Reference
private ResourceResolverFactory resolverFactory;

@Override
protected void doGet(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws ServletException,
IOException {

// Reading the JSON File from DAM.
Resource original;
String myJSON = “”;

LOGGER.info(“before factory..”);
ResourceResolver resolver = null;
HashMap<String, Object> param = new HashMap<>();
param.put(ResourceResolverFactory.SUBSERVICE, “readService”); //readService is my System User.
LOGGER.info(“After factory..”);
try {

resolver = resolverFactory.getServiceResourceResolver(param);
Resource resource = resolver
.getResource(“/content/dam/ab/holiday.json”);
Asset asset = resource.adaptTo(Asset.class);
original = asset.getOriginal();
InputStream content = original.adaptTo(InputStream.class);

StringBuilder sb = new StringBuilder();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(
content, StandardCharsets.UTF_8));

while ((line = br.readLine()) != null) {
sb.append(line);
}
JSONObject jsonObj = new JSONObject(sb.toString()); // In jsonObj I will get the data from the JSON file from DAM.

} catch (LoginException | JSONException e1) {
LOGGER.info(“EXCEPTION”);
}

// Getting the data from API Call by sending header parameters.

JSONObject json = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet getRequest = new HttpGet(
“/rest/api/end/point”);
getRequest.addHeader(“accept”, “application/json”);
getRequest.addHeader(“ClientId”, “123456”);
getRequest.addHeader(“Request-Tracking-Id”, “123456”);
HttpResponse httpResponse = httpClient.execute(getRequest);
LOGGER.info(“before if condition”);
if (httpResponse.getStatusLine().getStatusCode() != 200) {
LOGGER.info(“inside if condigiton”);
throw new RuntimeException(“Failed : HTTP error code : ”
+ httpResponse.getStatusLine().getStatusCode());
} else {
StringBuilder sb = new StringBuilder();
LOGGER.info(“before buffer reader”);
BufferedReader br = new BufferedReader(new InputStreamReader(
(httpResponse.getEntity().getContent())));

String output;
while ((output = br.readLine()) != null) {

myJSON = myJSON + output;
sb.append(output);
}

// Saving the data to DAM .json file which we got from API call.
InputStream is = new ByteArrayInputStream(myJSON.getBytes()); //we are sending the JSON data as a String.
com.day.cq.dam.api.AssetManager assetMgr = resolver
.adaptTo(com.day.cq.dam.api.AssetManager.class);
assetMgr.createAsset(“/content/dam/ab/holidayApi.json”, is,
“application/json”, true);
try {
json = new JSONObject(sb.toString());
} catch (JSONException e) {
LOGGER.info(“EXCEPTION”);
}

}

response.getWriter().println(json);

}
}


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.