001/*
002 *  Copyright 2014 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.cms.search.query;
017
018import org.ametys.cms.content.indexing.solr.SolrFieldNames;
019
020/**
021 * Represents a {@link Query} testing if contents have comments.
022 */
023public class CommentQuery implements Query
024{
025    
026    private boolean _includeValidated;
027    private boolean _includeNonValidated;
028    
029    /**
030     * Constructor. Parameters can not be both false.
031     * @param includeValidated will request contents with validated comments 
032     * @param includeNonValidated will request contents with non validated comments 
033     */
034    public CommentQuery(boolean includeValidated, boolean includeNonValidated)
035    {
036        this._includeValidated = includeValidated;
037        this._includeNonValidated = includeNonValidated;
038        
039        if (!includeValidated && !includeNonValidated)
040        {
041            throw new IllegalArgumentException("Can not create a comment expression to search for no comments");
042        }
043    }
044    
045    /**
046     * Get the includeValidated.
047     * @return the includeValidated
048     */
049    public boolean includeValidated()
050    {
051        return _includeValidated;
052    }
053    
054    /**
055     * Get the includeNonValidated.
056     * @return the includeNonValidated
057     */
058    public boolean includeNonValidated()
059    {
060        return _includeNonValidated;
061    }
062    
063    @Override
064    public String build() throws QuerySyntaxException
065    {
066        StringBuilder query = new StringBuilder();
067        
068        if (this._includeValidated && this._includeNonValidated)
069        {
070            query.append(SolrFieldNames.CONTENT_COMMENTS).append(":true");
071        }
072        else if (this._includeValidated)
073        {
074            query.append(SolrFieldNames.CONTENT_COMMENTS_VALIDATED).append(":true");
075        }
076        else if (this._includeNonValidated)
077        {
078            query.append(SolrFieldNames.CONTENT_COMMENTS_NONVALIDATED).append(":true");
079        }
080        else
081        {
082            query.append('-').append(SolrFieldNames.CONTENT_COMMENTS).append(":true");
083        }
084        
085        return query.toString();
086    }
087    
088}