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.core.cache;
017
018import java.util.Collections;
019import java.util.List;
020
021import org.apache.avalon.framework.service.ServiceException;
022import org.apache.avalon.framework.service.ServiceManager;
023import org.apache.avalon.framework.service.Serviceable;
024import org.apache.cocoon.environment.Request;
025import org.apache.commons.lang3.StringUtils;
026
027import org.ametys.core.ui.dispatcher.DispatchRequestProcess;
028
029/**
030 * Handle cache stats during dispatch
031 */
032public class CacheDispatchRequestProcess implements DispatchRequestProcess, Serviceable
033{
034
035    private AbstractCacheManager _cacheManager;
036    
037    @Override
038    public void service(ServiceManager manager) throws ServiceException
039    {
040        _cacheManager = (AbstractCacheManager) manager.lookup(AbstractCacheManager.ROLE);
041    }
042    
043    @Override
044    public void preProcess(Request request)
045    {
046        // Nothing to handle on preProcess
047    }
048    
049    @Override
050    public void postProcess(Request request)
051    {
052        @SuppressWarnings("unchecked")
053        List<String> attrNames = Collections.list(request.getAttributeNames());
054        for (String attrName : attrNames)
055        {
056            if (attrName != null && attrName.startsWith(AbstractCacheManager.ROLE))
057            {
058                String id = StringUtils.replace(attrName, AbstractCacheManager.ROLE + "$", StringUtils.EMPTY);
059                Cache<Object, Object> cache = _cacheManager.get(id);
060                if (!cache.isDispatchable())
061                {
062                    _cacheManager.refreshStats(request, id);
063                    cache.resetCache();
064                }
065            }
066        }
067    }
068}