001/*
002 *  Copyright 2018 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.advanced;
017
018import java.util.Collection;
019import java.util.function.Function;
020import java.util.stream.Collectors;
021import java.util.stream.Stream;
022
023import org.apache.avalon.framework.component.Component;
024
025import org.ametys.cms.search.query.AndQuery;
026import org.ametys.cms.search.query.OrQuery;
027import org.ametys.cms.search.query.Query;
028import org.ametys.cms.search.query.Query.LogicalOperator;
029import org.ametys.runtime.plugin.component.AbstractLogEnabled;
030
031/**
032 * Builds a {@link Query} object from advanced search criteria (as a {@link AbstractTreeNode}).
033 */
034public class AdvancedQueryBuilder extends AbstractLogEnabled implements Component
035{
036    /** The component role. */
037    public static final String ROLE = AdvancedQueryBuilder.class.getName();
038    
039    /**
040     * Builds the {@link Query} object represented by the given tree of advanced search criteria.
041     * @param <T> the type of the values of the leaves of the given tree
042     * @param tree The tree
043     * @param queryMapper The mapper to build a Query from a {@link TreeLeaf leaf}
044     * @return the built query of the {@link AbstractTreeNode tree}
045     */
046    public <T> Query build(AbstractTreeNode<T> tree, Function<T, Query> queryMapper)
047    {
048        return AbstractTreeNode.walk(tree, 
049            // leaf => get the value of the leaf, apply the mapper to have the leaf Query
050            leaf -> queryMapper.apply(leaf.getValue()),
051            // internalNode => build the logical (OR | AND) query of the internal node
052            (queries, operator) -> _logicalQuery(queries, operator));
053    }
054    
055    private Query _logicalQuery(Stream<Query> queries, LogicalOperator operator)
056    {
057        Collection<Query> queriesAsCol = queries.collect(Collectors.toList());
058        return operator == LogicalOperator.AND ? new AndQuery(queriesAsCol) : new OrQuery(queriesAsCol);
059    }
060}