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 java.util.Date;
019
020/**
021 * Represents a {@link Query} testing a date range.
022 */
023public class DateRangeQuery extends AbstractFieldQuery
024{
025    
026    /** The lower end of the date range. */
027    protected Date _from;
028    /** The upper end of the date range. */
029    protected Date _to;
030    /** True to include the lower end, false to exclude it. */
031    protected boolean _includeFrom;
032    /** True to include the upper end, false to exclude it. */
033    protected boolean _includeTo;
034    
035    /**
036     * Build a date range query.
037     * @param fieldPath The field path.
038     * @param from The lower end of the range.
039     * @param to The upper end of the range.
040     */
041    public DateRangeQuery(String fieldPath, Date from, Date to)
042    {
043        this(fieldPath, from, to, true, true);
044    }
045    
046    /**
047     * Build a date range query.
048     * @param fieldPath The field path.
049     * @param from The lower end of the range.
050     * @param to The upper end of the range.
051     * @param includeFrom Whether to include the lower end or not.
052     * @param includeTo Whether to include the upper end or not.
053     */
054    public DateRangeQuery(String fieldPath, Date from, Date to, boolean includeFrom, boolean includeTo)
055    {
056        super(fieldPath);
057        _from = from;
058        _to = to;
059        _includeFrom = includeFrom;
060        _includeTo = includeTo;
061    }
062    
063    @Override
064    public String build() throws QuerySyntaxException
065    {
066        String fromStr = DateQuery.DATE_FORMAT.format(_from);
067        String toStr = DateQuery.DATE_FORMAT.format(_to);
068        
069        StringBuilder query = new StringBuilder();
070        
071        query.append(_fieldPath).append("_dt:")
072             .append(_includeFrom ? '[' : '{')
073             .append(fromStr).append(" TO ").append(toStr)
074             .append(_includeTo ? ']' : '}');
075        
076        return query.toString();
077    }
078
079}