/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

====================================================================== */

package org.bodington.spring;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.bodington.server.BuildingServerException;
import org.bodington.server.BuildingSession;
import org.bodington.server.BuildingSessionManagerImpl;
import org.bodington.server.NavigationSession;
import org.bodington.server.realm.User;
import org.bodington.server.resources.Resource;
import org.bodington.servlet.Request;

/**
 * Utility methods for SpringMVC controllers.
 * 
 * @author buckett
 */
final public class Utils
{
    
    private static final String MESSAGES_ATTRIBUTE = "messages";

	/**
     * Gets the current resource for the request.
     * @param request The incomming servlet request.
     * @return The resource object associated with this request.
     */
    public static Resource getResource(HttpServletRequest request)
    {
        Object resource = request.getAttribute(Request.RESOURCE_ATTRIBUTE);
        return (Resource)resource;
    }
    
    public static BuildingSession getSession(HttpServletRequest request) throws BuildingServerException
    {
        return BuildingSessionManagerImpl.getSession(getResource(request));
    }
    
    public static User getUser(HttpServletRequest request) throws BuildingServerException
    {
        return ((NavigationSession)request.getAttribute(Request.NAVIGATION_ATTRIBUTE)).getAuthenticatedUser();
    }
    
    /**
     * Add a message to the session.
     * @param request The request to add the message to.
     * @param msg The message.
     */
    public static void saveMessage(HttpServletRequest request, Object msg) {
        List messages = (List) request.getSession().getAttribute(MESSAGES_ATTRIBUTE);
        if (messages == null) {
            messages = new ArrayList();
        }
        messages.add(msg);
        request.getSession().setAttribute(MESSAGES_ATTRIBUTE, messages);
    }
    
    
}
