/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *     "Apache Jetspeed" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache" or
 *    "Apache Jetspeed", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
package org.apache.jetspeed.test;

import java.io.File;
import java.io.FileReader;

import junit.framework.AssertionFailedError;
import junit.framework.TestResult;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang.exception.NestableRuntimeException;
import org.apache.jetspeed.om.profile.PSMLDocument;
import org.apache.jetspeed.om.profile.Portlets;
import org.apache.jetspeed.services.PsmlManager;
import org.apache.turbine.util.StringUtils;
import org.apache.turbine.util.TurbineConfig;
import org.exolab.castor.mapping.Mapping;

/**
 * @author <a href="mailto:sweaver@rippe.com">Scott Weaver</a>
 *
 * Base abstract class for running Jetspeed (Turbine) in headles-mode
 * i.e. without a servlet container.
 *  
 * @version $Id: HeadlessBaseTest.java,v 1.4 2003/08/08 18:28:03 morciuch Exp $
 */
public abstract class HeadlessBaseTest extends JetspeedTestCase
{
    
    public static final String WEBAPP_PATH = "webapp.path";
    public static final String TR_PROPS_PATH = "tr.props.path";
    public static final String TEST_CONF_RES = "org/apache/jetspeed/test/jetspeed_testconfig.properties";
    public static final String PSML_MAPPING = "psml.mapping"; 
    public static final String DIVIDER = "+=============================================================================+";
    //public static final String  TEST_CONF_RES = "jetspeed_testconfig.properties";
    
    
    /*
    Configuration object to run Turbine outside a servlet container
    ( uses turbine.properties )
    */
    private static TurbineConfig config = null;
    private static final PropertiesConfiguration testConfig = new PropertiesConfiguration();
    
    protected TestResult testResult;


    
    public HeadlessBaseTest( String name)
    {
        super(name);
    }

 
    /**
     * Returns the Configuration object that holds testing values
     * @return PropertiesConfiguration
     */
    public static Configuration getTestConfig()
    {
        return testConfig;
    }
    
    
        /**
     * @see junit.framework.Test#run(TestResult)
     */
    public void run(TestResult result)
    {
        result.startTest(this);
        try
        {
            setUp();
        }
        catch (Exception e)
        {
            throw new NestableRuntimeException("Error running TestCase setUp().", e);
        }
        try
        {
            runTest();
        }
        catch (AssertionFailedError e)
        { //1
            result.addFailure(this, e);
        }

        catch (Throwable e)
        { // 2
            result.addError(this, e);
        }
        finally
        {
            try
            {
                tearDown();
            }
            catch (Exception e)
            {
                throw new NestableRuntimeException("Error running TestCase tearDown().", e);
            }
        }
    }
    



    /**
     * @see junit.framework.TestCase#setUp()
     *
     * Sets up TurbineConfig using the system property:
     *  <pre>turbine.properties</pre>
     */
    
    protected void setUp() throws Exception
    {
        try
        {
            // Only set it up once per class loader
            if(testConfig == null || config == null)
            {
                ClassLoader cl = Thread.currentThread().getContextClassLoader();
                System.out.println(cl.getResource(TEST_CONF_RES));
                testConfig.load(cl.getResourceAsStream(TEST_CONF_RES));
                System.out.println(testConfig.getString(WEBAPP_PATH));
                File webappUrl = new File(testConfig.getString(WEBAPP_PATH));
                System.out.println(webappUrl);
                //System.out.println("webapp found "+webappUrl.exists());
                config = new TurbineConfig(webappUrl.getPath(), testConfig.getString(TR_PROPS_PATH));
                config.init();
            }
        }
        catch (Throwable e)
        {
            fail(StringUtils.stackTrace(e));
        }        
        
        super.setUp();
    }
    
    public PSMLDocument getDocumentFromPath(String psmlFile)
    {
        print("Loading portlets from PSML file "+psmlFile);
      
        Portlets rootset = null;
            
        PSMLDocument doc = PsmlManager.getDocument(psmlFile);        
        rootset = doc.getPortlets();
        
         return doc;
    }
    
    public void saveDocument(PSMLDocument doc)
    {
        PsmlManager.saveDocument(doc);
    }
    
 
    
    public void savePortletsToPSML(String psmlFile, Portlets portlets)
    {
        print("Storing portlets to PSML file "+psmlFile);
      
        Mapping mapping = null;
        String mapFile = getProfileMappingFileName();
        print("Locating PSML file "+mapFile+"...");
        File map = new File(mapFile);
        print("PSML file exists????: "+map.exists());
        Portlets rootset = null;
        FileReader reader = null;
        if (map.exists() && map.isFile() && map.canRead())
        {
                
                try
                {
                }
                catch(Exception e)
                {
                }
        }
    }
    
    protected void print(Object obj)
    {
        if(testConfig.getBoolean("verbose"))
            System.out.println("+ "+obj);
    }
    
    protected void printOk()
    {
    
            print("OK");
        
    }
    
     protected void printOk(String linePrefix)
    {
    
            print(linePrefix+"OK");
    
    }
    
    protected void printDivider()
    {
        if(testConfig.getBoolean("verbose"))
          System.out.println(DIVIDER);        
    }
    
    /**
     * retreives the castor mapping file to use if
     * we need to marshal/unmarshal profiles
     */
    protected String getProfileMappingFileName()
    {
        return testConfig.getString(PSML_MAPPING);
    }

}
