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