001/*
002 *  Copyright 2015 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.core.userpref;
017
018import java.io.IOException;
019import java.util.ArrayList;
020import java.util.HashMap;
021import java.util.List;
022import java.util.Map;
023
024import org.apache.avalon.framework.service.ServiceException;
025import org.apache.avalon.framework.service.ServiceManager;
026import org.apache.cocoon.ProcessingException;
027import org.apache.cocoon.environment.ObjectModelHelper;
028import org.apache.cocoon.environment.Request;
029import org.apache.cocoon.xml.AttributesImpl;
030import org.apache.cocoon.xml.XMLUtils;
031import org.apache.commons.lang3.StringUtils;
032import org.xml.sax.SAXException;
033
034import org.ametys.core.user.UserIdentity;
035import org.ametys.core.userpref.UserPreference;
036import org.ametys.core.userpref.UserPreferenceProvider;
037import org.ametys.core.userpref.UserPreferencesException;
038import org.ametys.core.userpref.UserPreferencesExtensionPoint;
039import org.ametys.core.userpref.UserPreferencesManager;
040import org.ametys.core.util.cocoon.AbstractCurrentUserProviderServiceableGenerator;
041import org.ametys.runtime.parameter.ParameterHelper;
042import org.ametys.runtime.workspace.WorkspaceMatcher;
043
044/**
045 * SAX user preferences values
046 */
047public class UserPreferencesValuesGenerator extends AbstractCurrentUserProviderServiceableGenerator
048{
049    /** The user preferences manager. */
050    protected UserPreferencesManager _userPrefManager;
051    
052    /** The user preferences extension point. */
053    protected UserPreferencesExtensionPoint _userPrefEP;
054    
055    @Override
056    public void service(ServiceManager serviceManager) throws ServiceException
057    {
058        super.service(serviceManager);
059        _userPrefEP = (UserPreferencesExtensionPoint) serviceManager.lookup(UserPreferencesExtensionPoint.ROLE);
060        _userPrefManager = (UserPreferencesManager) serviceManager.lookup(UserPreferencesManager.ROLE);
061    }
062    
063    @SuppressWarnings("unchecked")
064    @Override
065    public void generate() throws IOException, SAXException, ProcessingException
066    {
067        Request request = ObjectModelHelper.getRequest(objectModel);
068        String storageContext = request.getParameter("prefContext");
069        if (storageContext == null)
070        {
071            storageContext = parameters.getParameter("prefContext", null);
072        }
073
074        UserIdentity user = getUser();
075        Map<String, String> contextVars = getContextVars(request);
076        
077        contentHandler.startDocument();
078        
079        AttributesImpl attrs = new AttributesImpl();
080        attrs.addCDATAAttribute("prefContext", storageContext);
081        XMLUtils.startElement(contentHandler, "userprefs", attrs);
082        
083        try
084        {
085            Map<String, String> prefValues = _userPrefManager.getUnTypedUserPrefs(user, storageContext, contextVars);
086            Map<String, UserPreference> userPrefsDefinitions = _userPrefEP.getUserPreferences(contextVars);
087            
088            Map<String, Object> jsParameters = (Map<String, Object>) objectModel.get(ObjectModelHelper.PARENT_CONTEXT);
089            List<String> userprefs = null;
090            
091            if (jsParameters != null)
092            {
093                userprefs = (List<String>) jsParameters.get("userprefs");
094            }
095            
096            if (userprefs == null || userprefs.size() == 0)
097            {
098                userprefs = new ArrayList<>(userPrefsDefinitions.keySet());
099            }
100            
101            for (String userpref : userprefs)
102            {
103                if (prefValues.containsKey(userpref))
104                {
105                    XMLUtils.createElement(contentHandler, userpref, prefValues.get(userpref));
106                }
107                else
108                {
109                    // No value ? let's sax the default one (if available)
110                    UserPreference userPref = userPrefsDefinitions.get(userpref);
111                    if (userPref != null)
112                    {
113                        Object defaultValue = userPref.getDefaultValue();
114                        if (defaultValue != null)
115                        {
116                            XMLUtils.createElement(contentHandler, userpref, ParameterHelper.valueToString(defaultValue));
117                        }
118                    }
119                }
120            }
121        }
122        catch (UserPreferencesException e)
123        {
124            getLogger().error("Cannot get user preferences.", e);
125            throw new ProcessingException("Cannot get user preferences.", e);
126        }
127        
128        XMLUtils.endElement(contentHandler, "userprefs");
129        contentHandler.endDocument();
130    }
131    
132    /**
133     * Get the user in the user manager.
134     * @return the user.
135     */
136    protected UserIdentity getUser()
137    {
138        String login = parameters.getParameter("username", "");
139        String populationId = parameters.getParameter("populationId", "");
140        UserIdentity user;
141        if (StringUtils.isEmpty(login) || StringUtils.isEmpty(populationId))
142        {
143            user = _currentUserProvider.getUser();
144        }
145        else
146        {
147            user = new UserIdentity(login, populationId);
148        }
149        return user;
150    }
151    
152    /**
153     * Get the preferences context.
154     * @param request the request.
155     * @return the preferences context as a Map.
156     */
157    protected Map<String, String> getContextVars(Request request)
158    {
159        Map<String, String> contextVars = new HashMap<>();
160        contextVars.put(UserPreferenceProvider.CONTEXT_VAR_WORKSPACE, (String) request.getAttribute(WorkspaceMatcher.WORKSPACE_NAME));
161        return contextVars;
162    }
163    
164}