001/*
002 *  Copyright 2020 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.web.frontoffice.search.requesttime.impl;
017
018import java.util.Collections;
019import java.util.HashMap;
020import java.util.List;
021import java.util.Map;
022import java.util.Optional;
023import java.util.stream.Collectors;
024
025import org.apache.avalon.framework.parameters.Parameters;
026import org.apache.avalon.framework.service.ServiceException;
027import org.apache.avalon.framework.service.ServiceManager;
028import org.apache.avalon.framework.service.Serviceable;
029import org.apache.cocoon.xml.AttributesImpl;
030import org.apache.cocoon.xml.XMLUtils;
031import org.xml.sax.ContentHandler;
032import org.xml.sax.SAXException;
033
034import org.ametys.cms.search.SearchResults;
035import org.ametys.cms.search.advanced.AbstractTreeNode;
036import org.ametys.cms.search.advanced.TreeLeaf;
037import org.ametys.cms.search.content.ContentSearchHelper;
038import org.ametys.cms.search.solr.SearcherFactory;
039import org.ametys.cms.search.solr.SearcherFactory.Searcher;
040import org.ametys.core.right.RightManager;
041import org.ametys.plugins.repository.AmetysObject;
042import org.ametys.runtime.i18n.I18nizableText;
043import org.ametys.web.frontoffice.search.instance.SearchServiceInstance;
044import org.ametys.web.frontoffice.search.instance.model.SearchServiceCriterion;
045import org.ametys.web.frontoffice.search.metamodel.SearchServiceCriterionDefinition;
046import org.ametys.web.frontoffice.search.metamodel.SearchServiceFacetDefinition;
047import org.ametys.web.frontoffice.search.metamodel.impl.ContentFacetDefinition;
048import org.ametys.web.frontoffice.search.metamodel.impl.ReferencingSearchServiceCriterionDefinition;
049import org.ametys.web.frontoffice.search.requesttime.AbstractSearchComponent;
050import org.ametys.web.frontoffice.search.requesttime.SearchComponent;
051import org.ametys.web.frontoffice.search.requesttime.SearchComponentArguments;
052import org.ametys.web.frontoffice.search.requesttime.input.impl.FormSearchUserInputs;
053
054/**
055 * {@link SearchComponent} for saxing number of results for each values of enumerated criteria
056 */
057public class SaxEnumeratedCriteriaComponent extends AbstractSearchComponent implements Serviceable
058{
059    /** The searcher factory */
060    protected SearcherFactory _searcherFactory;
061    
062    /** The helper for search component */
063    protected SearchComponentHelper _searchComponentHelper;
064    
065    /** The right manager */
066    protected RightManager _rightManager;
067    
068    /** The content search helper */
069    protected ContentSearchHelper _contentSearchHelper;
070    
071    public void service(ServiceManager manager) throws ServiceException
072    {
073        _searcherFactory = (SearcherFactory) manager.lookup(SearcherFactory.ROLE);
074        _searchComponentHelper = (SearchComponentHelper) manager.lookup(SearchComponentHelper.ROLE);
075        _rightManager = (RightManager) manager.lookup(RightManager.ROLE);
076        _contentSearchHelper = (ContentSearchHelper) manager.lookup(ContentSearchHelper.ROLE);
077    }
078    
079    @Override
080    public int getPriority()
081    {
082        return SEARCH_PRIORITY + 2500;
083    }
084
085    @Override
086    public boolean supports(SearchComponentArguments args)
087    {
088        return args.serviceInstance().computeCriteriaCounts();
089    }
090
091    @Override
092    public void execute(SearchComponentArguments args) throws Exception
093    {
094        ContentHandler contentHandler = args.contentHandler();
095        XMLUtils.startElement(contentHandler, "enumerated-criteria");
096        
097        SearchServiceInstance serviceInstance = args.serviceInstance();
098        
099        // Transform each enumerated criteria in facet definition to have the number of result for each enumerated values
100        Map<SearchServiceFacetDefinition, SearchServiceCriterion> serviceFacets = _getFacetDefinitions(serviceInstance);
101        if (!serviceFacets.isEmpty())
102        {
103            Searcher searcher = _searcherFactory.cloneSearcher(args.searcher());
104            
105            // Add criterion query without user's inputs
106            searcher.withQuery(_searchComponentHelper.getCriterionTreeQuery(serviceInstance, Map.of(), args.currentSite(), args.currentLang()));
107            
108            // Add filter query (filter query is already added in the searcher only if the search is launched, so force it to be added here to have the same results as the search)
109            searcher.addFilterQuery(_searchComponentHelper.getFilterQuery(args));
110
111            // Use enumerated criteria as facets
112            searcher.withFacets(serviceFacets.keySet().stream()
113                    .map(SearchServiceFacetDefinition::getFacetDefinition)
114                    .collect(Collectors.toList()));
115            
116            // Remove limits to get all results for enumerated criteria
117            searcher.withLimits(0, Integer.MAX_VALUE);
118            
119            // Launch search with facets
120            SearchResults<AmetysObject> results = searcher.searchWithFacets();
121            args.setEnumeratedResults(results);
122            
123            // Sax the number of result for each values of enumerated criteria
124            Map<String, Object> contextualParameters = SearchComponentHelper.getSearchComponentContextualParameters(args);
125            _saxCountEnumeratedCriteria(contentHandler, args.generatorParameters(), serviceFacets, results, contextualParameters);
126        }
127        
128        XMLUtils.endElement(contentHandler, "enumerated-criteria");
129    }
130    
131    /**
132     * Transform each enumerated criteria in facet definition to have the number of result for each enumerated values
133     * @param serviceInstance the service instance
134     * @return the collection of facet definition
135     */
136    @SuppressWarnings("unchecked")
137    protected Map<SearchServiceFacetDefinition, SearchServiceCriterion> _getFacetDefinitions(SearchServiceInstance serviceInstance)
138    {
139        Map<SearchServiceFacetDefinition, SearchServiceCriterion> facets = new HashMap<>();
140        List<SearchServiceCriterion> criteria = serviceInstance.getCriterionTree()
141                                                               .map(AbstractTreeNode::getFlatLeaves)
142                                                               .orElseGet(Collections::emptyList)
143                                                               .stream()
144                                                               .map(TreeLeaf::getValue)
145                                                               .filter(c -> !c.getMode().isStatic())
146                                                               .collect(Collectors.toList());
147        
148        for (SearchServiceCriterion<?> criterion : criteria)
149        {
150            Optional.of(criterion.getCriterionDefinition())
151                    .filter(criterionDefinition -> criterionDefinition.getSolrFacetFieldName(new HashMap<>()) != null)
152                    .filter(ReferencingSearchServiceCriterionDefinition.class::isInstance)
153                    .map(ReferencingSearchServiceCriterionDefinition.class::cast)
154                    .map(critDef -> new ContentFacetDefinition(critDef, null, _contentSearchHelper))
155                    .ifPresent(facet -> facets.put(facet, criterion));
156        }
157        
158        return facets;
159    }
160    
161    /**
162     * SAX the enumerated criteria
163     * @param contentHandler the content handler
164     * @param parameters the parameters
165     * @param facets The facets
166     * @param searchResults The search results
167     * @param contextualParameters The contextual parameters
168     * @throws SAXException if an error occurs while generating SAX events
169     */
170    protected void _saxCountEnumeratedCriteria(ContentHandler contentHandler, Parameters parameters, Map<SearchServiceFacetDefinition, SearchServiceCriterion> facets, SearchResults<AmetysObject> searchResults, Map<String, Object> contextualParameters) throws SAXException
171    {
172        Map<String, Integer> valuesForCurrentFacetDef = Collections.EMPTY_MAP;
173        Map<String, Map<String, Integer>> facetResults = searchResults.getFacetResults();
174        
175        for (SearchServiceFacetDefinition facet : facets.keySet())
176        {
177            SearchServiceCriterion<?> criterion = facets.get(facet);
178            contextualParameters.put("criterion", criterion);
179
180            String id = facet.getName();
181            String name = FormSearchUserInputs.FACET_PREFIX + id;
182            AttributesImpl attrs = new AttributesImpl();
183            attrs.addCDATAAttribute("name", name);
184            if (facetResults.containsKey(id))
185            {
186                valuesForCurrentFacetDef = _getFacetValues(facetResults.get(id), criterion, contextualParameters);
187            }
188            attrs.addCDATAAttribute("total", String.valueOf(valuesForCurrentFacetDef.values()
189                    .stream()
190                    .mapToInt(Integer::intValue)
191                    .sum()));
192            
193            XMLUtils.startElement(contentHandler, "criterion", attrs);
194            facet.getLabel().toSAX(contentHandler, "label");
195            _saxFacetItemsWithCount(contentHandler, facet, valuesForCurrentFacetDef, contextualParameters);
196            XMLUtils.endElement(contentHandler, "criterion");
197        }
198    }
199    
200    /**
201     * Retrieves the values of the current facet
202     * @param facetResult the result of the current facet
203     * @param criterion the criterion corresponding to the current facet
204     * @param contextualParameters the contextual parameters
205     * @param <T> Type of the criterion value
206     * @return the values of the current facet
207     */
208    protected <T> Map<String, Integer> _getFacetValues(Map<String, Integer> facetResult, SearchServiceCriterion<T> criterion, Map<String, Object> contextualParameters)
209    {
210        SearchServiceCriterionDefinition<T> criterionDefinition = criterion.getCriterionDefinition();
211        Map<String, Integer> valuesForCurrentFacetDef = new HashMap<>();
212        
213        for (Map.Entry<String, Integer> facetResultEntry : facetResult.entrySet())
214        {
215            String facetResultValue = facetResultEntry.getKey();
216            Integer facetResultCount = facetResultEntry.getValue();
217            
218            String value = criterionDefinition.facetValueToSAX(facetResultValue, contextualParameters);
219            valuesForCurrentFacetDef.put(value, facetResultCount);
220        }
221        
222        return valuesForCurrentFacetDef;
223    }
224    
225    /**
226     * SAX the facet items with the count
227     * @param contentHandler the content handler
228     * @param facet the facet definition
229     * @param valuesForCurrentFacetDef The values for the current facet definition
230     * @param contextualParameters The contextual parameters
231     * @throws SAXException if an error occurs while generating SAX events
232     */
233    protected void _saxFacetItemsWithCount(ContentHandler contentHandler, SearchServiceFacetDefinition facet, Map<String, Integer> valuesForCurrentFacetDef, Map<String, Object> contextualParameters) throws SAXException
234    {
235        for (String value : valuesForCurrentFacetDef.keySet())
236        {
237            Integer count = valuesForCurrentFacetDef.get(value);
238            Optional<I18nizableText> facetLabel = facet.getFacetLabel(value, contextualParameters);
239            if (facetLabel.isPresent())
240            {
241                _saxFacetItemWithCount(contentHandler, facetLabel.get(), value, count);
242            }
243        }
244    }
245    
246    /**
247     * SAX the facet item with the count
248     * @param contentHandler the content handler
249     * @param facetLabel the facet label
250     * @param value the value for the current facet item
251     * @param count the value count
252     * @throws SAXException if an error occurs while generating SAX events
253     */
254    protected void _saxFacetItemWithCount(ContentHandler contentHandler, I18nizableText facetLabel, String value, Integer count) throws SAXException
255    {
256        AttributesImpl valueAttrs = new AttributesImpl();
257        valueAttrs.addCDATAAttribute("value", value);
258        valueAttrs.addCDATAAttribute("count", String.valueOf(count));
259        
260        XMLUtils.startElement(contentHandler, "item", valueAttrs);
261        facetLabel.toSAX(contentHandler);
262        XMLUtils.endElement(contentHandler, "item");
263    }
264}