Expand my Community achievements bar.

Don’t miss the AEM Skill Exchange in SF on Nov 14—hear from industry leaders, learn best practices, and enhance your AEM strategy with practical tips.

Servelt code not visible in publish mode

Avatar

Level 4

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?


 
Updating Media

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;
    }
}

 

10 Replies

Avatar

Community Advisor

Hi @tatrived 

Can you please check your servlet is installed in the publish instances & in the active state? Also please check the result is cached or not. And also can you please check whether it is failing any where or not. You can check the logs. Also please ensure the access rights for the service users in the publish instance.

Avatar

Community Advisor

Check the service user permission in publisher

 

cq:lastReplicationAction property of a page. This property is protected and cannot be accessed by anonymous users.

Avatar

Level 4

Hi Suresh,

Thanks for the quick response
where can i find the publisher so that i can check user permission, sorry i am new to this

If you can help me navigate?

Avatar

Community Advisor

Hi @tatrived 

  1. Verify Permissions: Ensure that the user accessing the publish environment has the necessary permissions to read the child resources under the parent resource. Check the user's permissions in AEM and make sure they have read access to the required content.

  2. Check Content Structure: Confirm that the content structure in the publish environment matches the structure in the author environment. Ensure that the parent resource and its child resources exist in the same location and have the same properties.

  3. Debugging: Add logging statements to your servlet code to check if the parent resource and child resources are being retrieved correctly in the publish environment. You can log the values of parentResource and childResources.hasNext() to see if they are null or empty.

  4. Resource Resolver: In some cases, the resource resolver used in the servlet may not have the necessary permissions to access the child resources in the publish environment. You can try using a different resource resolver or adapting the existing resource resolver to a system user or a user with appropriate permissions.

  5. Replication Status: Ensure that the child resources are properly replicated to the publish environment. Check the replication status of the parent resource and its child resources to ensure they are replicated successfully.

  6. Cache Clearing: If you have recently made changes to the content structure or permissions, try clearing the AEM cache in the publish environment. This can help ensure that the latest content and permissions are reflected.



Avatar

Community Advisor

Hi @tatrived 
Please check the replication properties on publish by default it is not available on publish instances 

https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/cq-lastreplicated-not-foun... 

 

Better to write debugger logs to debug and point the exact problem. Make sure you use log.debug but info.



Arun Patidar

Avatar

Level 4

Can you help me with how to check if page is published or not with any 

lastReplicated or lastReplicationAction property because of this it is causing issue?

Avatar

Community Advisor

Hi @tatrived 
You can check the last modified that on publish.



Arun Patidar

Avatar

Level 4
 Calendar lastModifiedDate = page.getProperties().get("jcr:lastModified", Calendar.class);
        log.info("lastModifiedDate: {}", page.getProperties());
 
i am getting always null for lastModified property ?
and if i am using cq:lastModified it will always giving some value irrespective of page is published or not?
 Calendar lastModifiedDate = page.getProperties().get("cq:lastModified", Calendar.class);
 
       

Avatar

Community Advisor

Below line is the issue as it will not allow you to read node if we are not logged in to read resource and it'd data.

 

It will he good if you start your publish in debug mode and debug the issue.

 

ResourceResolver resourceResolver = request.getResourceResolver();

Avatar

Administrator

@tatrived Did you find the suggestions from users helpful? Please let us know if more information is required. Otherwise, please mark the answer as correct for posterity. If you have found out solution yourself, please share it with the community.



Kautuk Sahni