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 java.util.ArrayList;
019import java.util.Arrays;
020import java.util.Collection;
021import java.util.Collections;
022import java.util.List;
023
024import org.apache.commons.lang3.StringUtils;
025
026/**
027 * Represents a search {@link Query} corresponding to the logical "or" between several other queries.
028 */
029public class OrQuery implements Query
030{
031    
032    /** The list of queries. */
033    protected List<Query> _queries;
034    
035    /**
036     * Build an OrQuery object.
037     * @param queries the queries.
038     */
039    public OrQuery(Query... queries)
040    {
041        _queries = Arrays.asList(queries);
042    }
043    
044    /**
045     * Build an OrQuery object.
046     * @param queries the queries as a Collection.
047     */
048    public OrQuery(Collection<Query> queries)
049    {
050        _queries = new ArrayList<>(queries);
051    }
052    
053    /**
054     * Get the list of queries in this "or".
055     * @return the list of queries.
056     */
057    public List<Query> getQueries()
058    {
059        return Collections.unmodifiableList(_queries);
060    }
061    
062    @Override
063    public String build() throws QuerySyntaxException
064    {
065        boolean isFirst = true;
066        StringBuilder sb = new StringBuilder("(");
067        
068        for (Query subQuery : _queries)
069        {
070            if (subQuery != null)
071            {
072                String exprAsString = subQuery.build();
073                if (StringUtils.isNotBlank(exprAsString))
074                {
075                    if (!isFirst)
076                    {
077                        sb.append(" OR ");
078                    }
079                    sb.append(exprAsString);
080                    isFirst = false;
081                }
082            }
083        }
084        
085        if (isFirst)
086        {
087            return "";
088        }
089        else
090        {
091            return sb.append(")").toString();
092        }
093    }
094    
095}