001/*
002 *  Copyright 2021 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.workspaces.members.observers;
017
018import java.util.List;
019import java.util.Set;
020
021import org.apache.avalon.framework.service.ServiceException;
022import org.apache.avalon.framework.service.ServiceManager;
023
024import org.ametys.cms.repository.Content;
025import org.ametys.core.observation.Event;
026import org.ametys.core.observation.Observer;
027import org.ametys.plugins.userdirectory.UserDirectoryPageHandler;
028import org.ametys.plugins.workspaces.WorkspacesConstants;
029import org.ametys.web.cache.CacheInvalidationPolicy;
030import org.ametys.web.repository.page.Page;
031
032/**
033 * {@link Observer} to invalidate cache on front-office of a user content when a member was added or removed from a project
034 *
035 */
036public class InvalidateCacheOnMemberUpdatedObserver extends AbstractMemberObserver
037{
038    private CacheInvalidationPolicy _cachePolicy;
039    private UserDirectoryPageHandler _udPageHandler;
040    
041    @Override
042    public void service(ServiceManager smanager) throws ServiceException
043    {
044        super.service(smanager);
045        _cachePolicy = (CacheInvalidationPolicy) smanager.lookup(CacheInvalidationPolicy.class.getName());
046        _udPageHandler = (UserDirectoryPageHandler) smanager.lookup(UserDirectoryPageHandler.ROLE);
047    }
048    
049    @Override
050    public int getPriority(Event event)
051    {
052        // Will be processed after indexation
053        return MAX_PRIORITY + 4000;
054    }
055    
056    @Override
057    protected void _internalObserve(Event event, List<Content> userContents) throws Exception
058    {
059        Set<Page> rootPages = _udPageHandler.getUserDirectoryRootPages(WorkspacesConstants.MEMBER_CONTENT_TYPE_ID);
060        
061        for (Content userContent : userContents)
062        {
063            for (Page rootPage : rootPages)
064            {
065                try
066                {
067                    _cachePolicy.invalidateCacheOnContentModification(rootPage.getSite(), userContent);
068                }
069                catch (Exception e)
070                {
071                    getLogger().error("Unable to invalidate cache for user content " + userContent, e);
072                }
073            }
074        }
075    }
076}