Clover icon

Magnolia REST Content Delivery 2.1

  1. Project Clover database Fri Mar 16 2018 18:21:08 CET
  2. Package info.magnolia.rest.delivery.jcr

File QueryBuilder.java

 

Coverage histogram

../../../../../img/srcFileCovDistChart10.png
0% of files have more coverage

Code metrics

30
94
22
1
337
220
47
0.5
4.27
22
2.14

Classes

Class Line # Actions
QueryBuilder 67 94 0% 47 8
0.9452054594.5%
 

Contributing tests

This file is covered by 33 tests. .

Source view

1    /**
2    * This file Copyright (c) 2017-2018 Magnolia International
3    * Ltd. (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10    * This file is distributed in the hope that it will be
11    * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12    * implied warranty of MERCHANTABILITY or FITNESS FOR A
13    * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14    * Redistribution, except as permitted by whichever of the GPL
15    * or MNA you select, is prohibited.
16    *
17    * 1. For the GPL license (GPL), you can redistribute and/or
18    * modify this file under the terms of the GNU General
19    * Public License, Version 3, as published by the Free Software
20    * Foundation. You should have received a copy of the GNU
21    * General Public License, Version 3 along with this program;
22    * if not, write to the Free Software Foundation, Inc., 51
23    * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24    *
25    * 2. For the Magnolia Network Agreement (MNA), this file
26    * and the accompanying materials are made available under the
27    * terms of the MNA which accompanies this distribution, and
28    * is available at http://www.magnolia-cms.com/mna.html
29    *
30    * Any modifications to this file must keep this entire header
31    * intact.
32    *
33    */
34    package info.magnolia.rest.delivery.jcr;
35   
36    import static java.util.stream.Collectors.*;
37   
38    import info.magnolia.jcr.RuntimeRepositoryException;
39    import info.magnolia.jcr.util.NodeTypes;
40   
41    import java.nio.file.Paths;
42    import java.util.ArrayList;
43    import java.util.LinkedList;
44    import java.util.List;
45    import java.util.Map;
46    import java.util.function.Function;
47    import java.util.regex.Matcher;
48    import java.util.regex.Pattern;
49    import java.util.stream.Stream;
50   
51    import javax.jcr.RepositoryException;
52    import javax.jcr.Workspace;
53    import javax.jcr.nodetype.NodeType;
54    import javax.jcr.nodetype.NodeTypeManager;
55    import javax.jcr.query.Query;
56    import javax.jcr.query.QueryManager;
57   
58    import org.apache.commons.collections4.CollectionUtils;
59    import org.apache.commons.lang3.StringUtils;
60    import org.apache.jackrabbit.util.Text;
61    import org.slf4j.Logger;
62    import org.slf4j.LoggerFactory;
63   
64    /**
65    * Query builder.
66    */
 
67    public class QueryBuilder {
68   
69    private static final Logger log = LoggerFactory.getLogger(QueryBuilder.class);
70   
71    private static final String SELECTOR_NAME = "t";
72   
73    private static final String SELECT_TEMPLATE = "SELECT * FROM [nt:base] AS " + SELECTOR_NAME;
74   
75    private static final String WHERE_TEMPLATE_FOR_PATH = " ISDESCENDANTNODE('%s')";
76   
77    private static final String ORDER_BY = " ORDER BY ";
78   
79    private static final String ASCENDING_KEYWORD = " ASC";
80   
81    private static final String JCR_NAME_FUNCTION = "LOWER(NAME(" + SELECTOR_NAME + "))";
82   
83    private static final String JCR_NAME = "@name";
84   
85    private static final String WHERE_TEMPLATE_FOR_SEARCH = "LOWER(LOCALNAME()) LIKE '%1$s%%'";
86   
87    private static final String CONTAINS_TEMPLATE_FOR_SEARCH = "CONTAINS(" + SELECTOR_NAME + ".*, '%1$s')";
88   
89    private static final String JCR_IS_SAME_NODE_FUNCTION = "ISSAMENODE(" + SELECTOR_NAME + ", '%1$s')";
90   
91    private final Pattern simpleTermsRegexPattern = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'");
92   
93    private final Workspace workspace;
94    private String rootPath;
95    private List<String> nodeTypes = new ArrayList<>();
96    private String keyword;
97    private List<FilteringCondition> filteringConditions = new ArrayList<>();
98    private List<String> propertiesToOrder;
99    private long offset;
100    private long limit;
101   
 
102  33 toggle private QueryBuilder(Workspace workspace) {
103  33 this.workspace = workspace;
104    }
105   
 
106  33 toggle public static QueryBuilder inWorkspace(Workspace workspace) {
107  33 return new QueryBuilder(workspace);
108    }
109   
 
110  3 toggle public QueryBuilder rootPath(String rootPath) {
111  3 this.rootPath = rootPath;
112  3 return this;
113    }
114   
 
115  22 toggle public QueryBuilder nodeTypes(List<String> nodeTypes) {
116  22 this.nodeTypes.addAll(nodeTypes);
117  22 return this;
118    }
119   
 
120  8 toggle public QueryBuilder keyword(String keyword) {
121  8 this.keyword = keyword;
122  8 return this;
123    }
124   
 
125  14 toggle public QueryBuilder conditions(Map<String, List<String>> conditions) {
126  14 List<FilteringCondition> conditionList = conditions.entrySet().stream()
127    .map(this::toFilteringConditions)
128    .flatMap(Function.identity())
129    .collect(toList());
130  13 this.filteringConditions.addAll(conditionList);
131  13 return this;
132    }
133   
 
134  12 toggle private Stream<FilteringCondition> toFilteringConditions(Map.Entry<String, List<String>> entry) {
135  12 String key = entry.getKey();
136  12 return entry.getValue().stream()
137    .map(value -> new FilteringCondition(sanitize(key), sanitize(value)));
138    }
139   
 
140  38 toggle private static String sanitize(String text) {
141  38 String trimmedText = text.trim();
142  38 return trimmedText.replaceAll("'", "''");
143    }
144   
 
145  10 toggle public QueryBuilder orderBy(List<String> propertiesToOrder) {
146  10 this.propertiesToOrder = propertiesToOrder;
147  10 return this;
148    }
149   
 
150  2 toggle public QueryBuilder offset(long offset) {
151  2 this.offset = offset;
152  2 return this;
153    }
154   
 
155  2 toggle public QueryBuilder limit(long limit) {
156  2 this.limit = limit;
157  2 return this;
158    }
159   
 
160  32 toggle public Query build() {
161  32 StringBuilder statement = new StringBuilder(SELECT_TEMPLATE);
162  32 try {
163    // Collect condition clauses.
164  32 List<String> conditionClauses = new ArrayList<>();
165  32 conditionClauses.add(getWhereClauseForNodeTypes());
166  32 conditionClauses.add(getWhereClauseWorkspacePath());
167  32 conditionClauses.add(getWhereClauseForSearch());
168  32 conditionClauses.addAll(getWhereClausesForFiltering());
169   
170    // Remove empty clauses.
171  32 List<String> clauses = conditionClauses.stream()
172    .filter(clause -> !clause.isEmpty())
173    .collect(toList());
174   
175    // Append condition clauses.
176  32 statement.append(clauses.isEmpty() ? "" : " WHERE ");
177  32 statement.append(clauses.stream()
178    .map(clause -> "(" + clause + ")")
179    .collect(joining(" AND ")));
180   
181  32 if (!CollectionUtils.isEmpty(propertiesToOrder)) {
182  8 statement.append(getOrderByClause());
183    }
184   
185    // Get query and set offset and limit.
186  32 QueryManager jcrQueryManager = workspace.getQueryManager();
187  32 Query query = jcrQueryManager.createQuery(statement.toString(), Query.JCR_SQL2);
188   
189  30 if (offset > 0) {
190  0 query.setOffset(offset);
191    }
192  30 if (limit > 0) {
193  2 query.setLimit(limit);
194    }
195   
196  30 log.debug("SQL statement is {}", query.getStatement());
197  30 return query;
198   
199    } catch (RepositoryException e) {
200  2 throw new RuntimeRepositoryException(e);
201    }
202    }
203   
 
204  8 toggle private String getOrderByClause() {
205  8 StringBuilder orderByBuilder = new StringBuilder(ORDER_BY);
206  8 for (String propertyToOrder : propertiesToOrder) {
207  10 String[] tokens = propertyToOrder.split(" ");
208  10 String property = tokens[0];
209  10 String direction = "";
210   
211  10 if (tokens.length > 1) {
212  8 direction = tokens[1];
213    }
214   
215  10 if (JCR_NAME.equalsIgnoreCase(property)) {
216  3 orderByBuilder.append(String.format("%s %s, ", JCR_NAME_FUNCTION, direction));
217    } else {
218  7 orderByBuilder.append(String.format("%s.[%s] %s, ", SELECTOR_NAME, property, direction));
219    }
220    }
221   
222  8 return StringUtils.removeEnd(orderByBuilder.toString(), ", ");
223    }
224   
 
225  32 toggle private String getWhereClauseForNodeTypes() {
226  32 return nodeTypes.stream()
227    .map(this::getNodeType)
228    .filter(nodeType -> !nodeType.isNodeType(NodeTypes.Folder.NAME))
229    .map(this::getConditionBasedOnNodeType)
230    .collect(joining(" OR "));
231    }
232   
 
233  24 toggle private NodeType getNodeType(String nodeTypeStr) {
234  24 try {
235  24 NodeTypeManager nodeTypeManager = workspace.getNodeTypeManager();
236  24 return nodeTypeManager.getNodeType(nodeTypeStr);
237    } catch (RepositoryException e) {
238  0 throw new RuntimeRepositoryException(e);
239    }
240    }
241   
 
242  23 toggle private String getConditionBasedOnNodeType(NodeType nodeType) {
243  23 if (nodeType.isMixin()) {
244  0 return String.format("[jcr:mixinTypes] = '%s'", nodeType.getName());
245    }
246  23 return String.format("[jcr:primaryType] = '%s'", nodeType.getName());
247    }
248   
 
249  32 toggle private String getWhereClauseWorkspacePath() {
250  32 return StringUtils.isNotBlank(rootPath) && !"/".equals(rootPath) ? String.format(WHERE_TEMPLATE_FOR_PATH, rootPath) : "";
251    }
252   
 
253  32 toggle private String getWhereClauseForSearch() {
254  32 if (StringUtils.isBlank(keyword)) {
255  26 return "";
256    }
257   
258  6 String lowercaseText = keyword.toLowerCase();
259  6 String jcrCharsEscapedText = Text.escapeIllegalJcrChars(lowercaseText);
260  6 String singleQuoteEscapedText = sanitize(jcrCharsEscapedText);
261  6 String escapedFullTextExpression = escapeFullTextExpression(lowercaseText);
262   
263    // The given search query string starts with "/" is considered as abs path.
264  6 if (Paths.get(escapedFullTextExpression).isAbsolute()) {
265  1 String rootPath = this.rootPath;
266   
267  1 if (StringUtils.isEmpty(rootPath) || "/".equals(rootPath) || escapedFullTextExpression.startsWith(rootPath)) {
268  1 rootPath = "";
269    }
270   
271  1 return String.format(JCR_IS_SAME_NODE_FUNCTION, rootPath + escapedFullTextExpression);
272    }
273  5 return String.format(WHERE_TEMPLATE_FOR_SEARCH, singleQuoteEscapedText) + String.format(" OR " + CONTAINS_TEMPLATE_FOR_SEARCH, escapedFullTextExpression);
274    }
275   
276    /**
277    * See http://wiki.apache.org/jackrabbit/EncodingAndEscaping.
278    * Copied over from {@link info.magnolia.ui.workbench.search.SearchJcrContainer}.
279    */
 
280  6 toggle private String escapeFullTextExpression(String fulltextExpression) {
281  6 List<String> matchList = findSimpleTerms(fulltextExpression);
282   
283  6 List<String> simpleTerms = new ArrayList<>();
284  6 for (String token : matchList) {
285  6 simpleTerms.add(escapeIllegalFullTextSearchChars(token));
286    }
287    // Workaround as our regex does not match one single double quote ["].
288  6 if ("\"".equals(fulltextExpression)) {
289  0 simpleTerms.add("\\\"");
290    }
291   
292  6 return sanitize(simpleTerms.stream().collect(joining(" ")));
293    }
294   
295    /**
296    * @return a list of simple terms according to JCR 2.0 definition, i.e. SimpleTerm ::= Word | '"' Word {Space Word} '"'
297    * (See http://www.day.com/specs/jcr/2.0/6_Query.html#6.7.19%20FullTextSearch)
298    * Copied over from {@link info.magnolia.ui.workbench.search.SearchJcrContainer}.
299    */
 
300  6 toggle private List<String> findSimpleTerms(String unescapedFullTextExpression) {
301  6 List<String> matchList = new LinkedList<>();
302  6 Matcher regexMatcher = simpleTermsRegexPattern.matcher(unescapedFullTextExpression);
303  12 while (regexMatcher.find()) {
304  6 matchList.add(regexMatcher.group());
305    }
306  6 return matchList;
307    }
308   
309    /**
310    * Within a term, each sensitive char must be escaped by a preceding “\”.<br>
311    * - “-” (minus sign), “+” (plus sign) and “\” (backslash) are escaped if they are the single element of the term <br>
312    * - "()[]{}" (all brackets) are always escaped<br>
313    * - “"” (double quote) is always escape unless it delimits a simple term, i.e <code>"foo -bar"</code><br>
314    * <strong>This method has package visibility for testing purposes.</strong>
315    * Copied over from {@link info.magnolia.ui.workbench.search.SearchJcrContainer}.
316    */
 
317  6 toggle private String escapeIllegalFullTextSearchChars(String simpleTerm) {
318  6 StringBuilder sb = new StringBuilder(simpleTerm.length());
319   
320  78 for (int i = 0; i < simpleTerm.length(); i++) {
321  72 char ch = simpleTerm.charAt(i);
322  72 if (("\\+-".contains(String.valueOf(ch)) && simpleTerm.length() == 1)
323    || ("()[]{}".contains(String.valueOf(ch)))
324    || ("\"".contains(String.valueOf(ch)) && (i != 0 && i != simpleTerm.length() - 1))) {
325  2 sb.append('\\');
326    }
327  72 sb.append(ch);
328    }
329  6 return sb.toString();
330    }
331   
 
332  32 toggle private List<String> getWhereClausesForFiltering() {
333  32 return filteringConditions.stream()
334    .map(FilteringCondition::asSqlString)
335    .collect(toList());
336    }
337    }