001/* 002 * Copyright 2017 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; 017 018import java.util.ArrayList; 019import java.util.Collections; 020import java.util.HashMap; 021import java.util.LinkedHashSet; 022import java.util.List; 023import java.util.Map; 024import java.util.Objects; 025import java.util.Optional; 026import java.util.Set; 027 028import org.apache.avalon.framework.component.Component; 029import org.apache.avalon.framework.logger.AbstractLogEnabled; 030import org.apache.avalon.framework.service.ServiceException; 031import org.apache.avalon.framework.service.ServiceManager; 032import org.apache.avalon.framework.service.Serviceable; 033import org.apache.commons.lang3.StringUtils; 034 035import org.ametys.cms.search.content.ContentSearcherFactory.ContentSearchSort; 036import org.ametys.cms.search.model.SearchModel; 037import org.ametys.cms.search.model.SearchModelHelper; 038import org.ametys.cms.search.query.AndQuery; 039import org.ametys.cms.search.query.ContentTypeOrMixinTypeQuery; 040import org.ametys.cms.search.query.ContentTypeQuery; 041import org.ametys.cms.search.query.MixinTypeQuery; 042import org.ametys.cms.search.query.Query; 043import org.ametys.cms.search.query.Query.Operator; 044import org.ametys.cms.search.query.QuerySyntaxException; 045import org.ametys.cms.search.ui.model.SearchUIColumn; 046import org.ametys.core.util.JSONUtils; 047import org.ametys.runtime.model.ViewHelper; 048import org.ametys.runtime.model.ViewItem; 049import org.ametys.runtime.model.ViewItemAccessor; 050import org.ametys.runtime.model.ViewItemContainer; 051 052/** 053 * Helper to get query infos from JSON object 054 */ 055public class GetQueryFromJSONHelper extends AbstractLogEnabled implements Component, Serviceable 056{ 057 /** The Avalon role name */ 058 public static final String ROLE = GetQueryFromJSONHelper.class.getName(); 059 060 private QueryBuilder _queryBuilder; 061 private JSONUtils _jsonUtils; 062 private SearchModelHelper _searchModelHelper; 063 064 public void service(ServiceManager serviceManager) throws ServiceException 065 { 066 _queryBuilder = (QueryBuilder) serviceManager.lookup(QueryBuilder.ROLE); 067 _jsonUtils = (JSONUtils) serviceManager.lookup(JSONUtils.ROLE); 068 _searchModelHelper = (SearchModelHelper) serviceManager.lookup(SearchModelHelper.ROLE); 069 } 070 071 /** 072 * Retrieves the search UI model 073 * @param parameters The JS parameters 074 * @return the search UI model 075 */ 076 public SearchModel getSearchModel(Map<String, Object> parameters) 077 { 078 return getSearchModel(parameters, "model"); 079 } 080 081 /** 082 * Retrieves the search UI model 083 * @param parameters The JS parameters 084 * @param modelKeyName key name of the model parameter 085 * @return the search UI model 086 */ 087 @SuppressWarnings("unchecked") 088 public SearchModel getSearchModel(Map<String, Object> parameters, String modelKeyName) 089 { 090 String modelId = (String) parameters.get(modelKeyName); 091 Map<String, Object> contextualParameters = Optional.ofNullable((Map<String, Object>) parameters.get("contextualParameters")).orElse(new HashMap<>()); 092 return _searchModelHelper.getRestrictedSearchModel(modelId, contextualParameters); 093 } 094 095 /** 096 * Retrieves a Query object from the SearchUIModel and the JSON parameters 097 * @param model Model 098 * @param parameters JSON parameters 099 * @param contentTypes List of content types to fill 100 * @return the created Query object 101 * @throws QuerySyntaxException If an error occurs during the query parsing 102 */ 103 @SuppressWarnings("unchecked") 104 public Query getQueryFromModel(SearchModel model, Map<String, Object> parameters, List<String> contentTypes) throws QuerySyntaxException 105 { 106 Map<String, Object> contextualParameters = Optional.ofNullable((Map<String, Object>) parameters.get("contextualParameters")).orElseGet(HashMap::new); 107 108 Map<String, Object> values = (Map<String, Object>) parameters.get("values"); 109 String searchMode = Objects.toString(parameters.get("searchMode"), "simple"); 110 111 Query query = _queryBuilder.build(model, searchMode , values, contextualParameters); 112 Query extractedQuery = _extractContentTypesFromQuery(query, contentTypes); 113 114 // Use search model content type if no content type has been found in the query 115 if (contentTypes.isEmpty()) 116 { 117 Set<String> modelContentTypes = model.getContentTypes(contextualParameters); 118 contentTypes.addAll(modelContentTypes); 119 } 120 121 return extractedQuery; 122 } 123 124 private Query _extractContentTypesFromQuery(Query query, List<String> contentTypes) 125 { 126 Query newQuery = query; 127 if (query instanceof AndQuery andQuery) 128 { 129 boolean foundContentTypes = false; 130 131 Set<Query> subQueries = new LinkedHashSet<>(andQuery.getQueries()); 132 Query matchingQuery = _getFirstMatchingQuery(subQueries); 133 if (matchingQuery != null) 134 { 135 List<String> extractedContentTypes = _getContentTypesFromQuery(matchingQuery); 136 if (!extractedContentTypes.isEmpty()) 137 { 138 contentTypes.addAll(extractedContentTypes); 139 foundContentTypes = true; 140 141 // Change the query by putting the same AndQuery but without the part about contentTypes which are in the contentTypes field 142 subQueries.remove(matchingQuery); 143 newQuery = new AndQuery(subQueries); 144 } 145 } 146 147 if (!foundContentTypes) 148 { 149 // No content types query has been found => check recursively in sub-sub-queries 150 Set<Query> newSubQueries = new LinkedHashSet<>(); 151 for (Query subQuery : subQueries) 152 { 153 Query newSubQuery = _extractContentTypesFromQuery(subQuery, contentTypes); 154 newSubQueries.add(newSubQuery); 155 } 156 157 newQuery = new AndQuery(newSubQueries); 158 } 159 } 160 161 return newQuery; 162 } 163 164 private Query _getFirstMatchingQuery(Set<Query> queries) 165 { 166 // Find the first `ContentTypeQuery` with EQ operator 167 Optional<? extends Query> contentTypeQuery = queries.stream() 168 .filter(ContentTypeQuery.class::isInstance) 169 .map(ContentTypeQuery.class::cast) 170 .filter(query -> Operator.EQ.equals(query.getOperator())) 171 .findFirst(); 172 if (contentTypeQuery.isPresent()) 173 { 174 return contentTypeQuery.get(); 175 } 176 177 // Find the first `ContentTypeOrMixinTypeQuery` with EQ operator 178 contentTypeQuery = queries.stream() 179 .filter(ContentTypeOrMixinTypeQuery.class::isInstance) 180 .map(ContentTypeOrMixinTypeQuery.class::cast) 181 .filter(query -> Operator.EQ.equals(query.getOperator())) 182 .findFirst(); 183 if (contentTypeQuery.isPresent()) 184 { 185 return contentTypeQuery.get(); 186 } 187 188 // Find the first `MixinTypeQuery` with EQ operator 189 contentTypeQuery = queries.stream() 190 .filter(MixinTypeQuery.class::isInstance) 191 .map(MixinTypeQuery.class::cast) 192 .filter(query -> Operator.EQ.equals(query.getOperator())) 193 .findFirst(); 194 return contentTypeQuery.orElse(null); 195 } 196 197 private List<String> _getContentTypesFromQuery(Query query) 198 { 199 List<String> contentTypes = new ArrayList<>(); 200 201 if (query instanceof ContentTypeQuery cTypeQuery) 202 { 203 contentTypes.addAll(cTypeQuery.getValue()); 204 } 205 else if (query instanceof ContentTypeOrMixinTypeQuery cTypeOrMixinQuery) 206 { 207 contentTypes.addAll(cTypeOrMixinQuery.getIds()); 208 } 209 else if (query instanceof MixinTypeQuery mixinQuery) 210 { 211 contentTypes.addAll(mixinQuery.getValue()); 212 } 213 214 return contentTypes; 215 } 216 217 /** 218 * Retrieves a list of column ids 219 * @param model search model containing result fields 220 * @param contextualParameters JSON object containing the contextual parameters 221 * @return a list of columns ids 222 */ 223 public List<String> getColumnsFromSearchModel(SearchModel model, Map<String, Object> contextualParameters) 224 { 225 ViewItemContainer resultItems = model.getResultItems(contextualParameters != null ? contextualParameters : Collections.EMPTY_MAP); 226 return _getColumnIds(resultItems); 227 } 228 229 private List<String> _getColumnIds(ViewItemAccessor viewItemAccessor) 230 { 231 List<String> columnIds = new ArrayList<>(); 232 233 for (ViewItem viewItem : viewItemAccessor.getViewItems()) 234 { 235 if (viewItem instanceof SearchUIColumn searchUIColumn) 236 { 237 String columnId = ViewHelper.getModelViewItemPath(searchUIColumn); 238 columnIds.add(columnId); 239 } 240 else if (viewItem instanceof ViewItemAccessor itemAccessor) 241 { 242 columnIds.addAll(_getColumnIds(itemAccessor)); 243 } 244 } 245 246 return columnIds; 247 } 248 249 /** 250 * Retrieves the sort criteria from a sort string. 251 * @param parameters The parameters (containing sort and optionally group keys) 252 * @return the sort criteria as a List of {@link ContentSearchSort}. 253 */ 254 public List<ContentSearchSort> getSort(Map<String, Object> parameters) 255 { 256 String sortString = (String) parameters.get("sort"); 257 String groupString = (String) parameters.get("group"); 258 return getSort(sortString, groupString); 259 } 260 261 /** 262 * Retrieves the sort criteria from a sort string. 263 * @param sortString The sort criteria as a JSON-encoded string. 264 * @param groupString The group criteria as a JSON-encoded string (for server-side grouping feature). Can be null. 265 * @return the sort criteria as a List of {@link ContentSearchSort}. 266 */ 267 public List<ContentSearchSort> getSort(String sortString, String groupString) 268 { 269 List<ContentSearchSort> sort = new ArrayList<>(); 270 271 List<Object> sortList = new ArrayList<>(_jsonUtils.convertJsonToList(sortString)); 272 if (StringUtils.isNotEmpty(groupString)) 273 { 274 // Grouping will be treated server side as a sort. It just needs to be before all the sorters 275 sortList.add(0, _jsonUtils.convertJsonToMap(groupString)); 276 } 277 278 for (Object object : sortList) 279 { 280 if (object instanceof Map) 281 { 282 Map map = (Map) object; 283 String fieldId = (String) map.get("property"); 284 boolean ascending = "ASC".equals(map.get("direction")); 285 286 sort.add(new ContentSearchSort(fieldId, ascending ? SortOrder.ASC : SortOrder.DESC)); 287 } 288 } 289 290 return sort; 291 } 292} 293