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.frontoffice.search.requesttime.impl;
017
018import java.util.HashMap;
019import java.util.Map;
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;
025
026import org.ametys.plugins.repository.provider.RequestAttributeWorkspaceSelector;
027import org.ametys.web.frontoffice.search.requesttime.SearchComponent;
028import org.ametys.web.frontoffice.search.requesttime.SearchComponentArguments;
029
030/**
031 * {@link SearchComponent} executing in two parts: for getting the forced workspace, then restoring the forced workspace
032 */
033public class WorkspaceSwitcherSearchComponent implements SearchComponent, Configurable
034{
035    private static Map<Request, String> _forcedWorkspacesByReq = new HashMap<>();
036    private int _part;
037
038    @Override
039    public void configure(Configuration configuration) throws ConfigurationException
040    {
041        _part = configuration.getChild("part").getValueAsInteger();
042    }
043    
044    @Override
045    public int priority()
046    {
047        return _part == 1 ? MAX_PRIORITY : MIN_PRIORITY;
048    }
049
050    @Override
051    public boolean supports(SearchComponentArguments args)
052    {
053        return true;
054    }
055
056    @Override
057    public void execute(SearchComponentArguments args) throws Exception
058    {
059        Request request = args.request();
060        if (_part == 1)
061        {
062            // Retrieve current workspace
063            String currentWsp = RequestAttributeWorkspaceSelector.getForcedWorkspace(request);
064            _forcedWorkspacesByReq.put(request, currentWsp);
065        }
066        else
067        {
068            String currentWsp = _forcedWorkspacesByReq.remove(request);
069            // Restore context
070            RequestAttributeWorkspaceSelector.setForcedWorkspace(request, currentWsp);
071        }
072    }
073}