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 org.apache.avalon.framework.service.ServiceException;
019import org.apache.avalon.framework.service.ServiceManager;
020import org.apache.avalon.framework.service.Serviceable;
021import org.apache.cocoon.components.ContextHelper;
022import org.apache.cocoon.environment.Request;
023import org.apache.commons.lang.StringUtils;
024
025import org.ametys.core.resources.ProxiedContextPathProvider;
026import org.ametys.web.URIPrefixHandler;
027import org.ametys.web.WebConstants;
028import org.ametys.web.renderingcontext.RenderingContext;
029import org.ametys.web.renderingcontext.RenderingContextHandler;
030
031/**
032 * Proxied context path provider for the Front
033 */
034public class FrontProxiedContextPathProvider extends ProxiedContextPathProvider implements Serviceable
035{
036    private URIPrefixHandler _prefixHandler;
037    private RenderingContextHandler _renderingContextHandler;
038
039    @Override
040    public void service(ServiceManager manager) throws ServiceException
041    {
042        _prefixHandler = (URIPrefixHandler) manager.lookup(URIPrefixHandler.ROLE);
043        _renderingContextHandler = (RenderingContextHandler) manager.lookup(RenderingContextHandler.ROLE);
044    }
045    
046    @Override
047    public String getContextPath()
048    {
049        Request request = ContextHelper.getRequest(_context);
050        
051        if (_renderingContextHandler.getRenderingContext() == RenderingContext.FRONT)
052        {
053            String siteName = request.getParameter("siteName");
054            if (siteName == null)
055            {
056                siteName = (String) request.getAttribute("siteName");
057            }
058            if (siteName == null)
059            {
060                siteName = (String) request.getAttribute("site");
061            }
062            
063            return _prefixHandler.getUriPrefix(siteName);
064        }
065        else
066        {
067            // For example, /cms/preview
068            return super.getContextPath() + StringUtils.trimToEmpty((String) request.getAttribute(WebConstants.PATH_PREFIX));
069        }
070    }
071}