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.site.proxy;
017
018import java.util.ArrayList;
019import java.util.List;
020
021import org.apache.avalon.framework.configuration.Configurable;
022import org.apache.avalon.framework.configuration.Configuration;
023import org.apache.avalon.framework.configuration.ConfigurationException;
024import org.apache.cocoon.environment.Request;
025import org.apache.cocoon.environment.Response;
026import org.apache.cocoon.environment.Session;
027import org.apache.http.HttpResponse;
028import org.apache.http.client.methods.HttpUriRequest;
029
030/**
031 * Proxies a session attribute to the back-office, under the form of a request header prefixed by "X-Ametys-Session-".
032 */
033public class SessionAttributeRequestProxy implements BackOfficeRequestProxy, Configurable
034{
035    /** The header prefix */
036    public static final String HEADER_PREFIX = "X-Ametys-Session-";
037    
038    private List<String> _attributes = new ArrayList<>();
039    
040    public void configure(Configuration configuration) throws ConfigurationException
041    {
042        for (Configuration attributeConfig : configuration.getChildren("attribute"))
043        {
044            _attributes.add(attributeConfig.getValue());
045        }
046    }
047    
048    public void prepareBackOfficeRequest(Request request, HttpUriRequest backOfficeRequest)
049    {
050        Session session = request.getSession(false);
051        if (session != null)
052        {
053            for (String attributeName : _attributes)
054            {
055                Object attribute = session.getAttribute(attributeName);
056                if (attribute != null)
057                {
058                    backOfficeRequest.addHeader(HEADER_PREFIX + attributeName, attribute.toString());
059                }
060            }
061        }
062    }
063
064    public void handleBackOfficeResponse(Response response, HttpResponse backOfficeResponse)
065    {
066        // nothing to do
067    }
068}