/*
 * 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.
 */

/*
 * AppDD.java
 *
 * Created on December 7, 2001, 1:48 PM
 */

package com.sun.enterprise.deployment.backend;

import java.io.*;
import java.util.*;
import java.util.logging.*;

import javax.enterprise.deploy.shared.ModuleType;

import com.sun.enterprise.deployment.Application;
import com.sun.enterprise.deployment.io.ApplicationDeploymentDescriptorFile;
import com.sun.enterprise.deployment.io.runtime.ApplicationRuntimeDDFile;
import com.sun.enterprise.deployment.util.ModuleDescriptor;

import org.xml.sax.SAXParseException;
import com.sun.enterprise.util.i18n.StringManager;
import com.sun.enterprise.deployment.util.LogDomains;


/** Code for parsing out the names of all modules in Application.xml
 *
 * @author  bnevins
 * @version 
 */

public class AppDD 
{
	public AppDD(File f) throws IASDeploymentException, IOException, SAXParseException
	{
		this(f, false);
	}

	///////////////////////////////////////////////////////////////////////////

	public AppDD(File f, boolean validateXML) throws IASDeploymentException, IOException, SAXParseException
	{
		if(f == null || !f.exists()) {
			String msg = localStrings.getString(
					"enterprise.deployment.backend.bad_file_parameter", f );
			throw new IllegalArgumentException( msg );
		}
		
                File f2 = null;
		if(f.isDirectory())
		{
			File f1 = new File(f, "META-INF");
			f = new File(f1, "application.xml");//noi18n
			f2 = new File(f1, "sun-application.xml");//noi18n
		}

		//4669843 - 5/2/02 WBN: changed message and type of Exception -- it used to be IllegalArgumentException
		if(!f.exists() || f.isDirectory())  {
			String msg = localStrings.getString(
					"enterprise.deployment.backend.no_application_xml",
					f.getPath() );
			throw new IASDeploymentException( msg );
		}
		
		file = f;

                if(f2 != null && f2.exists() && f2.isFile())  {
                    file2 = f2;
                }

		try
		{
			parse(validateXML);
		}
		catch(Throwable t)
		{
                    
                    t.printStackTrace();
                    if(t instanceof IASDeploymentException)
                        throw (IASDeploymentException) t;
                    else {
                        String msg = localStrings.getString(
                        "enterprise.deployment.backend.error_parsing_application_xml",
                        file.getPath(), t );
                        throw new IASDeploymentException( msg, t );
                    }
		}
	}

	///////////////////////////////////////////////////////////////////////////

        public Application getApplication()
        {
         
                return app;
        }

	public String[] getEjbModules()
	{
		String[] ss = new String[ejbModules.size()];
		
		return (String[])ejbModules.toArray(ss);
	}

	///////////////////////////////////////////////////////////////////////////

	public String[] getWarModules()
	{
		String[] ss = new String[warModules.size()];
		
		return (String[])warModules.toArray(ss);
	}

	///////////////////////////////////////////////////////////////////////////

	public String[] getRarModules()
	{
		String[] ss = new String[rarModules.size()];
		
		return (String[])rarModules.toArray(ss);
	}

	///////////////////////////////////////////////////////////////////////////

	public String[] getClientModules()
	{
		String[] ss = new String[clientModules.size()];
		
		return (String[])clientModules.toArray(ss);
	}

	///////////////////////////////////////////////////////////////////////////

	public String[] getContextRoots()
	{
		String[] ss = new String[contextRoots.size()];
		
		return (String[])contextRoots.toArray(ss);
	}

	///////////////////////////////////////////////////////////////////////////

	public File getFile()
	{
		return file;
	}
	
	///////////////////////////////////////////////////////////////////////////

        private void parse(boolean validateXML) throws IASDeploymentException, IOException, SAXParseException
	{
            FileInputStream fis = null;
            try {
		fis = new FileInputStream(file);
		ApplicationDeploymentDescriptorFile addf = new ApplicationDeploymentDescriptorFile();
                addf.setXMLValidation(validateXML);
                if (validateXML) {
                    addf.setXMLValidationLevel(addf.PARSING_VALIDATION);
                }

                app = (Application) addf.read(fis);

                // read runtime deployment descriptor file if it exists
                if (file2 != null) { 
                    FileInputStream fis2 = new FileInputStream(file2);
		    ApplicationRuntimeDDFile arddf = 
                        new ApplicationRuntimeDDFile();
                    arddf.setXMLValidation(validateXML);
                    if (validateXML) {
                        arddf.setXMLValidationLevel(arddf.PARSING_VALIDATION);
                    }
                    app = (Application)arddf.read(app, fis2); 
                    if (fis2 != null) {
                        fis2.close();
                    }

                }

		// WBN 4-19-2002 -- If we are using this class ONLY for getting
		// context-roots -- please note that node.getApplication(null) has 
		// already done all the time-consuming work.  The getXXXX methods 
		// simply return a reference.  So performance isn't an issue.
                
                for (Iterator modules = app.getModules(); modules.hasNext();) {
                    ModuleDescriptor md = (ModuleDescriptor) modules.next();
                    if (md.getModuleType().equals(ModuleType.EJB)) {
                        ejbModules.add(md.getArchiveUri());
                    } else 
                    if (md.getModuleType().equals(ModuleType.WAR)) {
                        warModules.add(md.getArchiveUri());
                    } else 
                    if (md.getModuleType().equals(ModuleType.CAR)) {
                        clientModules.add(md.getArchiveUri());
                    } else 
                    if (md.getModuleType().equals(ModuleType.RAR)) {
                        rarModules.add(md.getArchiveUri());
                    }                          
                }

		setContextRoots(app);
            } finally {
                if (fis != null) {
                    fis.close();
                }
            }
	}		

	///////////////////////////////////////////////////////////////////////////

	private void setContextRoots(Application app) throws IASDeploymentException
	{
            assert app		!= null;
            assert warModules	!= null;
            assert contextRoots	== null;  // error to call this method more than once
            
            contextRoots = new HashSet();
            
            for(Iterator it = warModules.iterator(); it.hasNext(); ) {
                
                ModuleDescriptor md = app.getModuleDescriptorByUri((String) it.next());
                String cr = md.getContextRoot();                
                
                if(contextRoots.add(cr) == false) {
                    // this means that there is more than one web-module
                    // in the Application with the same context-root
                    
                    String msg = localStrings.getString(
                    "enterprise.deployment.backend.duplicate_context_root",
                    cr );
                    throw new IASDeploymentException( msg );
                }
            }
	}
        
	///////////////////////////////////////////////////////////////////////////

	private String trim(String s)
	{
		// change <ejb>xxx</ejb> to xxx
		
		int index = s.indexOf(">");
		String ret = s.substring(index + 1);
		ret = ret.substring(0, ret.indexOf("<"));
		
		return ret;
	}
	
	///////////////////////////////////////////////////////////////////////////

	private File			file			= null;
	private File			file2			= null;
	private Set				ejbModules = new HashSet();
	private Set				warModules = new HashSet();
	private Set				rarModules = new HashSet();
	private Set				clientModules = new HashSet();
	private Application app = null;
	private Set				contextRoots	= null;
	private final Logger	logger			= LogDomains.getLogger(LogDomains.DPL_LOGGER);
    private static StringManager localStrings =
        StringManager.getManager( AppDD.class );
}
