001/*
002 *  Copyright 2010 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.plugins.repository.query;
017
018import org.apache.commons.lang.StringUtils;
019
020import org.ametys.plugins.repository.query.expression.Expression;
021
022/**
023 * Helper for creating JCR XPath queries.<br>
024 * Created XPath queries are like : <code>//element(*, ametys:object)[<i>&lt;predicates&lt;&gt;</i>]</code>
025 */
026public final class QueryHelper
027{
028    private QueryHelper()
029    {
030        // empty constructor
031    }
032    
033    /**
034     * Creates the XPath query corresponding to specified {@link Expression} and {@link SortCriteria}.
035     * @param namePattern a pattern for the name of the resulting nodes. May be null, which is equivalent to '*'
036     * @param nodetype the base nodetype for the query. May be null, which is equivalent to ametys:object
037     * @param expression the query predicates
038     * @param sortCriteria criteria for sorting results
039     * @return the created XPath query
040     */
041    public static String getXPathQuery(String namePattern, String nodetype, Expression expression, SortCriteria sortCriteria)
042    {
043        String predicats = null;
044        
045        if (expression != null)
046        {
047            predicats = StringUtils.trimToNull(expression.build());
048        }
049        
050        String type = nodetype == null ? "ametys:object" : nodetype;
051        String name = namePattern == null ? "*" : namePattern;
052        
053        String xpathQuery = "//element(" + name + ", " + type + ")" + (predicats != null ? "[" + predicats + "]" : "") + ((sortCriteria != null) ? (" " + sortCriteria.build()) : "");
054        return xpathQuery;
055    }
056
057    /**
058     * Creates the XPath query corresponding to specified {@link Expression}.
059     * @param namePattern a pattern for the name of the resulting nodes. May be null, which is equivalent to '*'
060     * @param nodetype the base nodetype for the query. May be null, which is equivalent to 'ametys:object'
061     * @param expression the query predicates
062     * @return the created XPath query
063     */
064    public static String getXPathQuery(String namePattern, String nodetype, Expression expression)
065    {
066        return getXPathQuery(namePattern, nodetype, expression, null);
067    }
068}