001/*
002 *  Copyright 2016 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.search.query.Query.Operator;
019
020/**
021 * Class providing helper methods to Query implementations.
022 */
023public final class QueryHelper
024{
025    
026    /** The special value testing that the field exists. */
027    public static final String EXISTS_VALUE = "[* TO *]";
028    
029    private QueryHelper()
030    {
031        // Hides the default constructor.
032    }
033    
034    /**
035     * Get a standard query on a value, with all possible standard operators.
036     * @param fieldName The field name.
037     * @param operator The operator.
038     * @param value The value, can be null if the operator is EXISTS.
039     * @return The standard value query.
040     */
041    public static final String getStandardQuery(String fieldName, Operator operator, Object value)
042    {
043        StringBuilder query = new StringBuilder();
044        
045        if (operator == Operator.NE)
046        {
047            query.append('-');
048        }
049        
050        query.append(fieldName).append(':');
051        
052        if (operator == Operator.EQ || operator == Operator.NE)
053        {
054            query.append(value);
055        }
056        else if (operator == Operator.GT)
057        {
058            query.append('{').append(value).append(" TO *]");
059        }
060        else if (operator == Operator.GE)
061        {
062            query.append('[').append(value).append(" TO *]");
063        }
064        else if (operator == Operator.LT)
065        {
066            query.append("[* TO ").append(value).append('}');
067        }
068        else if (operator == Operator.LE)
069        {
070            query.append("[* TO ").append(value).append(']');
071        }
072        else if (operator == Operator.EXISTS)
073        {
074            query.append(EXISTS_VALUE);
075        }
076        
077        return query.toString();
078    }
079    
080}