/*
 * $Header: /home/cvspublic/jakarta-slide/proposals/wvcm/test/junit/src/org/apache/wvcm/test/common/AbstractTest.java,v 1.3 2004/07/30 06:52:35 ozeigermann Exp $
 * $Revision: 1.3 $
 * $Date: 2004/07/30 06:52:35 $
 *
 * ====================================================================
 *
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2003 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 acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Slide", and "Apache Software
 *    Foundation" 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"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * 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/>.
 *
 * [Additional notices, if required by prior licensing conditions]
 *
 */

package org.apache.wvcm.test.common;

import java.net.ConnectException;
import java.util.Hashtable;
import java.util.Properties;
import java.util.logging.Logger;
import java.util.logging.Level;
import javax.wvcm.AccessControlElement.Privilege;
import javax.wvcm.ControllableFolder;
import javax.wvcm.ControllableResource;
import javax.wvcm.Location;
import javax.wvcm.Principal;
import javax.wvcm.Principal.Group;
import javax.wvcm.Principal.Role;
import javax.wvcm.Provider;
import javax.wvcm.ProviderFactory;
import javax.wvcm.Resource;
import javax.wvcm.Workspace;
import javax.wvcm.WvcmException;
import javax.wvcm.WvcmException.ReasonCode;
import junit.framework.TestCase;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.HeadMethod;
import org.apache.wvcm.test.common.util.FileHelper;
import org.apache.wvcm.test.common.util.PropertiesHelper;
import org.apache.wvcm.test.common.util.XmlHelper;

/**
 * This testsuite depends upon a running WebDAV server.
 * The environment can be set-up by setting properties at
 * test.properties.
 *
 * @author <a href="mailto:peter.nevermann@softwareag.com">Peter Nevermann</a>
 * @version $Revision: 1.3 $
 */
public abstract class AbstractTest extends TestCase {
	
	private static Logger logger = Logger.getLogger("org.apache.wvcm.test.common.AbstractTest");
	
    // Read properties from the properties file. If no props file is given,
    // default values will be used.
    protected static Properties webdavprops = new Properties();
    static {
		try {
			webdavprops.load( AbstractTest.class.getResourceAsStream("/test.properties") );
		}
		catch (java.io.IOException e) {}
    }
    
    protected PropertiesHelper propsHelper;
    protected XmlHelper xmlHelper;
    protected FileHelper fileHelper;
    
    protected String host = null;
    protected int port = 0;
    protected String context = null;
    protected String rootfolderName = null;
    protected String realm = null;
    protected String username = null;
    protected String password = null;
    
    protected String usersFolderName = null;
    protected String groupsFolderName = null;
    protected String rolesFolderName = null;
    protected String privilegesFolderName = null;
    protected String workspaceFolderName;
    
    protected HttpClient client = null;
    
    // caches
    private String contextPath = null;
    private String rootFolderPath = null;
    
    // Variables used by the test classes
    protected String resourcePath = null;
    protected String folderPath = null;
    protected String workspacePath = null;
    protected String resourceInFolderPath = null;
    protected String missingFolderPath = null;
    protected String resourceInMissingFolderPath = null;
    protected String usersFolderPath = null;
    protected String groupsFolderPath = null;
    protected String rolesFolderPath = null;
    
    protected ProviderFactory.Callback callback = null;
    protected Provider provider = null;
    
    protected Location location;
    protected Resource testResource;
    protected ControllableResource resource;
    protected ControllableFolder folder;
    protected Workspace workspace;
    
    protected String testResourcesRoot = "/org/apache/wvcm/test/resources/";
	protected String testResourcesAbsoluteRoot;
    
    
    /**
	 * Default Constructor
	 *
	 * @param    testName            Name of the test to run.
	 *
	 * @throws   Exception
	 *
	 */
    public AbstractTest(String testName) throws Exception {
		super(testName);
		try {
			initProperties();
			
			client = new HttpClient();
			client.getHostConfiguration().setHost(host, port, "http");
			HttpState state = new HttpState();
			state.setCredentials(
				realm, host, new UsernamePasswordCredentials(username, password) );
			client.setState( state );
		}
		catch (NoClassDefFoundError ncdfe) {
			System.out.println("no class def found error exception");
			System.out.println(ncdfe.getCause().getMessage());
			ncdfe.printStackTrace();
		}
		catch (ExceptionInInitializerError e) {
			System.out.println(e.getCause().getMessage());
			e.printStackTrace();
		}
		
		callback = new CallbackImpl();
		Hashtable h = new Hashtable();
		h.put( "host", host );
		h.put( "port", String.valueOf(port) );
		if( realm != null )
			h.put( "realm", realm );
		if( context != null )
			h.put( "context", context );
		provider = ProviderFactory.createProvider(
			"org.apache.wvcm.ProviderImpl", callback, h );
		
		propsHelper = new PropertiesHelper();
		xmlHelper = new XmlHelper();
		fileHelper = new FileHelper();
		
		// Initialize variables used by all tests.
		if (!usersFolderName.startsWith("/") )
			usersFolderName = "/"+usersFolderName;
		usersFolderPath = contextPath() + usersFolderName;
		
		if (!groupsFolderName.startsWith("/") )
			groupsFolderName = "/" + groupsFolderName;
		groupsFolderPath = contextPath() + groupsFolderName;
		
		if (!rolesFolderName.startsWith("/") )
			rolesFolderName = "/" + rolesFolderName;
		rolesFolderPath = contextPath() + rolesFolderName;
    }
    
    /**
	 * Initialises the properties needed for the test from a Properties file. If
	 * the properties file is not found, properties are initialised with some
	 * default value.
	 *
	 */
    private void initProperties() {
		host = webdavprops.getProperty( "org.apache.webdav.test.host", "localhost" );
		String portStr = webdavprops.getProperty( "org.apache.webdav.test.port", "8080" );
		try {
			port = Integer.parseInt(portStr);
		}
		catch (NumberFormatException e) {
			port = 8080;
		}
		context = webdavprops.getProperty( "org.apache.webdav.test.context", "slide" );
		rootfolderName = webdavprops.getProperty( "org.apache.webdav.test.rootfolder", "files" );
		realm = webdavprops.getProperty( "org.apache.webdav.test.realm", null );
		username = webdavprops.getProperty( "org.apache.webdav.test.username", "root" );
		password = webdavprops.getProperty( "org.apache.webdav.test.password", "root" );
		
		usersFolderName = webdavprops.getProperty( "org.apache.webdav.test.usersfolder", "/users" );
		groupsFolderName = webdavprops.getProperty( "org.apache.webdav.test.groupsfolder", "/groups" );
		rolesFolderName = webdavprops.getProperty( "org.apache.webdav.test.rolesfolder", "" );
		privilegesFolderName = webdavprops.getProperty( "org.apache.webdav.test.privilegesfolder", "actions" );
		workspaceFolderName = webdavprops.getProperty( "org.apache.webdav.test.workspacefolder", "workspace" );
		
		// Resource related properties
		testResourcesRoot = webdavprops.getProperty( "org.apache.webdav.test.resourcesRoot",
												   "/org/apache/wvcm/test/resources/");
		testResourcesAbsoluteRoot = webdavprops.getProperty( "org.apache.webdav.test.resourcesAbsolutePath",
												   "E:\\");
    }
    
    /**
	 * Tests common setup.
	 *
	 * @throws Exception
	 */
    protected void setUp() throws Exception {
		super.setUp ();
    }
    
    /**
	 * Tears down the fixture, for example, close a network connection.
	 * This method is called after a test is executed.
	 *
	 * @throws Exception
	 */
    protected void tearDown() throws Exception {
    }
    
    /**
	 * Removes a resource in the server specified by the given path.
	 *
	 * @param    resourcePath        Path to the resource to remove.
	 *
	 * @throws   Exception
	 *
	 */
    protected void deleteResourceOnServer( String resourcePath ) throws Exception {
		HttpMethod method = new DeleteMethod( resourcePath );
		try {
			client.executeMethod( method );
		}
		catch (ConnectException e) {
			if (logger.isLoggable(Level.INFO))
				logger.info("No connection with "
							+ client.getHostConfiguration().getHostURL()
							+ " could be done. Check configuration.");
			
			
			throw e;
		}
		
		assertTrue( method.getStatusCode() == 204 || method.getStatusCode() == 404 );
    }
    
    /**
	 * Check if the location specified by the passed path exists in the server.
	 *
	 * @param    resourcePath        Location to check.
	 *
	 * @return   True if the resource is found.
	 *
	 * @throws   Exception
	 *
	 */
    protected boolean resourceExistsOnServer( String resourcePath ) throws Exception {
		HttpMethod method = new HeadMethod( resourcePath );
		try {
			client.executeMethod( method );
		}
		catch (ConnectException e) {
			if (logger.isLoggable(Level.INFO))
				logger.info("No connection with "
							+ client.getHostConfiguration().getHostURL()
							+ " could be done. Check configuration.");
			
			
			throw e;
		}
		
		return( method.getStatusCode() == 200 );
    }
    
    /**
	 * Get context path
	 *
	 * @return   a String
	 */
    protected synchronized String contextPath() {
		if( contextPath == null ) {
			if( context != null && context.length() > 0 )
				contextPath = "/" + context;
			else
				contextPath = "/";
		}
		return contextPath;
    }
    
    /**
	 * Get rootfolder path
	 *
	 * @return   a String
	 */
    protected synchronized String rootFolderPath() {
		if( rootFolderPath == null ) {
			if( rootfolderName != null && rootfolderName.length() > 0 )
				rootFolderPath = contextPath()+"/"+rootfolderName;
			else
				rootFolderPath = contextPath();
		}
		return rootFolderPath;
    }
    
    /**
	 * Using the passed location, a ControllableResource is instantiated,
	 * unbound and then created again. If the resource exists there before, it
	 * will be deleted. Result is not checked.
	 *
	 * @param    loc                Path to the resource for the test.
	 *
	 * @return   A ControllableResource created with the passed path.
	 *
	 * @throws   WvcmException
	 *
	 */
    protected ControllableResource createControllableResource(Location loc) throws WvcmException {
		ControllableResource resource = loc.controllableResource();
		try {
			resource.doUnbind();
			resource.doCreateResource();
		}
		catch (WvcmException unexpected) {
			if (unexpected.getReasonCode() == ReasonCode.WRITE_FAILED) {
				if(logger.isLoggable(Level.INFO)) {
					logger.info("Creation of resource "
								+ loc.string()
								+ " failed.");
				}
			}
			else {
				if(logger.isLoggable(Level.INFO)) {
					logger.info("Unexpected exception while creating resource.");
				}
				throw unexpected;
			}
			resource = null;
		}
		
		return resource;
    }
    
    
    /**
	 * Using the passed location, a ControllableFolder is instantiated,
	 * unbound and then created again. If the folder exists there before, it
	 * will be deleted.
	 *
	 * @param    loc                Location to use when creating the folder.
	 *
	 * @return   A ControllableFolder created with the passed path or null if
	 * there were any problems while creating the folder.
	 *
	 * @throws   WvcmException
	 *
	 */
    protected ControllableFolder createControllableFolder(Location loc) throws WvcmException {
		ControllableFolder folder = (ControllableFolder)loc.folder();
		try {
			folder.doUnbind();
			folder.doCreateResource();
		}
		catch (WvcmException unexpected) {
			if (unexpected.getReasonCode() == ReasonCode.WRITE_FAILED) {
				if(logger.isLoggable(Level.INFO)) {
					logger.info("Creation of folder "
								+ loc.string()
								+ " failed.");
				}
			}
			else {
				if(logger.isLoggable(Level.INFO)) {
					logger.info("Unexpected exception while creating resource.");
				}
				throw unexpected;
			}
			folder = null;
		}
		
		return folder;
    }
    
    /**
	 * Using the passed location, a Workspace is instantiated,
	 * unbound and then created again. If the workspace exists there before, it
	 * will be deleted.
	 *
	 * @param    loc                Path to the workspace to be created.
	 *
	 * @return   A Workspace created with the passed path.
	 *
	 * @throws   WvcmException
	 *
	 */
    protected Workspace createWorkspace(Location loc) throws WvcmException {
		Workspace workspace = loc.workspace();
		
		try {
			workspace.doUnbind();
			workspace.doCreateResource();
		}
		catch (WvcmException unexpected) {
			if (unexpected.getReasonCode() == ReasonCode.WRITE_FAILED) {
				if(logger.isLoggable(Level.INFO)) {
					logger.info("Creation of workspace "
								+ loc.string()
								+ " failed.");
				}
			}
			else {
				if(logger.isLoggable(Level.INFO)) {
					logger.info("Unexpected exception while creating resource.");
				}
				throw unexpected;
			}
			workspace = null;
		}
		return workspace;
    }
    
    /**
	 * Using the passed location, a Privilege is instantiated, then unbound and
	 * created again.
	 *
	 * @param    loc                 Location where the privilege will be created.
	 *
	 * @return   Mmmm, the created privilege.
	 *
	 * @throws   WvcmException
	 *
	 */
    protected Privilege createPrivilege(Location loc) throws WvcmException {
		Privilege priv = loc.privilege();
		
		try {
			priv.doUnbind();
			priv.doCreateResource();
		}
		catch (WvcmException unexpected) {
			if (unexpected.getReasonCode() == ReasonCode.WRITE_FAILED) {
				if(logger.isLoggable(Level.INFO)) {
					logger.info("Creation of workspace "
								+ loc.string()
								+ " failed.");
				}
			}
			else {
				if(logger.isLoggable(Level.INFO)) {
					logger.info("Unexpected exception while creating resource.");
				}
				throw unexpected;
			}
			priv = null;
		}
		return priv;
    }
    
    /**
	 * Creates a Group. If the group already exists,
	 * depending on the value of the overwrite parameter, the group will be
	 * deleted and created again, losing in this way any properties and/or
	 * child groups/users.
	 *
	 * @param    groupName           Name of the group to create.
	 * @param    overwrite           If the group is to be deleted in case it exists.
	 *
	 * @return   The created Group.
	 *
	 * @throws   WvcmException
	 * @throws   Exception
	 *
	 */
    protected Group createGroup(String groupName, boolean overwrite)
		throws WvcmException, Exception{
		String path = null;
		if (groupsFolderPath != null && groupsFolderPath.length() > 0) {
			path = groupsFolderPath + "/" + groupName;
			location = provider.location(path);
		}
		else
			throw new Exception("GROUPS FOLDER PATH NOT INITIALIZED.");
		Group testGroup = location.group();
		
		try {
			if (overwrite && resourceExistsOnServer(path)) {
				testGroup.doUnbind();
			}
			testGroup.doCreateResource();
		}
		catch (WvcmException unexpected) {
			if (unexpected.getReasonCode() == ReasonCode.WRITE_FAILED) {
				if(logger.isLoggable(Level.INFO)) {
					logger.info("Creation of group "
								+ groupName
								+ " failed.");
				}
			}
			else {
				if(logger.isLoggable(Level.INFO)) {
					logger.info("Unexpected exception while creating resource.");
				}
				throw unexpected;
			}
			testGroup = null;
		}
		
		assertTrue( resourceExistsOnServer(path) );
		return testGroup;
    }
    
    /**
	 * Creates a Principal in the userdb folder. If the Principal already exists,
	 * depending on the value of the overwrite parameter, it will be
	 * deleted and created again, losing in this way any properties.
	 *
	 * @param    userName            Name of the Principal to create.
	 * @param    overwrite           If the Principal is to be deleted in case it exists.
	 *
	 * @return   The created Principal.
	 *
	 * @throws   WvcmException
	 * @throws   Exception
	 *
	 */
    protected Principal createUser(String userName, boolean overwrite)
		throws WvcmException, Exception {
		String path = null;
		if (usersFolderPath != null && usersFolderPath.length() > 0) {
			path = usersFolderPath + "/" + userName;
			location = provider.location(path);
		}
		else
			throw new Exception("USERS FOLDER PATH NOT INITIALIZED.");
		Principal user = location.principal();
		
		try {
			if (overwrite && resourceExistsOnServer(path)) {
				user.doUnbind();
			}
			
			user.doCreateResource();
		}
		catch (WvcmException unexpected) {
			if (unexpected.getReasonCode() == ReasonCode.WRITE_FAILED) {
				if(logger.isLoggable(Level.INFO)) {
					logger.info("Creation of user "
								+ userName
								+ " failed.");
				}
			}
			else {
				if(logger.isLoggable(Level.INFO)) {
					logger.info("Unexpected exception while creating resource.");
				}
				throw unexpected;
			}
			user = null;
		}
		
		assertTrue( resourceExistsOnServer(path) );
		return user;
    }
    
    /**
	 * Creates a Role. If the Role already exists,
	 * depending on the value of the overwrite parameter, it will be
	 * deleted and created again, losing in this way any properties and/or
	 * child roles.
	 *
	 * @param    roleName            Name of the folder to create.
	 * @param    overwrite           If the role is to be deleted in case it exists.
	 *
	 * @return   The created Role.
	 *
	 * @throws   WvcmException
	 * @throws   Exception
	 *
	 */
    protected Role createRole(String roleName, boolean overwrite)
		throws WvcmException, Exception{
		String path = null;
		if (rolesFolderPath != null && rolesFolderPath.length() > 0) {
			path = rolesFolderPath + "/" + roleName;
			location = provider.location(path);
		}
		else
			throw new Exception("ROLES FOLDER PATH NOT INITIALIZED.");
		Role testRole = location.role();
		
		try {
			if (overwrite && resourceExistsOnServer(path)) {
				testRole.doUnbind();
			}
			testRole.doCreateResource();
		}
		catch (WvcmException unexpected) {
			if (unexpected.getReasonCode() == ReasonCode.WRITE_FAILED) {
				if(logger.isLoggable(Level.INFO)) {
					logger.info("Creation of role "
								+ roleName
								+ " failed.");
				}
			}
			else {
				if(logger.isLoggable(Level.INFO)) {
					logger.info("Unexpected exception while creating resource.");
				}
				throw unexpected;
			}
			testRole = null;
		}
		
		assertTrue( resourceExistsOnServer(path) );
		return testRole;
    }
    
    /**
	 * Callback implementation
	 */
    class CallbackImpl implements ProviderFactory.Callback {
		
		Authentication authentication = new AuthenticationImpl();
		
		/**
		 * Return authentication information for the current user.
		 * @param realm The authentication realm for the provider.
		 */
		public ProviderFactory.Callback.Authentication getAuthentication(String realm, Integer retryCount) {
			//            System.out.println("@@@ getAuthentication("+realm+","+retryCount+")");
			return authentication;
		}
		
		/**
		 * Callback Authentication implementation.
		 */
		class AuthenticationImpl implements ProviderFactory.Callback.Authentication {
			
			/** Return the password of the current user. */
			public String password() {
				return password;
			}
			
			/** Return the login name of the current user. */
			public String loginName() {
				return username;
			}
		}
    }
}


