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.web.repository.page;
017
018import org.apache.commons.lang.StringUtils;
019import org.apache.jackrabbit.util.ISO9075;
020
021import org.ametys.plugins.repository.query.SortCriteria;
022import org.ametys.plugins.repository.query.expression.Expression;
023
024/**
025 * Helper for creating JCR XPath queries involving page predicate.
026 */
027public final class PageQueryHelper
028{
029    private PageQueryHelper()
030    {
031        // empty constructor
032    }
033    
034    /**
035     * Creates the XPath query corresponding to specified {@link Expression}.
036     * @param site the site or <code>null</code> for all sites.
037     * @param language the sitemap language or <code>null</code> for all sitemap languages.
038     * @param path the page path to search into or <code>null</code> for no filtering.
039     * @param pageExpression the query predicates.
040     * @param sortCriteria the sort criteria.
041     * @return the created XPath query.
042     */
043    public static String getPageXPathQuery(String site, String language, String path, Expression pageExpression, SortCriteria sortCriteria)
044    {
045        String predicats = null;
046        
047        if (pageExpression != null)
048        {
049            predicats = StringUtils.trimToNull(pageExpression.build());
050        }
051        
052        String siteName = site == null ? "*" : site;
053        
054        String xpathQuery = "//element(" + siteName + ", ametys:site)/ametys-internal:sitemaps/" 
055            + (language == null ? "*" : language)
056            + _encode(path) 
057            + "//element(*, ametys:page)" 
058            + (predicats != null ? "[" + predicats + "]" : "") 
059            + ((sortCriteria != null) ? (" " + sortCriteria.build()) : "");
060        return xpathQuery;
061    }
062    
063    private static String _encode(String path)
064    {
065        if (path == null || path.length() == 0)
066        {
067            return "";
068        }
069        
070        int pos = path.indexOf("/");
071        if (pos == -1)
072        {
073            return '/' + ISO9075.encode(path);
074        }
075        else
076        {
077            return '/' + ISO9075.encode(path.substring(0, pos)) + "/" + _encode(path.substring(pos + 1));
078        }
079    }
080}