Hierarchical SQL Queries in Adobe CQ5

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package com.globalbin.web.servlets;

import java.io.IOException;
import java.io.Writer;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PropertyIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.Row;
import javax.jcr.query.RowIterator;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.apache.sling.jcr.api.SlingRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
@Service(Servlet.class)
@Properties({
    @Property(name="service.description", value="MultiLevel Servlet"),
    @Property(name="service.vendor", value="The Global Bin"),
    @Property(name="sling.servlet.extensions", value="json"),
    @Property(name="sling.servlet.paths", value="/bin/multi")
})

public class MultiLevelQueryServlet extends SlingAllMethodsServlet {
   
    private static final long serialVersionUID = 1L;
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    private Session session;
   
    @Reference
    private SlingRepository repository;
    protected void bindRepository(SlingRepository repository) {
        this.repository = repository;
    }
   
    @Override
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
            throws ServletException, IOException {

        String term = request.getParameter("q");
        String sqlQuery = "SELECT * FROM [cq:Page] AS parent INNER JOIN [nt:base] AS child "
         + "ON ISCHILDNODE(child,parent) WHERE ISDESCENDANTNODE(parent, '/content/geometrixx/en/events') AND "
         + "CONTAINS(child.*, '"+ term +"')";
               
        JSONArray found = sqlQueryJcr(sqlQuery);
        log.info(">> SQL QUERY: " + sqlQuery);
        response.setContentType("application/json");
        Writer w = response.getWriter();
        w.write(found.toString());
    }
   
    private JSONArray sqlQueryJcr(String queryString) {
        JSONArray results = new JSONArray();
        try {
            session = this.repository.loginAdministrative(null);
            QueryManager qm = session.getWorkspace().getQueryManager();
            Query query = qm.createQuery(queryString, Query.JCR_SQL2);
            RowIterator ri = query.execute().getRows();        
            while (ri.hasNext()) {
                  JSONObject dbObj = new JSONObject();
                  Row row = ri.nextRow();
                  Node parent = row.getNode("parent");
                  dbObj.put("result-"+parent.getPath(), nodeToJsonObject(parent));
                  results.put(dbObj);
            }
        } catch (RepositoryException re) {
            log.error(">>> ERROR:" + re.getMessage());
        } catch (Exception e) {
            log.error("> ERROR:" + e.getMessage());
        } finally {
            session.logout();
        }
        return results;
    }
   
    private JSONArray nodesToJsonArray(NodeIterator ni) {
        JSONArray jsonArray = new JSONArray();
        while (ni.hasNext()) {
            Node node = ni.nextNode();
            JSONObject obj = new JSONObject();
            try {
                obj.put( node.getName(), nodeToJsonObject(node));
            } catch (JSONException e) {
                log.error(e.getMessage());
            } catch (RepositoryException e) {
                log.error(e.getMessage());
            }
            jsonArray.put(obj);
        }
        return jsonArray;
    }
   
    private JSONObject nodeToJsonObject(Node node) {
        JSONObject obj = new JSONObject();
        try {
            PropertyIterator pi = node.getProperties();
            while (pi.hasNext()) {
                javax.jcr.Property prop = pi.nextProperty();
                if (prop.isMultiple()) {
                    obj.put(prop.getName(), "[multi]");
                } else {
                    obj.put(prop.getName(), prop.getString());                 
                }
            }
            NodeIterator children = node.getNodes();
            obj.put("nodes-of-" + node.getName(), nodesToJsonArray(children));
        } catch (JSONException e) {
            log.error(e.getMessage());
        } catch (RepositoryException e) {
            log.error(e.getMessage());
        }      
        return obj;
    }
}

Leave a Reply

You must be logged in to post a comment.