Servelt code not visible in publish mode
Hi i have written a servelt (below)
In servelt i am getting all the children pages that are published but the url works fine in author mode but in publish mode i can't able to see any data
Looks like I am getting an empty array in publish mode Can someone help me with that?
The servelt returning empty array in publish but in author I am getting data
Here is my servelt code:
@Component(service = Servlet.class, property = {
Constants.SERVICE_DESCRIPTION + "=Name Checker Servlet",
"sling.servlet.methods=" + HttpConstants.METHOD_GET,
"sling.servlet.paths=" + "/bin/cisco/newdemos"
})
public class NewDemosServlet extends SlingSafeMethodsServlet {
private static final Logger log = LoggerFactory.getLogger(NewDemosServlet.class);
private static final int ITEMS_PER_PAGE = 12; // Items per page
@Override
public void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
try {
log.info("In the servlet");
response.setContentType("application/json");
// Get the requested page number from the request parameter
int requestedPage = 1; // Default to page 1
String pageParam = request.getParameter("page");
log.info("Page Parameter: {}", pageParam);
if (pageParam != null && !pageParam.isEmpty()) {
try {
requestedPage = Integer.parseInt(pageParam);
log.info("Requested Page: {}", requestedPage);
} catch (NumberFormatException e) {
// Handle invalid page parameter
log.error("Invalid 'page' parameter: " + pageParam);
response.setStatus(SlingHttpServletResponse.SC_BAD_REQUEST);
return;
}
}
ResourceResolver resourceResolver = request.getResourceResolver();
log.info("resourceResolver: {}", resourceResolver);
Resource parentResource = resourceResolver.getResource("/content/cisco-dcloud/us/en/home/new-demos");
log.info("parentResource: {}", parentResource);
if (parentResource == null) {
log.error("Parent resource is not found.");
response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// Get a list of child resources
Iterator<Resource> childResources = parentResource.listChildren();
log.info("childResources: {}", childResources.hasNext());
List<JsonObject> jsonList = new ArrayList<>();
int totalItems = 0;
while (childResources.hasNext()) {
Resource childResource = childResources.next();
PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
Page page = pageManager.getContainingPage(childResource);
if (page != null && isPagePublished(page)) {
totalItems++;
log.info("childResource: {}", childResource);
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("childTitle",
childResource.getValueMap().get("jcr:content/jcr:title", String.class));
jsonObject.addProperty("childDescription",
childResource.getValueMap().get("jcr:content/jcr:description", String.class));
jsonObject.addProperty("childImage",
childResource.getValueMap().get("cq:featuredimage/fileReference", String.class));
jsonObject.addProperty("childPath", childResource.getPath());
Calendar createdDate = childResource.getValueMap().get("jcr:content/jcr:created", Calendar.class);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = (createdDate != null) ? dateFormat.format(createdDate.getTime()) : null;
jsonObject.addProperty("createdDate", formattedDate);
log.info("createdDate: {}", formattedDate);
int year = -1;
int month = -1;
if (createdDate != null) {
year = createdDate.get(Calendar.YEAR);
month = createdDate.get(Calendar.MONTH) + 1;
}
if (year != -1) {
jsonObject.addProperty("creationYear", year);
}
if (month != -1) {
jsonObject.addProperty("creationMonth", month);
}
jsonObject.addProperty("childTags",
childResource.getValueMap().get("jcr:content/cq:tags", String.class));
jsonList.add(jsonObject);
}
}
// Sort the entire list before applying pagination
Collections.sort(jsonList, Comparator.<JsonObject, Long>comparing(jsonObject -> {
JsonElement createdDateElement = jsonObject.get("createdDate");
if (createdDateElement != null && !createdDateElement.isJsonNull()) {
String dateString = createdDateElement.getAsString();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = dateFormat.parse(dateString);
return date.getTime();
} catch (ParseException e) {
log.error("Error parsing date: " + dateString, e);
}
}
return 0L;
}).reversed());
// Apply pagination to the sorted list
JsonArray jsonArray = new JsonArray();
for (int i = (requestedPage - 1) * ITEMS_PER_PAGE; i < Math.min(jsonList.size(),
requestedPage * ITEMS_PER_PAGE); i++) {
jsonArray.add(jsonList.get(i));
}
// Create a response JSON object that includes totalItems and items
JsonObject responseJson = new JsonObject();
responseJson.addProperty("totalItems", totalItems);
responseJson.addProperty("itemsPerPage", ITEMS_PER_PAGE);
responseJson.addProperty("currentPage", requestedPage);
responseJson.add("items", jsonArray);
// Send the JSON object as the response
response.getWriter().write(responseJson.toString());
} catch (Exception e) {
log.error("Error in NewDemosServlet: " + e.getMessage());
response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
private boolean isPagePublished(Page page) {
// return page.getProperties().get("cq:lastReplicated", null) != null;
ValueMap pageProperties = page.getProperties();
if (pageProperties.containsKey("cq:lastReplicationAction")) {
return !"Deactivate".equals(pageProperties.get("cq:lastReplicationAction", String.class));
}
return false;
}
}