Menu

Execute a query in AEM

Execute SQL query with the help of QueryManger interface in Adobe Experience Manager(AEM) using Java.

QueryManager interface encapsulates methods for the management of search queries. Provides methods for the creation and retrieval of search queries.

Method used: createQuery

In this sample program we have created a sling servlet and register that servlet on paths. When browser make the request to registered path then a serch query will get executed and find the all nodes which contains resourceType "granite/ui/components/foundation/form/textfield" under path "/apps/myproject/components/config".
 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.ModifiableValueMap;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.slf4j.Logger;

@SlingServlet(paths ="/bin/private/addMissingProperties", methods = "GET", selectors="", extensions="html", metatype=true)
public class AddDialogProperties extends SlingAllMethodsServlet{
 /**
  *
  */
 private static final long serialVersionUID = 1L;
 Logger LOGGER=org.slf4j.LoggerFactory.getLogger(AddDialogProperties.class);

 protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
  String queryStatement = "SELECT * FROM [nt:unstructured] AS s WHERE ISDESCENDANTNODE([/apps/myproject/components/config]) AND [sling:resourceType] = \"granite/ui/components/foundation/form/textfield\"";
  ResourceResolver resourceResolver=request.getResourceResolver();
  javax.jcr.Session session=resourceResolver.adaptTo(javax.jcr.Session.class);
  QueryManager queryManager;
  try {
   queryManager = session.getWorkspace().getQueryManager();
   Query query = queryManager.createQuery(queryStatement, Query.JCR_SQL2);
   QueryResult result = query.execute();
   NodeIterator nodes;
   nodes = result.getNodes();
   while (nodes.hasNext()) {
    Node node = nodes.nextNode();
    ModifiableValueMap mvp=resourceResolver.getResource(node.getPath()).adaptTo(ModifiableValueMap.class);
    mvp.put("value", " ");
    resourceResolver.commit();
   }
  } catch (Exception e) {
   LOGGER.error("Exception occured in class AddDialogProperties {}" ,e);
  }
 }

}

No comments:

Post a Comment