001/*
002 *  Copyright 2016 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.plugins.ai.rights;
017
018import java.util.HashSet;
019import java.util.Set;
020
021import javax.jcr.RepositoryException;
022
023import org.apache.avalon.framework.service.ServiceException;
024import org.apache.avalon.framework.service.ServiceManager;
025
026import org.ametys.cms.repository.Content;
027import org.ametys.core.right.RightContextConvertor;
028import org.ametys.plugins.ai.search.CacheContentVersionChunk;
029import org.ametys.plugins.repository.AmetysObjectResolver;
030import org.ametys.plugins.repository.AmetysRepositoryException;
031import org.ametys.runtime.plugin.component.AbstractLogEnabled;
032import org.ametys.runtime.plugin.component.DeferredServiceable;
033
034/**
035 * This implementation converts a Chunk into its parent {@link Content}
036 */
037public class Chunk2ContentRightContextConvertor extends AbstractLogEnabled implements RightContextConvertor, DeferredServiceable
038{
039    private AmetysObjectResolver _ametysObjectResolver;
040
041    public void deferredService(ServiceManager manager) throws ServiceException
042    {
043        _ametysObjectResolver = (AmetysObjectResolver) manager.lookup(AmetysObjectResolver.ROLE);
044    }
045    
046    public Set<Object> convert(Object object)
047    {
048        Set<Object> convertedObjects = new HashSet<>();
049        
050        if (object instanceof CacheContentVersionChunk chunk)
051        {
052            try
053            {
054                Content content = _ametysObjectResolver.resolveById(chunk.getContentId());
055                convertedObjects.add(content);
056            }
057            catch (AmetysRepositoryException | RepositoryException e)
058            {
059                getLogger().warn("Could not resolve content for chunk {}", chunk.getId(), e);
060            }
061        }
062        
063        return convertedObjects;
064    }
065}