/*
 * $Header: /home/cvspublic/jakarta-slide/proposals/wvcm/test/junit/src/org/apache/wvcm/test/LocationTest.java,v 1.3 2004/07/30 06:52:33 ozeigermann Exp $
 * $Revision: 1.3 $
 * $Date: 2004/07/30 06:52:33 $
 *
 * ====================================================================
 *
 * 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;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.wvcm.ControllableResource;
import javax.wvcm.Folder;
import javax.wvcm.Location;
import javax.wvcm.Principal;
import javax.wvcm.Principal.Group;
import javax.wvcm.Resource;
import javax.wvcm.Workspace;
import javax.wvcm.WvcmException;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.wvcm.test.common.AbstractTest;
import org.apache.wvcm.test.common.util.ReasonCodeChecker;

/**
 * Tests for javax.wvcm.Location.
 *
 * @author <a href="mailto:peter.nevermann@softwareag.com">Peter Nevermann</a>
 * @version $Revision: 1.3 $
 */
public class LocationTest extends AbstractTest {
	
	private Logger logger = Logger.getLogger(this.getClass().getName());
	
	private String testFolderName = "foo";
	private String childResourceName = "fooChild.gof";
		
    /**
	 * Default Constructor. Initializes the path for the folder to be used in tests.
	 *
	 * @param    testName            Name of the test to run.
	 *
	 * @throws   Exception
	 *
	 */
    public LocationTest(String testName) throws Exception {
		super(testName);
		folderPath = rootFolderPath() + "/" + testFolderName;
    }
    
    /**
	 * Method suite
	 *
	 * @return   a Test
	 */
    public static Test suite() {
		return new TestSuite(LocationTest.class);
    }
    
    /**
	 * Start test suite contained in this class using the text interface. If a
	 * parameter is passed, it will use it as a test name and run only that test
	 * case.
	 *
	 * @param args   commandline options (first argument = test method name to run)
	 *
	 * @throws   Exception
	 */
    public static void main( String[] args ) throws Exception{
		if (args.length == 1) {
			TestSuite testSuite = new TestSuite();
			testSuite.addTest(new LocationTest(args[0]));
			junit.textui.TestRunner.run(testSuite);
		}
		else {
			junit.textui.TestRunner.run( suite() );
		}
    }
    
    /**
	 * Common test 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 {
    }
	
	/**
	 * Creates a test folder and a resource inside it. The name of the folder and
	 * the resource are given by the class variables
	 *
	 * @throws WvcmException
	 */
	private void createTestFolderStructure() throws WvcmException{
		location= provider.location( folderPath );
		createControllableFolder(location);
		location = location.child(childResourceName);
		createControllableResource(location);
	}
    
	/**
	 * Initializes a location (/<rootfolder>/foo where <rootfolder> is defined
	 * in the configuration file.
	 * Checks the parent of the initialized location.
	 *
	 * @throws   Exception
	 *
	 */
    public void testParent() throws Exception {
		location = provider.location( "http://"+host+":"+port+folderPath );
		assertEquals("Parent folder is not the expected.",
					 rootFolderPath(),
					 location.parent().string());
    }
	
	/**
	 * <ul>
	 * <li>parent
	 * <li>Try to get the parent of the root folder.
	 * <li>A "/" is returned.
	 * <li>Get a location to the context node (http://server:port/
	 * <li>Get its parent. Parent should be null.
	 *
	 * @throws Exception
	 */
	public void testParentRoot() throws Exception {
		location = provider.location( "http://"+host+":"+port+contextPath() );
		
		assertEquals("Parent folder is not the expected.",
					 null,
					 location.parent());
		try {
			location = provider.location( "http://"+host+":" + port + "/" );
			fail("Expected Exception (ILLEGAL_LOCATION_SYNTAX) has not been thrown.");
		}
		catch (WvcmException expected) {
			if (logger.isLoggable(Level.CONFIG))
				logger.config("Exception Message thrown: " + expected.getMessage());
			
			assertEquals("Unexpected reason for thrown exception",
						 "ILLEGAL_LOCATION_SYNTAX",
						 ReasonCodeChecker.getReasonCodeAsString(expected));
		}
	}
	
	/**
	 * <ul>
	 * <li>Create a test folder.
	 * <li>Create a child folder and get a location of it.
	 * <li>Delete the test folder.
	 * <li>Check for parent.
	 * <li>WvcmException is thrown.
	 *
	 * @throws Exception
	 */
	public void testParentDeleted() throws Exception {
		String fooChildFolderName = "fooChildFolder";
		// Create test folders.
		location= provider.location( folderPath );
		Folder testFolder = createControllableFolder(location);
		
		Location childLocation = testFolder.location().child(fooChildFolderName);
		Folder childFolder = createControllableFolder(childLocation);
		
		testFolder.doUnbind();
		
		try {
			assertEquals("Parent location of deleted folder not expected.",
						 location.string(),
						 childLocation.parent().string());
		}
		catch (Exception unexpected) {
			unexpected.printStackTrace();
		}
	}
	
    
	/**
	 * Initializes a location (/<rootfolder>/foo where <rootfolder> is defined
	 * in the configuration file.
	 * Creates a child location of the initial one and checks its correctly done.
	 *
	 * @throws   Exception
	 *
	 */
    public void testChild() throws Exception {
		String childName = "test.xml";
		location= provider.location( folderPath );
		Location childLocation = location.child(childName);
		assertEquals("Child location is not the expected.",
					 folderPath + "/" + childName,
					 childLocation.string());
    }
	
	/**
	 * <ul>
	 * <li>Create test folder.
	 * <li>Create a child with a non existing path.
	 * <li>Check location corresponds with the expected one.
	 *
	 * @throws Exception
	 */
	public void testChildNonExisting() throws Exception {
		String childName = "locationTest/testChildNonExisting";
		location= provider.location( folderPath );
		
		Location childLocation = location.child(childName);
		assertEquals("Child location is not the expected.",
					 folderPath + "/" + childName,
					 childLocation.string());
	}
	
	/**
	 * <ul>
	 * <li>Create a test folder and add a resource to it.
	 * <li>Get a Location for the resource created.
	 * <li>Get the controllabeResource on that Location.
	 * <li>The corresponding ControllableResource instance is returned.
	 *
	 * @throws Exception
	 */
	public void testControllableResource() throws Exception {
		createTestFolderStructure();
		location = provider.location(folderPath).child(childResourceName);
		resource = location.controllableResource();
		
		assertTrue("Unexpected instance of controllable resource returned.",
				   resource instanceof ControllableResource);
		
		assertEquals("Wrong location of the returned controllable resource.",
					 folderPath.concat("/").concat(childResourceName),
					 resource.location().string());
	}
	
	/**
	 * <ul>
	 * <li>Create a test folder and add a resource to it.
	 * <li>Get a Location for the resx created.
	 * <li>Delete the resx created.
	 * <li>Get the controllable resource to the resx created.
	 * <li>Instance is correct.
	 *
	 * @throws Exception
	 */
	public void testControllableResourceDeleted() throws Exception {
		createTestFolderStructure();
		location = provider.location(folderPath).child(childResourceName);
		resource = location.controllableResource();
		
		resource.doUnbind();
		assertTrue("Unexpected instance of controllable resource returned.",
				   resource instanceof ControllableResource);
		
		assertEquals("Wrong location of the returned controllable resource.",
					 folderPath.concat("/").concat(childResourceName),
					 resource.location().string());
	}
	
	/**
	 * <ul>
	 * <li>Create a test folder.
	 * <li>Get the folder instance to it.
	 * <li>Check that the Folder returned corresponds to the created one.
	 *
	 * @throws Exception
	 */
	public void testFolder() throws Exception {
		createTestFolderStructure();
		location = provider.location(folderPath);
		Folder testFolder = location.folder();
		
		assertEquals("Wrong location of the returned folder.",
					 folderPath,
					 testFolder.location().string());
	}
	
	/**
	 * <ul>
	 * <li>Create a test folder and add a resource to it.
	 * <li>Get a Location to the created resx.
	 * <li>Get a folder instance to that location.
	 * <li>Instance is returned.
	 *
	 * @throws Exception
	 */
	public void testFolderOnResource() throws Exception {
		createTestFolderStructure();
		location = provider.location(folderPath.concat("/").concat(childResourceName));
		assertTrue("Unexpected instance returned from folder.",
				   location.folder() instanceof Folder);
		
	}
	
	/**
	 * <ul>
	 * <li>Create a test resource.
	 * <li>Get a Location to that resource.
	 * <li>{@link javax.wvcm.Location#resource() resource()}
	 * <li>The Resource object that identifies the created resource is returned.
	 *
	 * @throws Exception
	 */
	public void testResource() throws Exception {
		createTestFolderStructure();
		location = provider.location(folderPath.concat("/").concat(childResourceName));
		assertTrue("Unexpected instance returned from folder.",
				   location.resource() instanceof Resource);
		
		assertEquals("Wrong location of the returned resource.",
					 folderPath.concat("/").concat(childResourceName),
					 location.resource().toString());
	}
	
	/**
	 * <ul>
	 * <li>Create a test workspace (??).
	 * <li>Get a Location to that workspace.
	 * <li>Get the workspace object from the location.
	 * <li>The Workspace object that identifies the created workspace is returned.
	 *
	 * @throws Exception
	 */
	public void testWorkspace() throws Exception {
		List workspaceFolderList = provider.serverWorkspaceFolderList( null );
		workspacePath = workspaceFolderList.get(0)+"/testWorkspace";
		
		location = provider.location( workspacePath );
		workspace = createWorkspace(location);
		
		assertTrue("Unexpected instance returned from folder.",
				   location.workspace() instanceof Workspace);
	}
	
	/**
	 * <ul>
	 * <li>Create a test folder.
	 * <li>Get a Location to that folder.
	 * <li>{@link javax.wvcm.Location#workspace() workspace()} (using the created Location).
	 * <li>WvcmException is thrown.
	 *
	 * @throws Exception
	 */
	public void testWorkspaceOnFolder() throws Exception {
		location= provider.location( folderPath );
		createControllableFolder(location);
		
		location.workspace();
	}
	
	/**
	 * <ul>
	 * <li>Create a test folder and a resource in it.
	 * <li>Get a Location to that resx.
	 * <li>{@link javax.wvcm.Location#workspace() workspace()} (using the created Location).
	 * <li>WvcmException is thrown.
	 *
	 * @throws Exception
	 */
	// TODO: remove this method.
//	public void testWorkspaceOnResource() throws Exception {
//		fail("Not Implemented.");
//	}
	
	/**
	 * <ul>
	 * <li>Create a test folder and a test resource in it.
	 * <li>Get a Location to that folder.
	 * <li>Call method {@link javax.wvcm.Location#string() string()}
	 * <li>String returned should be correct. It should not contain "/" at the end.
	 * <li>Repeat the same with the resx.
	 *
	 * @throws Exception
	 */
	public void testString() throws Exception {
		location= provider.location( folderPath );
		folder = createControllableFolder(location);
		Location locationToCheck = folder.location();
		assertEquals("Unexpected string returned from location of folder.",
					 folderPath,
					 locationToCheck.string());
		
		location = location.child(childResourceName);
		resource = createControllableResource(location);
		locationToCheck = resource.location();
		assertEquals("Unexpected string returned from location of resource.",
					 folderPath + "/" + childResourceName,
					 locationToCheck.string());
	}
	
	/**
	 * <ul>
	 * <li>Create a test folder and a test resx.
	 * <li>Get a Location to that folder and to the resx.
	 * <li>Get the lastSegment() (on folder and resx).
	 * <li>String returned should correspond to the last segment of the location
	 * path.
	 *
	 * @throws Exception
	 */
	public void testLastSegment() throws Exception {
		location= provider.location( folderPath );
		folder = createControllableFolder(location);
		Location locationToCheck = folder.location();
		assertEquals("Unexpected lastSegment returned from location of folder.",
					 testFolderName,
					 locationToCheck.lastSegment());
		
		location = location.child(childResourceName);
		resource = createControllableResource(location);
		locationToCheck = resource.location();
		assertEquals("Unexpected lastSegment returned from location of resource.",
					 childResourceName,
					 locationToCheck.lastSegment());
	}
	
	/**
	 * <ul>
	 * <li>Create a group folder.
	 * <li>Get a location to it.
	 * <li>Call method {@link javax.wvcm.Location#group() group()} to get an instance
	 * to the created group.
	 * <li>The Principal.Group object returned should correspond to the used
	 * group location.
	 *
	 * @throws Exception
	 */
	public void testGroup() throws Exception {
		String groupName = "location_testGroup";
		createGroup(groupName, true);
		location = provider.location(groupsFolderPath + "/" + groupName);
		assertTrue("Unexpected instance returned from group location.",
				   location.group() instanceof Group);
	}
	
	/**
	 * <ul>
	 * <li>Create a Principal folder.
	 * <li>Get a location to it.
	 * <li>Call method {@link javax.wvcm.Location#principal() principal()} and get
	 * a Principal object.
	 * <li>The Principal object returned should correspond to the used
	 * principal location.
	 *
	 * @throws Exception
	 */
	public void testPrincipal() throws Exception {
		String userName = "loc_testPrincipal";
		createUser(userName, true);
		location = provider.location(usersFolderName + "/" + userName);
		assertTrue("Unexpected instance returned from group location.",
				   location.principal() instanceof Principal);
	}
	
	/**
	 * <ul>
	 * <li>Create a Role folder.
	 * <li>Get a location to it.
	 * <li>{@link javax.wvcm.Location#role() role()}
	 * <li>The Principal.Role object returned should correspond to the used
	 * role location.
	 *
	 * @throws Exception
	 */
	public void testRole() throws Exception {
		String roleName = "loc_testRole";
		createRole(roleName, true);
		location = provider.location(rolesFolderName + "/" + roleName);
		assertTrue("Unexpected instance returned from role location.",
				   location.role() instanceof Principal.Role);
	}
}

