001/*
002 *  Copyright 2019 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.Objects;
019
020import org.apache.commons.lang3.StringUtils;
021import org.apache.solr.client.solrj.util.ClientUtils;
022
023/**
024 * Wraps another {@link Query}, but giving to each matching document a boosted score (scores are multiplied). 
025 */
026public class BoostedQuery implements Query
027{
028    private Query _query;
029    private float _boost;
030
031    /**
032     * Build a BoostedQuery object.
033     * @param query The wrapped query
034     * @param boost The boost
035     */
036    public BoostedQuery(Query query, float boost)
037    {
038        _query = query;
039        _boost = boost;
040    }
041    
042    @Override
043    public String build() throws QuerySyntaxException
044    {
045        StringBuilder sb = new StringBuilder()
046                .append("{!boost b=")
047                .append(_boost)
048                .append(" v=\"")
049                .append(ClientUtils.escapeQueryChars(_query.build()))
050                .append("\"}");
051        return sb.toString();
052    }
053    
054    @Override
055    public String toString(int indent)
056    {
057        final String thisLineIndent = StringUtils.repeat(' ', indent);
058        final int subIndent = indent + 2;
059        final String subLineIndent = StringUtils.repeat(' ', subIndent);
060        final String boost = subLineIndent + "[BOOST]" + _boost + "[/BOOST]";
061        final String q = subLineIndent + "[Q]\n" + _query.toString(subIndent + 2) + "\n" + subLineIndent + "[/Q]";
062        return thisLineIndent + "[BOOSTED]\n" + boost + "\n" + q + "\n" + thisLineIndent + "[/BOOSTED]";
063    }
064
065    @Override
066    public int hashCode()
067    {
068        return Objects.hash(_boost, _query);
069    }
070
071    @Override
072    public boolean equals(Object obj)
073    {
074        if (this == obj)
075        {
076            return true;
077        }
078        if (obj == null)
079        {
080            return false;
081        }
082        if (getClass() != obj.getClass())
083        {
084            return false;
085        }
086        BoostedQuery other = (BoostedQuery) obj;
087        return Float.floatToIntBits(_boost) == Float.floatToIntBits(other._boost) && Objects.equals(_query, other._query);
088    }
089}
090