001/*
002 *  Copyright 2018 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.web.resources;
017
018import java.util.Map;
019import java.util.Optional;
020
021import org.apache.avalon.framework.parameters.Parameters;
022import org.apache.avalon.framework.service.ServiceException;
023import org.apache.avalon.framework.service.ServiceManager;
024import org.apache.avalon.framework.service.Serviceable;
025import org.apache.avalon.framework.thread.ThreadSafe;
026import org.apache.cocoon.acting.AbstractConfigurableAction;
027import org.apache.cocoon.environment.ObjectModelHelper;
028import org.apache.cocoon.environment.Redirector;
029import org.apache.cocoon.environment.Request;
030import org.apache.cocoon.environment.Response;
031import org.apache.cocoon.environment.SourceResolver;
032
033import com.google.common.collect.ImmutableMap;
034
035/**
036 * This action adds cacheable HTTP headers to front resources. Some resources are ignored based on the {@link FrontCacheableResourceExtensionPoint}
037 */
038public class FrontCacheableResourceHeaderAction extends AbstractConfigurableAction implements ThreadSafe, Serviceable
039{
040    private FrontCacheableResourceExtensionPoint _frontCacheableResourceEP;
041
042    public void service(ServiceManager manager) throws ServiceException
043    {
044        _frontCacheableResourceEP = (FrontCacheableResourceExtensionPoint) manager.lookup(FrontCacheableResourceExtensionPoint.ROLE);
045    }
046    
047    @Override
048    public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters parameters) throws Exception
049    {
050        boolean isCacheable = Optional.of(objectModel)
051                .map(ObjectModelHelper::getRequest)
052                .map(Request::getRequestURI)
053                .filter(uri -> _frontCacheableResourceEP.isCacheable(uri))
054                .isPresent();
055        
056        return isCacheable
057                ? setCacheableHeaders(objectModel)
058                : ImmutableMap.of();
059    }
060    
061    private Map setCacheableHeaders(Map objectModel)
062    {
063        final Response response = ObjectModelHelper.getResponse(objectModel);
064        response.setHeader("X-Ametys-Cacheable", "true");
065        return ImmutableMap.of("X-Ametys-Cacheable", "true");
066    }
067}