/* ====================================================================
 * 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.services.security;

import java.util.Iterator;

// Junit imports
import junit.framework.Test;
import junit.framework.TestSuite;
import junit.framework.TestCase;


import org.apache.turbine.services.TurbineServices;
import org.apache.turbine.util.TurbineConfig;
import org.apache.turbine.util.StringUtils;

import org.apache.torque.Torque;
import org.apache.torque.TorqueException;

import org.apache.jetspeed.services.JetspeedUserManagement;
import org.apache.jetspeed.om.security.JetspeedUser;
import org.apache.jetspeed.om.security.JetspeedUserFactory;
import org.apache.jetspeed.om.security.UserNamePrincipal;
import org.apache.jetspeed.om.security.UserIdPrincipal;

/**
 * Unit test for UserManagement interface
 * 
 * @author <a href="mailto:david@bluesunrise.com">David Sean Taylor</a>
 * @version $Id: TestUserManagement.java,v 1.5 2002/12/08 19:33:53 taylor Exp $
 */

public class TestUserManagement extends TestCase {    

    /**
     * Defines the testcase name for JUnit.
     *
     * @param name the testcase's name.
     */
    public TestUserManagement( String name ) {
        super( name );
    }
    
    /**
     * Start the tests.
     *
     * @param args the arguments. Not used
     */
    public static void main(String args[]) 
    {
        junit.awtui.TestRunner.main( new String[] { TestUserManagement.class.getName() } );
    }
 
    public void setup() 
    {
        System.out.println("Setup: Testing Turbine User Management");         
    }

    /**
     * Creates the test suite.
     *
     * @return a test suite (<code>TestSuite</code>) that includes all methods
     *         starting with "test"
     */
    public static Test suite() 
    {
        // All methods starting with "test" will be executed in the test suite.
        return new TestSuite( TestUserManagement.class );
    }


    /**
     * Tests getUser method
     * @throws Exception
     */

    public void testGetUser() throws Exception 
    {
        setup();

        UserManagement service = getService();
        JetspeedUser user = null;
        try
        {
            user = JetspeedUserManagement.getUser(new UserNamePrincipal("turbine"));
        }
        catch (Exception e)
        {
            fail(StringUtils.stackTrace(e));
        }
        assertNotNull(user);
        assertTrue(user.getUserId().equals("2"));
        assertTrue(user.getUserName().equals("turbine"));
        assertTrue(user.getFirstName().equals("Tommy"));
        assertTrue(user.getLastName().equals("Turbine"));
        assertTrue(user.getEmail().equals("tommy@jakarta-jetspeed.com"));
        assertTrue(user.getConfirmed().equals("CONFIRMED"));
        assertTrue(user.getDisabled() == false);
        subtestTemp(user);

        try
        {
            JetspeedUserManagement.getUser(new UserNamePrincipal("nobody"));
        }
        catch (Exception e)
        {
            System.out.println("CAUGHT GETUSER EXCEPTION: " + e.toString());
            assertTrue(e instanceof UnknownUserException);
        }

        System.out.println("Completed getUser Test OK ");

    }

    /**
     * Tests getUsers method
     * @throws Exception
     */

    public void testGetUsers() throws Exception 
    {
        setup();

        UserManagement service = getService();
        JetspeedUser user = null;

        try
        {
            Iterator users = JetspeedUserManagement.getUsers();
            while (users.hasNext())
            {
                user = (JetspeedUser)users.next();
                //System.out.println("user name = " + user.getUserName());
                if (user.getUserName().equals("turbine"))
                {
                    assertTrue(user.getUserId().equals("2"));
                    assertTrue(user.getLastName().equals("Turbine"));
                }
                if (user.getUserName().equals("admin"))
                {
                    assertTrue(user.getUserId().equals("1"));
                    assertTrue(user.getLastName().equals("Admin"));
                }
            }
        }
        catch (Exception e)
        {
            fail(StringUtils.stackTrace(e));
        }

        System.out.println("Completed getUsers Test OK ");

    }


    static final String TEMP_LAST_NAME = "UnitTestLastName";

    /**
     * Tests saveUser method
     * @throws Exception
     */

    public void testSaveUser() throws Exception 
    {
        setup();

        UserManagement service = getService();
        JetspeedUser user = null;

        try
        {
            // test updating and retrieving some fields
            user = JetspeedUserManagement.getUser(new UserNamePrincipal("turbine"));
            String lastName = user.getLastName();
            user.setLastName(TEMP_LAST_NAME);
            user.setDisabled(true);

            JetspeedUserManagement.saveUser(user);
            JetspeedUser user2 = JetspeedUserManagement.getUser(new UserNamePrincipal("turbine"));
            assertTrue(user2.getLastName().equals(TEMP_LAST_NAME));
            assertTrue(user2.getDisabled() == true);

            user2.setLastName(lastName);
            user2.setDisabled(false);
            JetspeedUserManagement.saveUser(user2);
            JetspeedUser user3 = JetspeedUserManagement.getUser(new UserNamePrincipal("turbine"));
            assertTrue(user3.getLastName().equals(lastName));
            assertTrue(user3.getDisabled() == false);

            // test set/get Perm
            user3.setPerm("unittest", "test");
            JetspeedUserManagement.saveUser(user3);
            JetspeedUser user4 = JetspeedUserManagement.getUser(new UserNamePrincipal("turbine"));
            String unitTestValue = (String)user4.getPerm("unittest");
            assertTrue(unitTestValue.equals("test"));
            user4.setPerm("unittest", null);
            JetspeedUserManagement.saveUser(user4);            

            // try saving to an non-existing user
            try
            {
                JetspeedUser user5 = JetspeedUserFactory.getInstance();
                user5.setLastName("junk");
                JetspeedUserManagement.saveUser(user5);       
            }
            catch (Exception e)
            {
                assertTrue(e instanceof UnknownUserException);
            }
    
            // test dup on unique username key
            JetspeedUser user6 = JetspeedUserManagement.getUser(new UserNamePrincipal("turbine"));
            user6.setUserName("admin");
            try
            {
                JetspeedUserManagement.saveUser(user6);
            }
            catch (Exception e)
            {
                System.out.println("CAUGHT UNIQUE EXCEPTION: " + e.toString());
                assertTrue(e instanceof UserException);
            }

        }
        catch (Exception e)
        {
            fail(StringUtils.stackTrace(e));
        }

        System.out.println("Completed saveUser Test OK ");

    }

    /**
     * Tests addUser method
     * @throws Exception
     */

    public void testAddUser() throws Exception 
    {
        setup();

        UserManagement service = getService();

        try
        {
            // test updating and retrieving some fields
            JetspeedUser user = JetspeedUserFactory.getInstance();
            user.setUserName("busby");
            user.setPassword("woof");
            user.setLastName("Taylor");
            user.setFirstName("Busby");
            user.setEmail("busby@jakarta-jetspeed.com");
            user.setDisabled(false);
            user.setConfirmed("NO");
            user.setPerm("dogfood", "alpo");
            JetspeedUserManagement.addUser(user);

            JetspeedUser user2 = JetspeedUserManagement.getUser(new UserNamePrincipal("busby"));
            assertTrue(user2.getUserName().equals("busby"));
            assertTrue(user2.getLastName().equals("Taylor"));
            assertTrue(user2.getFirstName().equals("Busby"));
            assertTrue(user2.getEmail().equals("busby@jakarta-jetspeed.com"));
            assertTrue(user2.getConfirmed().equals("NO"));
            String dogfood = (String)user2.getPerm("dogfood");
            assertTrue(dogfood.equals("alpo"));
            assertTrue(user2.getDisabled() == false);
            assertTrue(user2.getUserId().equals(user.getUserId()));

            // test adding an existing user
            JetspeedUser user3 = JetspeedUserFactory.getInstance();
            user3.setUserName("busby");
            try
            {
                JetspeedUserManagement.addUser(user3);
            }
            catch (Exception e)
            {
                System.out.println("CAUGHT UNIQUE EXCEPTION: " + e.toString());
                assertTrue(e instanceof NotUniqueUserException);
            }


        }
        catch (Exception e)
        {
            fail(StringUtils.stackTrace(e));
        }

        System.out.println("Completed saveUser Test OK ");

    }

    /**
     * Tests removeUser method
     * @throws Exception
     */

    public void testRemoveUser() throws Exception 
    {
        setup();

        UserManagement service = getService();

        try
        {
            // depending on testAddUser running first!
            JetspeedUserManagement.removeUser(new UserNamePrincipal("busby"));

            try
            {
                JetspeedUserManagement.removeUser(new UserNamePrincipal("nobody"));
            }
            catch (Exception e)
            {
                System.out.println("CAUGHT REMOVE EXCEPTION: " + e.toString());
                assertTrue(e instanceof UnknownUserException);
            }

            try
            {
                JetspeedUserManagement.getUser(new UserNamePrincipal("busby"));
            }
            catch (Exception e)
            {
                System.out.println("CAUGHT REMOVE EXCEPTION: " + e.toString());
                assertTrue(e instanceof UnknownUserException);
            }


        }
        catch (Exception e)
        {
            fail(StringUtils.stackTrace(e));
        }

        System.out.println("Completed saveUser Test OK ");

    }

    private void subtestTemp(JetspeedUser user)
    {
        user.setTemp("test", new Integer(9));
        Integer test = (Integer)user.getTemp("test");
        assertTrue(test.intValue() == 9);
    }

  /*
    Configuration object to run Turbine outside a servlet container
    ( uses turbine.properties )
    */
    private static TurbineConfig config = null;
    
    /**
    Sets up TurbineConfig using the system property:
    <pre>turbine.properties</pre>
    */
    static
    {
        try
        {
            config = new TurbineConfig( "../webapp", "/WEB-INF/conf/TurbineResources.properties");
            config.init();
        }
        catch (Exception e)
        {
            fail(StringUtils.stackTrace(e));
        }
    }

    private static UserManagement getService()
    {
        return (UserManagement)TurbineServices
                .getInstance()
                .getService(UserManagement.SERVICE_NAME);
    }

}




