001/* 002 * Copyright 2025 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.model; 017 018import java.util.Locale; 019import java.util.Objects; 020import java.util.Optional; 021 022import org.apache.avalon.framework.component.Component; 023import org.apache.avalon.framework.context.Context; 024import org.apache.avalon.framework.context.ContextException; 025import org.apache.avalon.framework.context.Contextualizable; 026import org.apache.cocoon.components.ContextHelper; 027 028import org.ametys.cms.data.type.indexing.SortableIndexableElementType; 029import org.ametys.cms.search.cocoon.SearchAction; 030import org.ametys.runtime.model.type.DataContext; 031 032/** 033 * Helper for indexation aware element definitions 034 */ 035public class IndexationAwareElementDefinitionHelper implements Component, Contextualizable 036{ 037 /** The component role. */ 038 public static final String ROLE = IndexationAwareElementDefinitionHelper.class.getName(); 039 040 /** The avalon context */ 041 private Context _context; 042 043 public void contextualize(Context context) throws ContextException 044 { 045 _context = context; 046 } 047 048 /** 049 * Retrieves the default name of the definition's solr sort field 050 * @param definition the definition 051 * @return the name of the definition's solr sort field 052 */ 053 public String getDefaultSolrSortFieldName(IndexationAwareElementDefinition definition) 054 { 055 if (definition.getType() instanceof SortableIndexableElementType sortableType) 056 { 057 Locale locale = Optional.ofNullable(_context) 058 .map(c -> { 059 try 060 { 061 return ContextHelper.getRequest(c); 062 } 063 catch (RuntimeException e) 064 { 065 return null; 066 } 067 }) 068 .filter(Objects::nonNull) 069 .map(r -> r.getAttribute(SearchAction.SEARCH_LOCALE)) 070 .filter(Locale.class::isInstance) 071 .map(Locale.class::cast) 072 .orElse(null); 073 074 DataContext context = DataContext.newInstance() 075 .withModelItem(definition) 076 .withLocale(locale); 077 078 return definition.getName() + sortableType.getSortFieldSuffix(context); 079 } 080 else 081 { 082 return null; 083 } 084 } 085}