Expand my Community achievements bar.

SOLVED

no resultset from custom resource resolver and session for querybuilder

Avatar

Level 4

Hello,

 

I am posting this to seek advice from AEM experts.

I am attempting to upgrade an existing custom component to resolve an issue with an Unclosed Resource Resolver.

I created a custom system user, a custom Resource Resolver, and used it to create a custom session. I also conducted a querybuilder search, generated search results, and followed a process to display the data using the results.

In summary, I performed the following steps (please refer to the screenshot):

  1. Created a custom system user and set permissions.
  2. Created a resource resolver.
  3. Created a session.
  4. Created a querybuilder.
  5. Created a resultset.
  6. Displayed the data.

The issue I am facing is that there are no problems up to the querybuilder step, but the resultset is being assigned null. When I checked using the querybuilder, I confirmed that multiple records were indeed being found, but the resultset is still assigned null.

I would appreciate your feedback on what might be causing the issue in the above procedure.
Regards
=========================================

Screenshot 2024-10-14 182310.pngScreenshot 2024-10-14 182455.pngScreenshot 2024-10-14 182549.pngScreenshot 2024-10-14 182725.png
======================

<serviceSearch.jsp>
<%@include file="/libs/foundation/global.jsp" %>
<%@page import="com.day.cq.search.PredicateGroup" %>
<%@page import="com.day.cq.search.Query" %>
<%@page import="com.day.cq.search.QueryBuilder" %>
<%@page import="com.day.cq.search.result.Hit" %>
<%@page import="com.day.cq.search.result.SearchResult" %>
<%@page import="com.t4g.cnb.utils.ResourceUtils" %>
<%@page import="org.apache.sling.api.resource.ResourceResolver" %>
<%@page import="org.apache.sling.api.resource.ResourceResolverFactory" %>
<%@page import="java.util.HashMap" %>
<%@page import="java.util.Map" %>
<%
    ResourceResolverFactory resolverFactory = sling.getService(ResourceResolverFactory.class);
    ResourceResolver resolver = null;
    Session session = null;
    try {
        resolver = ResourceUtils.getWriteResourceResolver(resolverFactory);
        if (resolver == null) {
    out.println("Resolver is null");
        }else{
out.println("Resolver is NOT null");
        }
 
        session = ResourceUtils.getServiceUserSession(resolver);
if (session == null) {
    out.println("Session is null");
        }else{
out.println("Session is NOT null");
        }
        QueryBuilder queryBuilder = resolver.adaptTo(QueryBuilder.class);
        Map<String, String> map = new HashMap<>();
        map.put("path", "/content/gnb/en/news");
        map.put("type", "cq:Page");
        map.put("p.limit", "10");
 
        Query query = queryBuilder.createQuery(PredicateGroup.create(map), session);
        SearchResult result = query.getResult();
        out.println("Total results: " + result.getTotalMatches());
 
        for (Hit hit : result.getHits()) {
            out.println("Page: " + hit.getPath());
        }
 
    } catch (Exception e) {
        out.println("Error: " + e.getMessage());
    } finally {
        if (resolver != null && resolver.isLive()) {
            //resolver.close();
            ResourceUtils.terminateResourceResolver(resolver);
        }
        if (session.isLive()) {
            ResourceUtils.terminateSession(session);
        }
    }
%>
 
----------------------------
<ResourceUtils.java>
package com.t4g.cnb.utils;
 
import java.util.Collections;
import java.util.Map;
import javax.jcr.Session;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class ResourceUtils {
 
  private static final Logger LOGGER = LoggerFactory.getLogger(ResourceUtils.class);
 
  private static final String WRITE_SERVICE_NAME = "writeService";
 
  public static Session getServiceUserSession(ResourceResolver resourceResolver) throws NullPointerException {
    if (resourceResolver == null) {
      throw new NullPointerException("Failed to retrieve session.");
    }
    return resourceResolver.adaptTo(Session.class);
  }
 
  public static ResourceResolver getWriteResourceResolver(ResourceResolverFactory resolverFactory)
    throws NullPointerException {
    ResourceResolver resolver = getResourceResolver(resolverFactory);
 
    if (resolver == null) {
      throw new NullPointerException("Failed to retrieve resource resolver.");
    }
    return resolver;
  }
 
  public static void terminateResourceResolver(ResourceResolver resourceResolver) {
    if (resourceResolver != null) {
      resourceResolver.close();
    }
  }
 
  public static void terminateSession(Session session) {
    if (session != null) {
      session.logout();
    }
  }
 
  private static ResourceResolver getResourceResolver(ResourceResolverFactory resolverFactory) {
    ResourceResolver resolver = null;
    Map<String, Object> authInfo;
    try {
      authInfo = Collections.singletonMap(ResourceResolverFactory.SUBSERVICE, WRITE_SERVICE_NAME);
      resolver = resolverFactory.getServiceResourceResolver(authInfo);
    } catch (LoginException e) {
      LOGGER.error("Login Exception while getting resource resolver", e);
    }
    return resolver;
  }
}
----------------
<org.apache.sling.jcr.repoinit.RepositoryInitializer~cnb_hfx.config>
# Configuration created by Apache Sling JCR Installer
scripts=["create\ path\ (sling:OrderedFolder)\ /content/dam/cnb_hfx","create\ path\ (nt:unstructured)\ /content/dam/cnb_hfx/jcr:content","set\ properties\ on\ /content/dam/cnb_hfx/jcr:content\r\n\ \ set\ cq:conf{String}\ to\ /conf/cnb_hfx\r\n\ \ set\ jcr:title{String}\ to\ \"T4G\ CNB\ Project\"\r\nend","create\ service\ user\ writeService\ with\ path\ /home/users/system/gnb","set\ ACL\ for\ writeService\r\n\ \ allow\ jcr:read,rep:write\ on\ /,\ /content\r\nend"]
references=[""]
 
------------------
<org.apache.sling.serviceusermapping.impl.ServiceUserMapperImpl.amended~cnb_hfx.config>
user.mapping=[ \
"cnb_hfx.core\=[writeService]"
]
 
-------------------
1 Accepted Solution

Avatar

Correct answer by
Community Advisor

Hi @keehwan1,

You may try something like below

Map<String, String> queryMap = new HashMap<>();
            queryMap.put("path", rootPath);
            queryMap.put("p.limit", "-1");
            queryMap.put("p.offset", "0");
            queryMap.put("type", NT_PAGE);
            queryMap.put("1_property", "jcr:content/jcr:primaryType");
            queryMap.put("1_property.value", "cq:PageContent");
            Query query = queryBuilder.createQuery(PredicateGroup.create(queryMap), request.getResourceResolver().adaptTo(Session.class));
            SearchResult result = query.getResult();

Thanks

View solution in original post

4 Replies

Avatar

Level 4

What kind of permissions have you set to the service user?

Avatar

Level 4

Thank you for replying, @rk_pandian 
The service user of 'writeService' have been set as read/create/delete all on content.
 
keehwan1_0-1728990912554.png

 

Avatar

Correct answer by
Community Advisor

Hi @keehwan1,

You may try something like below

Map<String, String> queryMap = new HashMap<>();
            queryMap.put("path", rootPath);
            queryMap.put("p.limit", "-1");
            queryMap.put("p.offset", "0");
            queryMap.put("type", NT_PAGE);
            queryMap.put("1_property", "jcr:content/jcr:primaryType");
            queryMap.put("1_property.value", "cq:PageContent");
            Query query = queryBuilder.createQuery(PredicateGroup.create(queryMap), request.getResourceResolver().adaptTo(Session.class));
            SearchResult result = query.getResult();

Thanks

Avatar

Administrator

@keehwan1 Did you find the suggestions helpful? Please let us know if you require more information. Otherwise, please mark the answer as correct for posterity. If you've discovered a solution yourself, we would appreciate it if you could share it with the community. Thank you!



Kautuk Sahni