/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */

/*
 * DomainsProcessor.java
 *
 * Created on November 20, 2003, 10:45 AM
 */

package com.sun.enterprise.tools.upgrade.common;

import java.util.*;
import java.io.*;
import java.util.logging.*;
import java.net.InetAddress;
import java.net.UnknownHostException;

import com.sun.enterprise.util.ASenvPropertyReader;
import com.sun.enterprise.util.SystemPropertyConstants;

import com.sun.enterprise.tools.upgrade.logging.*;
import com.sun.enterprise.cli.framework.*;
import com.sun.enterprise.util.i18n.StringManager;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;

import javax.xml.transform.dom.DOMSource;  
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.OutputKeys;

import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.w3c.dom.Document;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.sun.enterprise.tools.upgrade.cluster.*;

/**
 *
 * @author  prakash
 * @author  hans
 */


public class DomainsProcessor {
    private static CommonInfoModel commonInfo;
    private java.util.Vector httpSSLPorts;
    private java.util.Vector iiopSSLPorts;
    private java.util.Vector iiopMutualAuthPorts;
    private java.util.Vector sourceXMLCorePorts;
    //start CR 6407292
    private java.util.Vector adminJMXPorts;
    //end CR 6407292
    //start CR 6430228
    private java.util.Vector iiopPorts;
    private java.util.Vector httpPorts;
    private static int iiopPortToStartWith = 1071;
    //end CR 6430228
    private static int adminPortToStartWith = 4858;
    
    private static Logger logger = LogService.getLogger(LogService.UPGRADE_LOGGER);
    private static StringManager stringManager = StringManager.getManager(LogService.UPGRADE_LOGGER);
   
    //start CR 6424053
    private boolean domainStarted = false;
    //end CR 6424053
 
    
    /** Creates a new instance of DomainsProcessor */
    public DomainsProcessor(CommonInfoModel ci) {
        this.commonInfo = ci;
        httpSSLPorts = new java.util.Vector();
        iiopSSLPorts = new java.util.Vector();
        iiopMutualAuthPorts = new java.util.Vector();
        sourceXMLCorePorts = new java.util.Vector();
        //start CR 6407292
        adminJMXPorts = new java.util.Vector();
        //end CR 6407292
        //start CR 6430228
        iiopPorts = new java.util.Vector();
        httpPorts = new java.util.Vector();
        //end CR 6430228
        // Prefill with ports used in default domain and samples domain.
        // default domain xml file ports:
        File domainDir =  new File(ci.getTargetDomainRoot() + File.separator + "domain1");
        if(!domainDir.exists()){
            // This could be due to the reason that its inplace upgrade.  In this case upgrade tool should create the default domain too.
        }
        //start CR 6407292 
        else {
        //end CR 6407292
        String targetDomainFile = ci.getTargetDomainRoot() + File.separator + "domain1"+File.separator+
        "config"+File.separator+"domain.xml" ;
        if(domainDir.isDirectory() && !(ci.isValid70Domain(ci.getTargetDomainRoot() + File.separator + "domain1")) && (new File(targetDomainFile)).exists())  {
            
            String htSSP = getPortFromXML(targetDomainFile, "http-listener", "http-listener-2");
            if(htSSP != null) httpSSLPorts.add(htSSP);
            String iiSSP = getPortFromXML(targetDomainFile, "iiop-listener", "SSL");
            if(iiSSP != null) iiopSSLPorts.add(iiSSP);
            String iiMAP = getPortFromXML(targetDomainFile, "iiop-listener", "SSL_MUTUALAUTH");
            if(iiMAP != null) iiopMutualAuthPorts.add(iiMAP);
            //start CR 6407292
            String adminJMX = getJMXPortFromXML(targetDomainFile, "jmx-connector", "system");
            if(adminJMX != null) adminJMXPorts.add(adminJMX);
            //end CR 6407292
            //start CR 6430228
            String iiP = getPortFromXML(targetDomainFile, "iiop-listener", "orb-listener-1");
            if(iiP != null) iiopPorts.add(iiP);
            String httpP = getPortFromXML(targetDomainFile, "http-listener", "http-listener-1");
            if(httpP != null) httpPorts.add(httpP);
            //end CR 6430228
        }
        //start CR 6407292
        }
        //end CR 6407292
        File samplesDir =  new File(ci.getTargetDomainRoot() + File.separator + "samples");
        if(samplesDir.isDirectory() && !(ci.isValid70Domain(ci.getTargetDomainRoot() + File.separator + "samples")) )   {
            // Now add sample domain ports if there is one
            String sampleDomainFile = ci.getTargetDomainRoot() + File.separator + "samples"+File.separator+"config"+File.separator+"domain.xml" ;
            if(new File(sampleDomainFile).exists()){
                String shtSSP = getPortFromXML(sampleDomainFile, "http-listener", "http-listener-2");
                if(shtSSP != null) httpSSLPorts.add(shtSSP);
                String siiSSP = getPortFromXML(sampleDomainFile, "iiop-listener", "SSL");
                if(siiSSP != null) iiopSSLPorts.add(siiSSP);
                String siiMAP = getPortFromXML(sampleDomainFile, "iiop-listener", "SSL_MUTUALAUTH");
                if(siiMAP != null) iiopMutualAuthPorts.add(siiMAP);
                //start CR 6407292
                String sadminJMX = getJMXPortFromXML(sampleDomainFile, "jmx-connector", "system");
                if(sadminJMX != null) adminJMXPorts.add(sadminJMX);
                //end CR 6407292
                //start CR 6430228
                String siiP = getPortFromXML(sampleDomainFile, "iiop-listener", "orb-listener-1");
                if(siiP != null) iiopPorts.add(siiP);
                String shttpP = getPortFromXML(sampleDomainFile, "http-listener", "http-listener-1");
                if(shttpP != null) httpPorts.add(shttpP);
                //end CR 6430228
            }
        }
        
        
        // Store source xml ports core ports: http,iiop,jms
        // TO-DO collect these ports from all source domains iteratively and store them in sourceXMLCorePorts vector
        // Only for testing purposes.....
    }
    private DomainsProcessor(CommonInfoModel ci, boolean nothing) {
        
    }
    
    public void processTargetDomains() throws HarnessException{
        List domainNames = commonInfo.getDomainList();
        String target = commonInfo.getTargetInstallDir();
        UpgradeUtils upgradeUtils = UpgradeUtils.getUpgradeUtils(commonInfo);        
        //Following lines are copied from IasAdminCommand
        ASenvPropertyReader reader = new ASenvPropertyReader(System.getProperty(SystemPropertyConstants.CONFIG_ROOT_PROPERTY));
        reader.setSystemProperties();
        //initGlobalsManager(null);
        //IasAdminCommand end
        //Added for CR 6480041
        //Build the ClusterInfo obejct for use.		
        if(commonInfo.checkUpgradefrom8xeeto9x()) {
            commonInfo.processDomainXmlForClusters();				
        }				
        //End - added			
        for(int i=0; i<domainNames.size();i++) {
            String sourceDomainName = (String)domainNames.get(i);
            String targetDomainName=sourceDomainName;
            if(!new File(commonInfo.getTargetDomainRoot()).isDirectory()) {
                logger.log(Level.INFO,stringManager.getString("enterprise.tools.upgrade.not_valid_target_install"));
                return;
            }
            File targetDomainUpgrade = new File(commonInfo.getTargetDomainRoot()+File.separator+targetDomainName);
            boolean targetDomainDeleted = false;	    
            if(!commonInfo.isInPlace()) {
                //Delete the existing domain in a SBS upgrade
                if(targetDomainUpgrade.isDirectory()) {
                    targetDomainDeleted = upgradeUtils.deleteDirectory(targetDomainUpgrade); 			
                } else {
                    targetDomainDeleted = true;
                }		    
            } else {
                targetDomainDeleted = true;
            }		
            // I think below condition is reduntant with the all conditions inside
            if(targetDomainDeleted || commonInfo.checkSourceInputAsDomainRoot(commonInfo.getSourceInstallDir())){
                File targetDomainUpgrade80=new File(commonInfo.getTargetDomainRoot()+File.separator+targetDomainName);
                if(targetDomainUpgrade80.isDirectory())   {
                    this.setAdminPortAndSecurity(sourceDomainName,targetDomainName);
                    //start CR 6430228
                    this.setServerIIOPPort(sourceDomainName, targetDomainName);
                    //end CR 6430228
                    continue;
                }
                String[] createDomainCommand = this.getCreateDomainCommand(sourceDomainName,targetDomainName);
                boolean canContinue = executeCommand(createDomainCommand);
                UpdateProgressManager.getProgressManager().setContinueUpgrade(canContinue);               
                if(!canContinue) {
                    throw new HarnessException(stringManager.getString("enterprise.tools.upgrade.domain_creation_error", targetDomainName));
                }
                //executeCommand(createDomainCommand);
                UpdateProgressManager.getProgressManager().processUpgradeUpdateEvent((i*30)/domainNames.size());
            }
            this.setAdminPortAndSecurity(sourceDomainName,targetDomainName);
            //start CR 6430228
            this.setServerIIOPPort(sourceDomainName, targetDomainName);
            //end CR 6430228
        }
        //this.processDomainInstances();
    }
    
    private String[] getCreateDomainCommand(String domainName, String domainName80) {
        /**
         * Port type                     Appserver 8.0                  Appserver 7.0
         * 1. Http                        8080  http-listener-1          80 or 1024- http-listener-1
         * 2. http_ssl                    1043   - http-listener-2       -------- dont know --------
         * 3. JMS                         7676  - default_jms_host       7676 - jms-service
         * 4. IIOP                        3700  - orb-listener-1         3700 - orb-listener-1
         * 5. iiop_ssl                    1060 - ssl                     ---------- dont know -------
         * 6. iiop_mutual_auth            1061 -ssl-math                 ----------   dont know -----
         * 7. admin port                  4848  - admin-listener (httplistener)    4848 - stored in admin-server server.xml
         *
         * http, jms, iiop, and admin ports are transferred from appserver 7.0.
         * Need to pick up appropriate ports for http_ssl, iiop_ssl and iiop_mutual_auth.
         */
        String target = commonInfo.getTargetDomainRoot();
        String domainPath = ((DomainInfo)this.commonInfo.getDomainMapping().get(domainName)).getDomainPath();	
        String adminPort = getSourceAdminPort(domainPath);
        String profile = ((DomainInfo)this.commonInfo.getDomainMapping().get(domainName)).getProfile();	
        //Admin credential changes. Added for CR 6454007
        //Commented for CR 6486068		
        /*String adminUser;
        if(commonInfo.getSourceVersion().equals(UpgradeConstants.VERSION_7X)) {
            adminUser = ((DomainInfo) commonInfo.getDomainMapping().get(domainName)).getDomainAdminUser();
        } else {
            adminUser = commonInfo.getAdminUserName();
        }*/
        //Added - end
		
        //start CR 6430028
        // http, iiop, jms ports are replaced by the migration anyway...
        String httpPort = getAFreePort(8080,10);
        httpPorts.add(httpPort);
        //String httpPort = "8080";
        String jmsPort = "7676";
        String iiopPort = getSourceIIOPPort(((DomainInfo)this.commonInfo.getDomainMapping().
            get(domainName)).getDomainPath());//getAFreePort(3700,10);
        iiopPorts.add(iiopPort);
        //String iiopPort = "3700";
        //end CR 6430028
        
        // Now I need a unique ports for http-ssl,iiop-ssl,iiop-mutual-auth
        String httpSSLPort = getAFreePort(1044,10);
        String iiopSSLPort = getAFreePort(1090,10);
        String iiopSSLMutualAuth = getAFreePort(1091,10);
        //start CR 6407292
        String adminJMXPort = getAFreePort(8686,10);
        //END CR 6397215
        
        adminJMXPorts.add(adminJMXPort);
        //end CR 6407292
        httpSSLPorts.add(httpSSLPort);
        iiopSSLPorts.add(iiopSSLPort);
        iiopMutualAuthPorts.add(iiopSSLMutualAuth);
		//start CR 6430228
        String instancePortAttr = "";
        if(httpPort != null) {
            instancePortAttr = "--instanceport " + httpPort;
        }
        //end CR 6430228
        String propertiesString = "http.ssl.port="+httpSSLPort+":orb.ssl.port="+iiopSSLPort+":orb.mutualauth.port="+iiopSSLMutualAuth+
            ":jms.port="+jmsPort+":orb.listener.port="+iiopPort;  
        propertiesString = propertiesString + ":domain.jmxPort=" + adminJMXPort;

        //START CR 6397215
        // if we are upgrading from 8.x PE to 9.0 PE we need to specify a 
        // JMX connector port
        //if(commonInfo.checkUpgradefrom8xpeto90pe()) {

        String[] createDomainCommand = {"create-domain",
        "--profile",
        "\"" + profile + "\"",	
        "--domaindir",
        "\"" + commonInfo.getTargetDomainRoot() +"\"",
        "--adminport",
        adminPort,
        "--adminuser",
        //Admin credential changes. Added for CR 6454007
        //adminUser,
        commonInfo.getAdminUserName(),
        "--passwordfile ",
        //Admin credential changes. Added for CR 6454007
        //"\"" + commonInfo.getPasswordFile(domainName80) +"\"",
        "\"" + commonInfo.getPasswordFile() +"\"",
        "--savemasterpassword=true",
        //start CR 6430228
        instancePortAttr,
        //end CR 6430228
        "--domainproperties",
        propertiesString,
        domainName80
        };
        return createDomainCommand;
    }
    
    public static String getSourceAdminPort() {
        return getSourceAdminPort(commonInfo.getSourceDomainPath());
    }
    
    // This method returns admin port from admin-server server.xml
    public static String getSourceAdminPort(String domainPath) {
        // Get the admin port from server.xml of admin-server
        if(commonInfo.getSourceVersion().equals(UpgradeConstants.VERSION_7X)) {
            String adminServerXmlFile = domainPath+File.separator+"admin-server"+File.separator+"config"+File.separator+"server.xml";
            String port = getPortFromXML(adminServerXmlFile,"http-listener", "http-listener-1");
            if(port != null)
                return port;
        }else{
            // For 8.x get it from domain.xml
            String domainXmlFile = domainPath+File.separator+"config"+File.separator+"domain.xml";
            if(new File(domainXmlFile).exists()){
                String port = getPortFromXML(domainXmlFile,"http-listener", "admin-listener");
                if(port != null)
                    return port;
            }
        }
        // return some default no....user should change it later.
        adminPortToStartWith =+10;
        return String.valueOf(adminPortToStartWith);
    }
    public static String getSourceAdminSecurity(String domainPath) {
        // Get the admin security-enabled from server.xml of admin-server
        if(commonInfo.getSourceVersion().equals(UpgradeConstants.VERSION_7X)) {
            String adminServerXmlFile = domainPath+File.separator+"admin-server"+File.separator+"config"+File.separator+"server.xml";
            String securityEnabled = getSecurityEnabledFromXML(adminServerXmlFile,"http-listener", "http-listener-1");
            if(securityEnabled != null)
                return securityEnabled;
        }else{
            // For 8.x get it from domain.xml
            String domainXmlFile = domainPath+File.separator+"config"+File.separator+"domain.xml";
            if(new File(domainXmlFile).exists()){
                String securityEnabled = getSecurityEnabledFromXML(domainXmlFile,"http-listener", "admin-listener");
                if(securityEnabled != null)
                    return securityEnabled;
            }
        }
        return "true"; // default to true
    }
    
    public static String getSourceAdminSecurity() {
        String domainPath = commonInfo.getSourceDomainPath();
        return getSourceAdminSecurity(domainPath);
    }
    private void setAdminPortAndSecurity(String sourceDomainName, String targetDomainName){
        String domainPath = ((DomainInfo)this.commonInfo.getDomainMapping().get(sourceDomainName)).getDomainPath();
        String adminPort = getSourceAdminPort(domainPath);
        String securityEnabled = getSourceAdminSecurity(domainPath);
        
        String domainFileName = commonInfo.getTargetDomainRoot()+File.separator+targetDomainName+File.separator+"config"+File.separator+"domain.xml";
        
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        //factory.setValidating(true);
        factory.setNamespaceAware(true);
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            builder.setEntityResolver((org.xml.sax.helpers.DefaultHandler)Class.forName
            ("com.sun.enterprise.config.serverbeans.ServerValidationHandler").newInstance());
            Document resultDoc = builder.parse( new File(domainFileName));
            NodeList taggedElements = resultDoc.getDocumentElement().getElementsByTagName("http-listener");
            for(int lh =0; lh < taggedElements.getLength(); lh++){
                Element element = (Element)taggedElements.item(lh);
                // Compare id attribute of http-listener elements.
                if((element.getAttribute("id")).equals("admin-listener")){
                    element.setAttribute("port",adminPort);
                    //start CR 6360600
                    if(UpgradeConstants.EDITION_EE.equals(commonInfo.getSourceEdition())) {
                        //Do nothing
                    } //end CR 6360600
                    else {
                        element.setAttribute("security-enabled", securityEnabled);
                    }
                    break;
                }
            }
            
          // Use a Transformer for output
          TransformerFactory tFactory = TransformerFactory.newInstance();
          Transformer transformer = tFactory.newTransformer();
          if (resultDoc.getDoctype() != null){
                String systemValue = resultDoc.getDoctype().getSystemId();
                transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, systemValue);
                String pubValue = resultDoc.getDoctype().getPublicId();
                transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, pubValue);
          } 

          DOMSource source = new DOMSource(resultDoc);
          StreamResult result = new StreamResult(new FileOutputStream(domainFileName));
          transformer.transform(source, result);
          result.getOutputStream().close();
          
        }catch (Exception ex){
            logger.log(Level.WARNING, stringManager.getString("domainProcessor.portFromXML"),ex);
            //throw new HarnessException(stringManager.getString("upgrade.transform.startFailureMessage"));
        }
        
    }
    private static String getPortFromXML(String fileName, String tagName, String id) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        //factory.setValidating(true);
        factory.setNamespaceAware(true);
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            builder.setEntityResolver((org.xml.sax.helpers.DefaultHandler)Class.forName
            ("com.sun.enterprise.config.serverbeans.ServerValidationHandler").newInstance());
            Document adminServerDoc = builder.parse( new File(fileName));
            NodeList taggedElements = adminServerDoc.getDocumentElement().getElementsByTagName(tagName);
            for(int lh =0; lh < taggedElements.getLength(); lh++){
                Element element = (Element)taggedElements.item(lh);
                // Compare id attribute of http-listener elements.
                if((element.getAttribute("id")).equals(id)){
                    return element.getAttribute("port");
                }
            }
        }catch (Exception ex){
            logger.log(Level.WARNING, stringManager.getString("domainProcessor.portFromXML"),ex);
            //throw new HarnessException(stringManager.getString("upgrade.transform.startFailureMessage"));
        }
        return null;
    }
    
    private static String getSecurityEnabledFromXML(String fileName, String tagName, String id) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        //factory.setValidating(true);
        factory.setNamespaceAware(true);
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            builder.setEntityResolver((org.xml.sax.helpers.DefaultHandler)Class.forName
            ("com.sun.enterprise.config.serverbeans.ServerValidationHandler").newInstance());
            Document adminServerDoc = builder.parse( new File(fileName));
            NodeList taggedElements = adminServerDoc.getDocumentElement().getElementsByTagName(tagName);
            for(int lh =0; lh < taggedElements.getLength(); lh++){
                Element element = (Element)taggedElements.item(lh);
                // Compare id attribute of http-listener elements.
                if((element.getAttribute("id")).equals(id)){
                    return element.getAttribute("security-enabled");
                }
            }
        }catch (Exception ex){
            logger.log(Level.WARNING, stringManager.getString("domainProcessor.adminSecureFromXML"),ex);
            //throw new HarnessException(stringManager.getString("upgrade.transform.startFailureMessage"));
        }
        return null;
    }
   
    //Added for CR 6480041
	/**
      * This method is called only for 8.2ee -> 9.1ee upgrade.
      * Retrieves the node-agent for the particular instance from the source domain.xml.
      */	  
    private String getSourceNodeAgentForInstance(String domainName, 
            String serverName) {
        String sourceDomainPath = ((DomainInfo)this.commonInfo.getDomainMapping().get(domainName)).getDomainPath();
        String domainXmlFile = sourceDomainPath + File.separator +
                "config" + File.separator + "domain.xml";
        String nodeAgentName = null;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            builder.setEntityResolver((org.xml.sax.helpers.DefaultHandler)Class.forName
                ("com.sun.enterprise.config.serverbeans.ServerValidationHandler").newInstance());
            Document adminServerDoc = builder.parse( new File(domainXmlFile));
            NodeList servers = adminServerDoc.getDocumentElement().getElementsByTagName("servers");
            NodeList serverList =
	            ((Element)servers.item(0)).getElementsByTagName("server");
            for(int lh =0; lh < serverList.getLength(); lh++){
                Element server = (Element)serverList.item(lh);
	            if(serverName.equals(server.getAttribute("name"))) {
                    //Get the node-agent ref for the specific stand-alone server
                    nodeAgentName = server.getAttribute("node-agent-ref");
                    break;					
                }
            }
        }catch (Exception ex){
            logger.log(Level.WARNING, stringManager.getString("domainProcessor.nodeAgentFromXML"),ex);
        }
        return nodeAgentName;
    }
    //end - added

    private String getTargetNodeAgentName(String domainName, 
            CommonInfoModel commonInfoMod){
        String configFileName = commonInfoMod.getTargetDomainRoot() + File.separator
            + domainName + File.separator +"config" + File.separator + "domain.xml";
        return getNodeAgentNameFromXML(configFileName);
    }
    
    private String getNodeAgentNameFromXML(String fileName) {
        if(commonInfo.getSourceVersion().equals(UpgradeConstants.VERSION_7X) || ! new File(fileName).exists()) {
            return null;
        }
        String nodeAgentName = null;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        //factory.setValidating(true);
        factory.setNamespaceAware(true);
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            builder.setEntityResolver((org.xml.sax.helpers.DefaultHandler)Class.forName
                ("com.sun.enterprise.config.serverbeans.ServerValidationHandler").newInstance());
            Document adminServerDoc = builder.parse( new File(fileName));
            NodeList taggedElements = adminServerDoc.getDocumentElement().getElementsByTagName("node-agent");
            Element element = (Element)taggedElements.item(0);
            if(null == element) {
                logger.log(Level.WARNING, stringManager.getString("domainProcessor.nodeAgentFromXML"));
                return null;
            }
            else {
                return element.getAttribute("name");
            }
        }catch (Exception ex){
            logger.log(Level.WARNING, stringManager.getString("domainProcessor.nodeAgentFromXML"),ex);
            //throw new HarnessException(stringManager.getString("upgrade.transform.startFailureMessage"));
        }
        return null;
    }

    private boolean isNodeAgentExists(String agentName, String fileName){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        //factory.setValidating(true);
        factory.setNamespaceAware(true);
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            builder.setEntityResolver((org.xml.sax.helpers.DefaultHandler)Class.forName
            ("com.sun.enterprise.config.serverbeans.ServerValidationHandler").newInstance());
            Document adminServerDoc = builder.parse( new File(fileName));
            NodeList taggedElements = adminServerDoc.getDocumentElement().getElementsByTagName("node-agent");
            for(int lh =0; lh < taggedElements.getLength(); lh++){
                Element itElement = ((Element)taggedElements.item(lh));
                String attrName = itElement.getAttribute("name");
                if(attrName.equals(agentName))
                    return true;
                // If the agentName contains .  example beacon.east, then should only compare to beacon.
                if(agentName.indexOf(".") != -1){
                    if(agentName.substring(0,agentName.indexOf(".")).equals(attrName)){
                        return true;
                    }
                }
            }
        }catch (Exception ex){
            logger.log(Level.WARNING, stringManager.getString("domainProcessor.nodeAgentFromXML"),ex);
            //throw new HarnessException(stringManager.getString("upgrade.transform.startFailureMessage"));
        }
        return false;
    }
    
    public static String getTargetDomainPort(String domainName, CommonInfoModel commonInfoMod){
        String configFileName = commonInfoMod.getTargetDomainRoot()+File.separator+domainName+File.separator+"config"+File.separator+"domain.xml";
        return getPortFromXML(configFileName, "http-listener", "admin-listener");
    }
    
    public static String getTargetDomainSecurity(String domainName, CommonInfoModel commonInfoMod){
        String configFileName = commonInfoMod.getTargetDomainRoot()+File.separator+domainName+File.separator+"config"+File.separator+"domain.xml";
        return getSecurityEnabledFromXML(configFileName, "http-listener", "admin-listener");
    }
    
    private String getAFreePort(int initPortNumber, int increment){
        // Do this only for 20 iterations.  If you cant find one in 10 iterations, then just assign some random number.
        int portNumber = initPortNumber;
        for(int i=0; i<20; i++){
            if(isPortNumberUsable(portNumber))
                return Integer.toString(portNumber);
            portNumber +=increment;
        }
        // In 20 iterations, if we cant find a free port, just return the last port number itereated.
        return Integer.toString(portNumber);
    }
    private boolean isPortNumberUsable(int portNumber){
        // First check if this port exists in any of the lists we have
        String portString = Integer.toString(portNumber);
        for(int i=0; i<httpSSLPorts.size(); i++){
            if(((String)httpSSLPorts.get(i)).equals(portString))
                return false;
        }
        for(int i=0; i<iiopSSLPorts.size(); i++){
            if(((String)iiopSSLPorts.get(i)).equals(portString))
                return false;
        }
        for(int i=0; i<iiopMutualAuthPorts.size(); i++){
            if(((String)iiopMutualAuthPorts.get(i)).equals(portString))
                return false;
        }
        for(int i=0; i<sourceXMLCorePorts.size(); i++){
            if(((String)sourceXMLCorePorts.get(i)).equals(portString))
                return false;
        }
        //start CR 6407292
        for(int i=0; i<adminJMXPorts.size(); i++){
            if(((String)adminJMXPorts.get(i)).equals(portString))
                return false;
        }
        //end CR 6407292
        //start CR 6430228
        for(int i=0; i<iiopPorts.size(); i++){
            if(((String)iiopPorts.get(i)).equals(portString))
                return false;
        }
        for(int i=0; i<httpPorts.size(); i++){
            if(((String)httpPorts.get(i)).equals(portString))
                return false;
        }
        //end CR 6430228
        // This NetUtils class is in appserv-commons module.
        return com.sun.enterprise.util.net.NetUtils.isPortFree(portNumber);
    }
    private java.util.List getInstanceNamesWithoutAdminServerAndServer1(java.util.List instanceList){
        java.util.List newList = new java.util.ArrayList();
        for(java.util.Iterator it = instanceList.iterator(); it.hasNext();){
            String serverName = (String)it.next();
            if(serverName.equals("admin-server")) //|| serverName.equals("server1"))
                continue;
            newList.add(serverName);
        }
        return newList;
    }
    public void processDomainInstances() throws HarnessException {
        // This method creates instances in target installation for every server instance existing in source.
        java.util.Hashtable domainMapping = commonInfo.getDomainMapping();
        
        // Make sure that this is not called on PE
        // Safety check
        //NOT REQUIRED TO MAKE THIS CHECK HERE 
        /*if(commonInfo.getTargetEdition().equals(UpgradeConstants.EDITION_PE)){
            return;
        }*/
        for(java.util.Enumeration domains = domainMapping.keys();domains.hasMoreElements();){
            DomainInfo dInfo = (DomainInfo)domainMapping.get((String)domains.nextElement());
            // creation of server instances required only if there more than 2 servers
            // Is this is valid?   admin-server and server1 are default ones.
            // Fixed:  Many a time when domains are created for 7.x appservers, 
            // it does create only admin-server and may not create server1
            //if(dInfo.getInstanceNames().size() > 2){
            //start CR 6424053
            //boolean domainStarted = false;
            //end CR 6424053
            //if(this.getInstanceNamesWithoutAdminServer(dInfo.getInstanceNames()).size() > 1){
            if(this.getInstanceNamesWithoutAdminServerAndServer1(dInfo.getInstanceNames()).size() > 0){
                // get adminport and adminhost name for the domain.
                String adminPort = this.getTargetDomainPort(dInfo.getDomainName(),this.commonInfo);
                String adminSecurity = this.getTargetDomainSecurity(dInfo.getDomainName(),this.commonInfo);
                String agentName = getTargetNodeAgentName(dInfo.getDomainName(),this.commonInfo);
                //Admin credential changes. Added for CR 6454007
                //Commented for CR 6486068				
                /*String adminUser;
                if(commonInfo.getSourceVersion().equals(UpgradeConstants.VERSION_7X)) {
                    adminUser = dInfo.getDomainAdminUser();
                } else {
                    adminUser = commonInfo.getAdminUserName();
                }*/
                //End - comment				
                //Added - end
                String adminUser = commonInfo.getAdminUserName();				
                //if agentName==null the installer did not create a node agent, so we do
                if ( agentName == null ) {
                    String hostName;
                    try {
                        hostName = (java.net.InetAddress.getLocalHost()).getHostName();
                        //start CR 6361146
                        //start CR 6430234
                        if(dInfo.getDomainName().trim().equals("domain1")) {
                            agentName = hostName;
                        } else {
                            agentName = hostName + "_" + dInfo.getDomainName();
                        }
                        //end CR 6430234
                        //agentName = hostName + "_" + dInfo.getDomainName();
                        //end CR 6361146
                    } catch (java.net.UnknownHostException uhe) {
                        hostName = "localhost";
                        agentName = dInfo.getDomainName() + "-agent";
                    }

                    //start CR 6417438
                    String agentProperties = "remoteclientaddress=" + hostName;
                    //start CR 6361146
                    String configFileName = commonInfo.getTargetDomainRoot() +
                        File.separator + dInfo.getDomainName() + File.separator +
                        "config" + File.separator + "domain.xml";
                    if(!this.isNodeAgentExists(agentName,configFileName)) {
                        //end CR 6361146
                        createNodeAgent(agentName, hostName, adminPort, adminUser, commonInfo.getAdminPassword(),dInfo.getDomainName(),agentProperties);
                        //createNodeAgent(agentName, hostName, adminPort, commonInfo.getAdminUserName(), commonInfo.getAdminPassword(),dInfo.getDomainName(),agentProperties);
		                //end CR 6417438
                        //start CR 6360600
                        this.startDomain(dInfo.getDomainName());
                        //end CR 6360600
                    }
                }
                for(java.util.Iterator instanceNames = dInfo.getInstanceNames().iterator(); instanceNames.hasNext();){
                    String serverName = (String)instanceNames.next();
                    if(!serverName.equals("admin-server")) {
                    //NOT REQUIRED to make this check here		    
                    //!commonInfo.getTargetEdition().equals(UpgradeConstants.EDITION_PE)) { //&& !serverName.equals("server1")){
                        //start CR 6424053
                        this.startDomain(dInfo.getDomainName());
                        //if(!domainStarted){
                        //    if(!this.startDomain(dInfo.getDomainName())){
                        //        throw new HarnessException(stringManager.getString("domainProcessor.domainStartFailed",dInfo.getDomainName()));
                        //    }
                        //    domainStarted = true;
                        //}
                        //end CR 6424053
                        //Added domainName attribute for use by Password File
                        //Admin credential changes. Added for CR 6454007
                        //boolean status = this.createServerInstance(serverName, agentName, null, adminUser, commonInfo.getAdminPassword(), adminPort, adminSecurity, dInfo.getDomainName());
                        boolean status = this.createServerInstance(serverName, agentName, null, commonInfo.getAdminUserName(), commonInfo.getAdminPassword(), adminPort, adminSecurity, dInfo.getDomainName());
                        if(!instanceNames.hasNext()){
                            //start CR 6424053
                            this.stopDomain(dInfo.getDomainName());
                            //if(domainStarted)
                            //    this.stopDomain(dInfo.getDomainName());
                            //end CR 6424053
                        }
                    }
                }
            }
        }
    }
    
    public boolean createNodeAgent(String agentName, String dasHost,
            String dasPort, String dasuser, String daspwd, 
            String domainName, String agentProperties) throws HarnessException {
        String adminSecurity = DomainsProcessor.getTargetDomainSecurity(domainName, commonInfo);
        //start CR 6417438
        if(agentProperties != null && !agentProperties.equals("")) {
            agentProperties = "--agentproperties " + agentProperties;
        } else {
            agentProperties = "";
        }
        //Admin credential changes. Added for CR 6454007
        //String[] command = {"create-node-agent", "--host", dasHost, 
                //"--port", dasPort, "--secure="+adminSecurity, "--user", dasuser, 
                //"--passwordfile ", "\"" + commonInfo.getPasswordFile(domainName) +"\"", 
                //agentProperties, agentName };
	    //String[] command = {"create-node-agent", "--host", dasHost, 
                //"--port", dasPort, "--secure="+adminSecurity, "--user", dasuser, 
                //"--passwordfile ", "\"" + commonInfo.getPasswordFile() +"\"",
                //agentName };
        String[] command = {"create-node-agent", "--host", dasHost, 
                "--port", dasPort, "--secure="+adminSecurity, "--user", dasuser, 
                "--passwordfile ", "\"" + commonInfo.getPasswordFile() +"\"", 
                agentProperties, agentName };
        //end CR 6417438
        //start CR 6360600
        this.stopDomain(domainName);
        //end CR 6360600
        return this.executeCommand(command);
    }
    
    public boolean createConfig(String configName){
        // Still dont know when to use.   will fill in whenever it is required
        return false;
    }
   
    //Added domain name attribute to be used by the Password File
    //Admin credential changes. Added for CR 6454007
    public boolean createServerInstance(String serverName, String agentName, String configName, String userid, String pwd, String adminPort, String adminSecurity, String domainName){
        // if  configName is null, then the command creates serverName_config
        // if nodeAgent does not exist, will create nodeAgent implicitely
        
        //start CR 6430234
        // unique ports for http-ssl,iiop-ssl,iiop-mutual-auth
        String httpSSLPort = getAFreePort(1044,10);
        String iiopSSLPort = getAFreePort(1090,10);
        String iiopSSLMutualAuth = getAFreePort(1091,10);
        String adminJMXPort = getAFreePort(8686,10);
        httpSSLPorts.add(httpSSLPort);
        iiopSSLPorts.add(iiopSSLPort);
        iiopMutualAuthPorts.add(iiopSSLMutualAuth);
        adminJMXPorts.add(adminJMXPort);

        String propertiesString = "HTTP_SSL_LISTENER_PORT=" + httpSSLPort + 
            ":IIOP_SSL_LISTENER_PORT=" + iiopSSLPort + 
            ":IIOP_SSL_MUTUALAUTH_PORT=" + iiopSSLMutualAuth + 
            ":JMX_SYSTEM_CONNECTOR_PORT=" + adminJMXPort;

        //end CR 6430234

        if(configName != null){
            String[] command = {"create-instance", 
                "--nodeagent", agentName,
                "--port", adminPort, 
                "--secure=" + adminSecurity, 
                "--config", configName,
                "--user", userid, 
                //Admin credential changes. Added for CR 6454007
                //"--passwordfile ", "\"" + commonInfo.getPasswordFile(domainName) +"\"", 
                "--passwordfile ", "\"" + commonInfo.getPasswordFile() +"\"", 
                "--systemproperties", propertiesString,
                serverName };
            return this.executeCommand(command);
        }else{
            //String[] command = {"create-instance","--nodeagent",agentName,
            //     "--user", userid, "--password", pwd, serverName };
            String[] command = {"create-instance",
                "--nodeagent", agentName,
                "--user", userid, 
                //Admin credential changes. Added for CR 6454007
                //"--passwordfile ", "\"" + commonInfo.getPasswordFile(domainName) +"\"", 
                "--passwordfile ", "\"" + commonInfo.getPasswordFile() +"\"", 
                "--port", adminPort,
                "--secure="+adminSecurity,
                "--systemproperties", propertiesString,
                serverName };
            return this.executeCommand(command);
        }
    }
    
    private boolean startDomain(String domainName) throws HarnessException {
        return startDomain(domainName, this.commonInfo);
    }

    //start CR 6424053
    public boolean startDomain(String domainName, CommonInfoModel commonInfo) throws HarnessException {
        if(!domainStarted) {
            if(Commands.startDomain(domainName, commonInfo)) {
                domainStarted = true;
                return true;
            } else {
                //throw exception
                throw new HarnessException(stringManager.getString("domainProcessor.domainStartFailed",domainName));
            }
        }
        return false;
    }

    public boolean stopDomain(String domainName) throws HarnessException {
        if(domainStarted ) {
            if(Commands.stopDomain(domainName, commonInfo)) {
               domainStarted = false;
               return true;
            } else {
                //throw exception
                throw new HarnessException(stringManager.getString("enterprise.tools.upgrade.domain_stopping_error",domainName));
            }
        }
        return false;
    }
    
    /*public boolean startDomain(String domainName, CommonInfoModel commonInfo){
        return Commands.startDomain(domainName, commonInfo);
    }
    
    public boolean stopDomain(String domainName){
        return Commands.stopDomain(domainName, commonInfo);
    }*/
    
    //end CR 6424053

    private boolean executeCommand(String[] commandStrings){
        try {
            return Commands.executeCommand(commandStrings);
        } catch (com.sun.enterprise.cli.framework.CommandException ce) {
            //e.printStackTrace();
            Throwable t = ce.getCause();
            CommonInfoModel.getDefaultLogger().log(Level.SEVERE, stringManager.getString("enterprise.tools.upgrade.generalException", ce.getMessage()),ce);
            if (t != null) {
                CommonInfoModel.getDefaultLogger().severe(stringManager.getString("enterprise.tools.upgrade.generalException", t.getMessage()));
            }
        }
        return false;
    }
    public boolean processClusters() throws HarnessException {
        String sourceVersionAndEdition = commonInfo.getSourceVersionAndEdition();		
        java.util.List clInfoList = ClustersInfoManager.getClusterInfoManager().getClusterInfoList();
        if((clInfoList == null) || (clInfoList.isEmpty()))
            return false;
        // Create cluster for each clInfoList.
        int clusterNo = 0;
        for(Iterator it = clInfoList.iterator(); it.hasNext(); ){
            ClusterInfo clInfo = (ClusterInfo)it.next();
            //Added for CR 6480041
            //cluster name got from ClusterInfo object if source is 8.xEE			
            String clusterName = null;
            if(UpgradeConstants.VERSION_AS81_EE.equals(sourceVersionAndEdition) ||
                    UpgradeConstants.VERSION_AS82_EE.equals(sourceVersionAndEdition)) {
                clusterName = clInfo.getClusterName();
            } else {
                clusterName = "cluster_"+Integer.toString(clusterNo++);
            }
            //End - added			
            clInfo.setClusterName(clusterName);
            //this.createCluster(clusterName,clInfo.getMasterInstance().getDomain());
            this.createCluster(clusterName,clInfo.getDomainName());
            /*if(!this.commonInfo.getSourceVersion().equals(UpgradeConstants.VERSION_7X)){
                continue;
            }  */          
            List clInstances = clInfo.getClusteredInstanceList();
            ClusteredInstance masterInstance = clInfo.getMasterInstance();
            //start CR 6424053
            //boolean domainStarted = false;
            //end CR 6424053
            String startedDomainName = null;
            String configName = configName = clusterName+"_config";
            if(masterInstance == null){
                // Is it guaranteed that there will be one master instance always?
                String adminPort = null;
                String adminSecurity = null;
                for(Iterator clInstIt = clInstances.iterator(); clInstIt.hasNext();){
                    ClusteredInstance clusteredInstance = (ClusteredInstance)clInstIt.next();
                    //start CR 6424053
                    startedDomainName = clusteredInstance.getDomain();
                    this.startDomain(startedDomainName);
                    //if(!domainStarted){
                    //    startedDomainName = clusteredInstance.getDomain();
                    //    if(!this.startDomain(startedDomainName)){
                    //        // Could not start domain.  Report the problem and break.
                    //        domainStarted = false;
                    //        throw new HarnessException(stringManager.getString("domainProcessor.domainStartFailed",startedDomainName));
                    //    }
                    //will reach here only if domain has been started successfully
                    adminPort = this.getTargetDomainPort(startedDomainName,this.commonInfo);
                    adminSecurity = this.getTargetDomainSecurity(startedDomainName,this.commonInfo);
                    //domainStarted = true;
                    //}
                    //end CR 6424053
                    this.createClusteredInstance(clusteredInstance,clusterName,startedDomainName,configName,adminPort, adminSecurity);
                    if(!clInstIt.hasNext()){
                        //start CR 6424053
                        //if(domainStarted)
                        this.stopDomain(startedDomainName);
                        //end CR 6424053
                    }
                }
            }else{
                //start CR 6424053
                startDomain(masterInstance.getDomain());
                //if(this.startDomain(masterInstance.getDomain())){
                //    domainStarted = true;
                //will reach here only if domain is started successfully
                String adminPort = this.getTargetDomainPort(masterInstance.getDomain(),this.commonInfo);
                String adminSecurity = this.getTargetDomainSecurity(masterInstance.getDomain(),this.commonInfo);
                this.createClusteredInstance(masterInstance,clusterName,masterInstance.getDomain(),configName,adminPort, adminSecurity);
                for(Iterator clInstIt = clInstances.iterator(); clInstIt.hasNext();){
                    ClusteredInstance clInst = (ClusteredInstance)clInstIt.next();
                    if(!clInst.isMaster())
                        this.createClusteredInstance(clInst,clusterName,masterInstance.getDomain(),configName,adminPort, adminSecurity);
                    if(!clInstIt.hasNext()){
                        //if(domainStarted)
                        this.stopDomain(masterInstance.getDomain());
                    }
                }
                //}else{
                //    throw new HarnessException(stringManager.getString("domainProcessor.domainStartFailed",masterInstance.getDomain()));
                //}
                //end CR 6424053
            }
        }
        // Set currentCluster to null;
        this.commonInfo.setCurrentCluster(null);
        this.processStandAloneInstances();
        return true;
    }

    private boolean createClusteredInstance(ClusteredInstance clInstance, 
            String clusterName, String domainName, String configName, 
            String adminPort, String adminSecurity) throws HarnessException {
        String nodeAgentName = clInstance.getHost();
        String dasHostName = null;
        //start CR 6417438
        String agentProperties = null;
        //end CR 6417438
        //Admin credential changes. Added for CR 6454007
        //Commented for CR 6486068		
        /*java.util.Hashtable domainMapping = commonInfo.getDomainMapping();
        DomainInfo dInfo = (DomainInfo)domainMapping.get(domainName);
        String adminUser;
        if(commonInfo.getSourceVersion().equals(UpgradeConstants.VERSION_7X)) {
            adminUser = dInfo.getDomainAdminUser();
        } else {
            adminUser = commonInfo.getAdminUserName();
        }*/
        //End - comment		
        //Added - end	
        try {
            dasHostName = (java.net.InetAddress.getLocalHost()).getHostName();
        } catch (java.net.UnknownHostException uhe) {
            dasHostName = domainName;
        }
        if(nodeAgentName.equals("localhost")){
            //Added for CR 6417438
            agentProperties = "remoteclientaddress=" + dasHostName;
            //start CR 6361146
            //start CR 6430234
            if(domainName.trim().equals("domain1")) {
                //DAS domain
                nodeAgentName = dasHostName;
            } else {
                nodeAgentName = dasHostName + "_" + domainName;
            }
            //end CR 6430234
            //nodeAgentName = dasHostName + "_" + domainName;
            //end CR 6361146
        } else {
            //Added for CR 6417438
            agentProperties = "remoteclientaddress=" + nodeAgentName;
            //nodeAgentName = nodeAgentName + "_" + domainName;
            //Added for CR 6480041
            nodeAgentName = nodeAgentName;
        }
        String configFileName = commonInfo.getTargetDomainRoot() +
                File.separator + domainName + File.separator +
                "config" + File.separator + "domain.xml";
        if(!this.isNodeAgentExists(nodeAgentName,configFileName)){
            //start CR 6417438
            //createNodeAgent(nodeAgentName, dasHostName, clInstance.getPort(), 
            //        commonInfo.getAdminUserName(), commonInfo.getAdminPassword(),domainName);
            //Admin credential changes. Added for CR 6454007
            //createNodeAgent(nodeAgentName, dasHostName, clInstance.getPort(), adminUser, 
                    //commonInfo.getAdminPassword(),domainName,agentProperties);
            createNodeAgent(nodeAgentName, dasHostName, clInstance.getPort(), 
                    commonInfo.getAdminUserName(), commonInfo.getAdminPassword(),domainName,agentProperties);
            //end CR 6417438
            //start CR 6360600
            this.startDomain(domainName);
            //end CR 6360600
        }
        //String property = http-listener-1-port=8078:HTTP_SSL_LISTENER_PORT=1041:IIOP_LISTENER_PORT=3698:IIOP_SSL_LISTENER_PORT=1051:IIOP_SSL_MUTUALAUTH_PORT=1052:JMX_SYSTEM_CONNECTOR_PORT=8688
        // I must use the data stored in clInstance to create the server instance by setting property.
        // Config name and cluster name cannot both be specified.
        //Admin credential changes. Added for CR 6454007
        String user = commonInfo.getAdminUserName();
        String password = commonInfo.getAdminPassword();

        //start CR 6430234
        // unique ports for http-ssl,iiop-ssl,iiop-mutual-auth
        String httpSSLPort = getAFreePort(1044,10);
        String iiopSSLPort = getAFreePort(1090,10);
        String iiopSSLMutualAuth = getAFreePort(1091,10);
        String adminJMXPort = getAFreePort(8686,10);
        httpSSLPorts.add(httpSSLPort);
        iiopSSLPorts.add(iiopSSLPort);
        iiopMutualAuthPorts.add(iiopSSLMutualAuth);
        adminJMXPorts.add(adminJMXPort);

        String propertiesString = "HTTP_SSL_LISTENER_PORT=" + httpSSLPort +
            ":IIOP_SSL_LISTENER_PORT=" + iiopSSLPort + 
            ":IIOP_SSL_MUTUALAUTH_PORT=" + iiopSSLMutualAuth + 
            ":JMX_SYSTEM_CONNECTOR_PORT=" + adminJMXPort;

        //end CR 6430234

        String[] command = {"create-instance",
            //Admin credential changes. Added for CR 6454007
            //"--user", adminUser, 
            "--user", user, 
            //Admin credential changes. Added for CR 6454007
            //"--passwordfile ", "\"" + commonInfo.getPasswordFile(domainName) +"\"",
            "--passwordfile ", "\"" + commonInfo.getPasswordFile() +"\"",
            "--nodeagent", nodeAgentName,
            "--port",adminPort, 
            "--secure=" + adminSecurity,
            "--cluster", clusterName,
            "--systemproperties", propertiesString,
            clInstance.getInstanceName()};
        return this.executeCommand(command);
    }

    private boolean createCluster(String clusterName, String domainName) throws HarnessException{
        String adminSecurity = null;
        String adminPort = null;
        if(domainName != null){
            this.startDomain(domainName);
            adminPort = this.getTargetDomainPort(domainName, this.commonInfo);
            adminSecurity = this.getTargetDomainSecurity(domainName, this.commonInfo);
        }else{
            // This should be fixed.  This is not typical.  Domain name is a must.
        }
        //Admin credential changes. Added for CR 6454007
        //Commented for CR 6486068		
        /*java.util.Hashtable domainMapping = commonInfo.getDomainMapping();
        DomainInfo dInfo = (DomainInfo)domainMapping.get(domainName);
        String adminUser;
        if(commonInfo.getSourceVersion().equals(UpgradeConstants.VERSION_7X)) {
            adminUser = dInfo.getDomainAdminUser();
        } else {
            adminUser = commonInfo.getAdminUserName();
        }*/
        //End - comment		
        //Added - end
        String adminUser = commonInfo.getAdminUserName();	
	    //Admin credential changes. Added for CR 6454007
        //String[] command = {"create-cluster","--port",adminPort, 
                //"--secure="+adminSecurity,"--user",adminUser,
                //"--passwordfile ", "\"" + commonInfo.getPasswordFile(domainName) +"\"",
                //clusterName};
        String[] command = {"create-cluster","--port",adminPort, 
                "--secure="+adminSecurity,"--user",adminUser,
                "--passwordfile ", "\"" + commonInfo.getPasswordFile() +"\"",
                clusterName};
        boolean returnStatus = this.executeCommand(command);
        this.stopDomain(domainName);
        return returnStatus;
    }
    public void processStandAloneInstances() throws HarnessException {
        //Commented for CR 6480041
        //Stand alone instances should be created afresh rather than transforming.
        //This reduces the overhead of introducing the new elements in the dtd.		
        /*if(!this.commonInfo.getSourceVersion().equals(UpgradeConstants.VERSION_7X)){
            // If the source is AS8.xEE then there server elements are migrated during transformation.
            return;
        } */
        //End - edit	
        List stdAloneInsts = null;		
        UpgradeUtils upgradeUtils = UpgradeUtils.getUpgradeUtils(commonInfo);
        String sourceVersion = commonInfo.getSourceVersion();		
        if(UpgradeConstants.VERSION_7X.equals(sourceVersion)) {		
            stdAloneInsts = upgradeUtils.getStandAloneInstances(commonInfo.getDomainMapping());
        } else {
            stdAloneInsts = upgradeUtils.getStandAloneInstancesFromDomainXml(commonInfo.getDomainMapping());
        }
        if(stdAloneInsts == null) {
            return;
        }			
        for(Iterator it = stdAloneInsts.iterator(); it.hasNext();){
            Vector instDInfo = (Vector)it.next();
            String serverName = (String)instDInfo.elementAt(0);
            DomainInfo dInfo = (DomainInfo)instDInfo.elementAt(1);
            String adminPort = this.getTargetDomainPort(dInfo.getDomainName(),this.commonInfo);
            String adminSecurity = this.getTargetDomainSecurity(dInfo.getDomainName(),this.commonInfo);
            //Added for CR 6480041
            //Get the nodeagent name from domain.xml if 8.x->9.1ee			
            String domainName = dInfo.getDomainName();			
            String agentName = null;
            if(UpgradeConstants.VERSION_7X.equals(sourceVersion)) {
                agentName = getTargetNodeAgentName(domainName, this.commonInfo);
            } else {				
		        agentName = getSourceNodeAgentForInstance(domainName, serverName);
            }				
            //End - added			
            //Admin credential changes. Added for CR 6454007
            //Commented for CR 6486068		   
            /*String adminUser;
            if(UpgradeConstants.VERSION_7X.equals(sourceVersion)) {
                adminUser = dInfo.getDomainAdminUser();
            } else {
                adminUser = commonInfo.getAdminUserName();
            }*/
            //End - comment			
            //Added - end
            //start CR 6424053
            this.startDomain(dInfo.getDomainName());
            //if(!this.startDomain(dInfo.getDomainName())){
            //throw new HarnessException(stringManager.getString("domainProcessor.domainStartFailed",dInfo.getDomainName()));
            //}
            //end CR 6424053
            String hostName;			
            String agentProperties;			
            if ( agentName == null ) {
                try {				
                    hostName = (java.net.InetAddress.getLocalHost()).getHostName();
                    //start CR 6361146
                    //start CR 6430234
                    if(dInfo.getDomainName().trim().equals("domain1")) {
                        agentName = hostName;
                    } else {
                        agentName = hostName + "_" + dInfo.getDomainName();
                    }
                    //end CR 6430234
                    //agentName = hostName + "_" + dInfo.getDomainName();
                    //end CR 6361146
                } catch (java.net.UnknownHostException uhe) {
                    hostName = "localhost";
                    agentName = dInfo.getDomainName() + "-agent";
                }
                agentProperties = "remoteclientaddress=" + hostName;				
            } else {
                try {
                    hostName = (java.net.InetAddress.getLocalHost()).getHostName();
                } catch (java.net.UnknownHostException uhe) {
                    hostName = "localhost";
                }
                agentProperties = "remoteclientaddress=" + hostName;				
            }                					
            //start CR 6417438
            //String agentProperties = "remoteclientaddress=" + hostName;
            //start CR 6361146
            String configFileName = commonInfo.getTargetDomainRoot() + 
                File.separator + dInfo.getDomainName() + File.separator +
                "config" + File.separator + "domain.xml";
            if(!this.isNodeAgentExists(agentName,configFileName)) {
                //end CR 6361146
                //Admin credential changes. Added for CR 6454007
                //createNodeAgent(agentName, hostName, adminPort, adminUser, 
                    //commonInfo.getAdminPassword(),dInfo.getDomainName(), agentProperties);
                createNodeAgent(agentName, hostName, adminPort, 
                    commonInfo.getAdminUserName(), commonInfo.getAdminPassword(),
                    dInfo.getDomainName(), agentProperties);
                //end CR 6417438
                //start CR 6360600
                this.startDomain(dInfo.getDomainName());
                //end CR 6360600
            }
                        
            if(!serverName.equals("admin-server")) { // && !serverName.equals("server1")){
                //Added domainName attribute for use by Password file
                //Admin credential changes. Added for CR 6454007
                //boolean status = this.createServerInstance(serverName, agentName, null, 
                        //adminUser, commonInfo.getAdminPassword(),adminPort, 
                        //adminSecurity, dInfo.getDomainName());
                boolean status = this.createServerInstance(serverName, agentName, null, 
                        commonInfo.getAdminUserName(), commonInfo.getAdminPassword(),
                        adminPort, adminSecurity, dInfo.getDomainName());
            }
            this.stopDomain(dInfo.getDomainName());
        }
    }

    //start CR 6407292
    private static String getJMXPortFromXML(String fileName, String tagName, String name) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            builder.setEntityResolver((org.xml.sax.helpers.DefaultHandler)Class.forName
            ("com.sun.enterprise.config.serverbeans.ServerValidationHandler").newInstance());
            Document adminServerDoc = builder.parse( new File(fileName));
            NodeList taggedElements = adminServerDoc.getDocumentElement().getElementsByTagName(tagName);
            for(int lh =0; lh < taggedElements.getLength(); lh++){
                Element element = (Element)taggedElements.item(lh);
                // Compare id attribute of http-listener elements.
                if((element.getAttribute("name")).equals(name)){
                    return element.getAttribute("port");
                }
            }
        }catch (Exception ex){
            logger.log(Level.WARNING, stringManager.getString("domainProcessor.portFromXML"),ex);
            //throw new HarnessException(stringManager.getString("upgrade.transform.startFailureMessage"));
        }
        return null;
    }
    //end CR 6407292

    //start CR 6430228
    // This method returns iiop orb-listener-1 port 
    //from domain.xml or server.xml
    public static String getSourceIIOPPort(String domainPath) {
        // Get the orb-listener-1 port from server.xml of admin-server
        if(commonInfo.getSourceVersion().equals(UpgradeConstants.VERSION_7X)) {
            String adminServerXmlFile = domainPath+File.separator+"admin-server"+File.separator+"config"+File.separator+"server.xml";
            String port = getPortFromXML(adminServerXmlFile,"iiop-listener", "orb-listener-1");
            if(port != null)
                return port;
        }else{
            // For 8.x get it from domain.xml
            String domainXmlFile = domainPath+File.separator+"config"+File.separator+"domain.xml";
            if(new File(domainXmlFile).exists()){
                String port = getPortFromXML(domainXmlFile,"iiop-listener", "orb-listener-1");
                if(port != null)
                    return port;
            }
        }
        // return some default no....user should change it later.
        iiopPortToStartWith =+10;
        return String.valueOf(iiopPortToStartWith);
    }

    private void setServerIIOPPort(String sourceDomainName, String targetDomainName){
        String domainPath = ((DomainInfo)this.commonInfo.getDomainMapping().get(sourceDomainName)).getDomainPath();
        String iiopPort = getSourceIIOPPort(domainPath);

        String domainFileName = commonInfo.getTargetDomainRoot() + File.separator +
                targetDomainName + File.separator + "config" + File.separator + "domain.xml";

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            builder.setEntityResolver((org.xml.sax.helpers.DefaultHandler)Class.forName
                ("com.sun.enterprise.config.serverbeans.ServerValidationHandler").newInstance());
            Document resultDoc = builder.parse( new File(domainFileName));
            NodeList configElements = resultDoc.getDocumentElement().getElementsByTagName("configs");
            NodeList configList = ((Element)configElements.item(0)).getElementsByTagName("config");
            for(int i=0; i<configList.getLength(); i++) {
                Element configElement = (Element)configList.item(i);
                //If this is a server-config element, then transfer the iiop ports
                if((configElement.getAttribute("name")).equals("server-config")) {
                    NodeList iiopListenerElements = configElement.getElementsByTagName("iiop-listener");
                    for(int lh =0; lh < iiopListenerElements.getLength(); lh++){
                        Element element = (Element)iiopListenerElements.item(lh);
                        // Compare id attribute of iiop-listener elements.
                        if((element.getAttribute("id")).equals("orb-listener-1")){
                            element.setAttribute("port",iiopPort);
                            break;
                        }
                    }
                }
            }

          // Use a Transformer for output
          TransformerFactory tFactory = TransformerFactory.newInstance();
          Transformer transformer = tFactory.newTransformer();
          if (resultDoc.getDoctype() != null){
                String systemValue = resultDoc.getDoctype().getSystemId();
                transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, systemValue);
                String pubValue = resultDoc.getDoctype().getPublicId();
                transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, pubValue);
          }

          DOMSource source = new DOMSource(resultDoc);
          StreamResult result = new StreamResult(new FileOutputStream(domainFileName));
          transformer.transform(source, result);
          result.getOutputStream().close();

        }catch (Exception ex){
            logger.log(Level.WARNING, stringManager.getString("domainProcessor.portFromXML"),ex);
            //throw new HarnessException(stringManager.getString("upgrade.transform.startFailureMessage"));
        }

    }

    //end CR 6430228
}
