package com.fujitsu.iflowqa.testframe;

import java.util.Properties;

import org.apache.slide.urm.authenticator.URMAdministrator;
import org.apache.slide.urm.authenticator.URMAuthenticator;
import org.apache.slide.urm.common.URMConfigurator;
import org.apache.slide.urm.common.URMConstants;
import org.apache.slide.urm.common.URMPrincipal;
import org.apache.slide.urm.common.impl.URMConfiguratorXML;

import com.fujitsu.iflow.common.SystemEnvironment;

/**
 * <p>This class tests the setup of IBPM SSX adapter with the SSX component. It first 
 * checks wheter it can load the urm_config.xml file that was specified at the IBPM
 * installation and then try to authenticate the usr specified by the LDAPAccesUserId
 * param.</p>
 * <p>You do not required to have the IBPM server running to run this test, but
 * make sure that you have successfully installed the IBPM server with the IMR/SSX
 * directory adapter.</p>
 * <p> Instructions to run this test case standalone - 
 * 1) Install AITS (Smoketest.zip)
 * 2) On a DOS command window run "0.TWFInit.bat"
 * 3) Change directory to <BPM install Dir>/bin/Aits
 * 4) Execute following command on the DOS window </p>
 * <b>java com.fujitsu.iflowqa.testframe.TestDriver com.fujitsu.iflowqa.testframe.TestSSXAdapterSetup </b>
 */
public class TestSSXAdapterSetup extends BPMTestBase
{
    Properties ibpmProp = null;
    SystemEnvironment sysEnv = null;
    
    public TestSSXAdapterSetup()
    {
        super();
    }
    
    /*
     * This method runs the rest.
     */
    public void runTests(TestRecorder recorder) throws Exception {
        init(recorder);

        String initFile = null;
        long piId = -1;

        try 
        {
            initFile = tr.getRequiredProperty("InitFile");
            //ibpmProp = readConfFile(initFile);
            sysEnv = new SystemEnvironment(initFile);
            int dirOption = sysEnv.vTWFDirectoryService;
            //ibpmProp.getProperty("TWFDirectoryService");
            if(dirOption == 4)
            {
                URMAuthenticator authenticator = null;
                URMAdministrator urmadmin = null;
                String urmFile = sysEnv.vURMConfigFilePath;
                //ibpmProp.getProperty("URMConfigFilePath");
                try{
                    authenticator = validateUrmFile(urmFile);
                    tr.markPassed("Successfully validated URM Configuration File");
                }
                catch(Exception ex){
                    tr.markFailed("Validating URM Config File test case failed",ex.getMessage());
                }
                if(authenticator != null)
                {
                    try{
                        urmadmin = authenticateSSXAdmin(authenticator);
                        tr.markPassed("Successfully communicated with SSX by using 'LDAPAccessUserID'");
                    }
                    catch(Exception ex){
                        tr.markFailed("Failed to communicate with SSX by using 'LDAPAccessUserID'",ex.getMessage());
                    }
                }
            }
            else
            {
                tr.markPassed("Directory Adapter is NOT using the IMR/SSX Directory server.");
            }
        } catch (Exception e) {
            throw new ExceptionWrapper("Exception caught in main test level", e);
        } 
    }
    /**
     * Validate the urm_config.xml file supplied at the time IBPM installation.
     * @param urmFile
     * @return 
     * @throws Exception
     */
    private
    URMAuthenticator
    validateUrmFile(String urmFile)
        throws Exception
    {
        // load the urm configuration file, this file will be read from the
        // environment variable URM_CONFIGFILE_PATH, make sure to set this param
        System.setProperty("URM_CONFIGFILE_PATH",urmFile);
        URMConfigurator conf = URMConfiguratorXML.newConfigfileConfigurator();
        conf = (URMConfigurator)(conf.getSubConfigurators().get("Authenticator"));
        URMAuthenticator authenticatorLocal = URMAuthenticator.newInstance(conf);
        return authenticatorLocal;
    }
    
    /**
     * Authenticates the user provided by the LDAPAccessUserId param, this user will
     * be acted as the Admin user for the SSX component.
     * @param urmAuthenticator
     * @return 
     * @throws Exception
     */
    private
    URMAdministrator
    authenticateSSXAdmin(URMAuthenticator urmAuthenticator)
        throws Exception
    {
        // Authenticates the user set by the LDAPAccessUserId and LDAPAccessUserPassword for the 
        // default domain, the user must have the administrative privilege to access
        // the directory server
        String adminUserDomain = sysEnv.vURMDomain;
        //ibpmProp.getProperty("URMDomain");
        String adminUser = sysEnv.vLDAPAccessUserID;
        //ibpmProp.getProperty("LDAPAccessUserID");
        int dIndex = -1;
        if((dIndex = adminUser.indexOf("\\")) != -1 )
        {
            adminUserDomain = adminUser.substring(0,dIndex);
            adminUser = adminUser.substring(dIndex+1);
        }
        if(adminUserDomain != null && adminUserDomain.trim().length() == 0)
            adminUserDomain = null;
        String userPass = sysEnv.vLDAPAccessUserPassword;
        //ibpmProp.getProperty("LDAPAccessUserPassword");
        URMPrincipal principal = urmAuthenticator.authenticateUser(adminUser, 
                                    userPass.toCharArray(), adminUserDomain);
        principal.setActiveRole(URMConstants.URM_ADMIN_ROLE);
        return principal.getURMAdministrator();
    }
    
}