001/*
002 *  Copyright 2020 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.userdirectory.observation;
017
018import java.util.Map;
019import java.util.Optional;
020
021import org.apache.avalon.framework.service.ServiceException;
022import org.apache.avalon.framework.service.ServiceManager;
023import org.apache.avalon.framework.service.Serviceable;
024
025import org.ametys.core.observation.Event;
026import org.ametys.core.observation.Observer;
027import org.ametys.plugins.userdirectory.page.UserDirectoryPageResolver;
028import org.ametys.runtime.plugin.component.AbstractLogEnabled;
029import org.ametys.web.repository.page.Page;
030
031/**
032 * {@link Observer} when the user directory root is updated
033 * Clear the cache for getting user page
034 */
035public class UserPageCacheObserver extends AbstractLogEnabled implements Observer, Serviceable
036{
037    /** The user directory page resolver */
038    protected UserDirectoryPageResolver _userDirectoryPageResolver;
039    
040    public void service(ServiceManager manager) throws ServiceException
041    {
042        _userDirectoryPageResolver = (UserDirectoryPageResolver) manager.lookup(UserDirectoryPageResolver.ROLE);
043    }
044
045    public int getPriority()
046    {
047        // Will be processed after Solr update
048        return Observer.MAX_PRIORITY + 4000;
049    }
050
051    public boolean supports(Event event)
052    {
053        return event.getId().equals(ObservationConstants.EVENT_USER_DIRECTORY_ROOT_CHANGED)
054                || event.getId().equals(ObservationConstants.EVENT_USER_DIRECTORY_ROOT_DELETED)
055                || event.getId().equals(ObservationConstants.EVENT_USER_DIRECTORY_ROOT_UPDATED);
056    }
057
058    public void observe(Event event, Map<String, Object> transientVars) throws Exception
059    {
060        String lang = Optional.ofNullable(_getPage(event))
061                .map(Page::getSitemapName)
062                .orElse(null);
063        
064        _userDirectoryPageResolver.invalidateUserPageCache(lang);
065    }
066    
067    private Page _getPage(Event event)
068    {
069        return (Page) event.getArguments().get(org.ametys.web.ObservationConstants.ARGS_PAGE);
070    }
071}