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.apache.commons.lang3.BooleanUtils;
019
020/**
021 * Represents a {@link Query} testing a boolean field.
022 */
023public class BooleanQuery extends AbstractOperatorQuery<Boolean>
024{
025    /**
026     * Build a BooleanQuery testing the existence of the field.
027     * @param fieldPath the field's path
028     */
029    public BooleanQuery(String fieldPath)
030    {
031        this(fieldPath, Operator.EXISTS, null);
032    }
033    
034    /**
035     * Build a BooleanQuery.
036     * @param fieldPath the field's path
037     * @param value the value.
038     */
039    public BooleanQuery(String fieldPath, Boolean value)
040    {
041        this(fieldPath, Operator.EQ, value);
042    }
043    
044    /**
045     * Build a BooleanQuery.
046     * @param fieldPath the field's path
047     * @param op the operator.
048     * @param value the value.
049     */
050    public BooleanQuery(String fieldPath, Operator op, Boolean value)
051    {
052        super(fieldPath + "_b", op, value);
053    }
054    
055    @Override
056    public String build() throws QuerySyntaxException
057    {
058        Operator operator = getOperator();
059        Boolean isTrue = BooleanUtils.isTrue(getValue());
060        
061        StringBuilder query = new StringBuilder();
062        
063        // "field != true" or "field == false" => test "not true".
064        boolean appendNegation = operator == Operator.NE && isTrue || operator == Operator.EQ && !isTrue; 
065        if (appendNegation)
066        {
067            NotQuery.appendNegation(query);
068        }
069        
070        query.append(getFieldName()).append(':')
071             .append(operator == Operator.EXISTS ? QueryHelper.EXISTS_VALUE : "true");
072        
073        return query.toString();
074    }
075}