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.web.frontoffice.search.metamodel.impl;
017
018import java.util.Collection;
019import java.util.Map;
020
021import org.ametys.cms.data.type.indexing.IndexableElementType;
022import org.ametys.cms.search.query.NotQuery;
023import org.ametys.cms.search.query.Query;
024import org.ametys.cms.search.query.Query.Operator;
025import org.ametys.runtime.model.type.ModelItemTypeConstants;
026import org.ametys.web.frontoffice.search.metamodel.SearchServiceCriterionDefinition;
027import org.ametys.web.search.query.SitemapQuery;
028
029/**
030 * {@link SearchServiceCriterionDefinition} proposing a criterion definition on the sitemap of the indexed document.
031 */
032public class SitemapCriterionDefinition extends AbstractSearchServiceCriterionDefinition<String>
033{
034    @SuppressWarnings("unchecked")
035    @Override
036    public IndexableElementType<String> getType()
037    {
038        String typeId = ModelItemTypeConstants.STRING_TYPE_ID;
039        return (IndexableElementType<String>) _getCriterionTypeExtensionPoint().getExtension(typeId);
040    }
041
042    @Override
043    public Query getQuery(Object value, Operator operator, Map<String, Object> allValues, String language, Map<String, Object> contextualParameters)
044    {
045        String[] sitemaps;
046        if (value instanceof String)
047        {
048            sitemaps = ((String) value).split(",");
049        }
050        else if (value instanceof Collection<?>)
051        {
052            sitemaps = ((Collection<?>) value)
053                    .stream()
054                    .filter(String.class::isInstance)
055                    .map(String.class::cast)
056                    .toArray(String[]::new);
057        }
058        else
059        {
060            throw new IllegalArgumentException("Not handled type of value: '" + value + "'");
061        }
062        
063        return new SitemapQuery(sitemaps);
064    }
065    
066    @Override
067    public Query getEmptyValueQuery(String language, Map<String, Object> contextualParameters)
068    {
069        Query existQuery = new SitemapQuery();
070        return new NotQuery(existQuery);
071    }
072}