package org.appfuse.webapp.action;


import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.apache.cactus.WebRequest;
import org.apache.cactus.client.authentication.FormAuthentication;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.appfuse.Constants;
import org.appfuse.model.User;
import org.appfuse.service.UserManager;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;

import servletunit.struts.MockStrutsTestCase;


/**
 * This class is extended by all ActionTests.  It basically
 * contains common methods that they might use.
 * <p/>
 * <p/>
 * <a href="BaseStrutsTestCase.java.html"><i>View Source</i></a>
 * </p>
 * 
 * @author <a href="mailto:[email protected]">Matt Raible</a>
 * @version $Revision: 1.1 $ $Date: 2004/03/31 13:04:16 $
 */
public class BaseMockTestCase extends MockStrutsTestCase {
    //~ Instance fields ========================================================

    protected User user = null;
    protected ResourceBundle rb = null;
    private Log log = LogFactory.getLog(BaseMockTestCase.class);
    protected ResourceBundle login = null;
    protected ApplicationContext ctx = null;

    //~ Constructors ===========================================================

    public BaseMockTestCase(String name) {
        super(name);
        // Since a ResourceBundle is not required for each class, just
        // do a simple check to see if one exists
        String className = this.getClass().getName();

        try {
            rb = ResourceBundle.getBundle(className);
        } catch (MissingResourceException mre) {
            //log.warn("No resource bundle found for: " + className);
        }
        login = ResourceBundle.getBundle(LoginServletTest.class.getName());
    }

    //~ Methods ================================================================


    public void begin(WebRequest request) {
        request.setRedirectorName("ServletRedirectorSecure");
        request.setAuthentication(new FormAuthentication(
                login.getString("username"),
                login.getString("encryptedPassword")));
    }

    public void setUp() throws Exception {
        super.setUp();
        // populate the userForm and place into session
        String username = login.getString("username");
        ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
        getSession().getServletContext().setAttribute(
                WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ctx);
        UserManager userMgr = (UserManager) ctx.getBean("userManager");
        user = (User) userMgr.getUser(username);
        getSession().setAttribute(Constants.USER_KEY, user);
    }

    protected void tearDown() throws Exception {
        ctx = null;
    }
}