/*
 * Created on 2004-9-5
 *
 * To change the template for this generated file go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
package org.huihoo.willow.tomcat;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;

/**
 * @author reic
 *
 * To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
public class CatalinaProperties
{

	// ------------------------------------------------------- Static Variables

	private static Properties properties = null;

	static {

		loadProperties();

	}

	// --------------------------------------------------------- Public Methods

	/**
	 * Return specified property value.
	 */
	public static String getProperty(String name)
	{

		return properties.getProperty(name);

	}

	/**
	 * Return specified property value.
	 */
	public static String getProperty(String name, String defaultValue)
	{

		return properties.getProperty(name, defaultValue);

	}

	// --------------------------------------------------------- Public Methods

	/**
	 * Load properties.
	 */
	private static void loadProperties()
	{

		InputStream is = null;
		Throwable error = null;

		try
		{
			String configUrl = getConfigUrl();
			if (configUrl != null)
			{
				is = (new URL(configUrl)).openStream();
			}
		}
		catch (Throwable t)
		{
			// Ignore
		}

		if (is == null)
		{
			try
			{
				File home = new File(getCatalinaHome());
				File conf = new File(home, "conf");
				File properties = new File(conf, "catalina.properties");
				is = new FileInputStream(properties);
			}
			catch (Throwable t)
			{
				// Ignore
			}
		}

		if (is == null)
		{
			try
			{
				is =
					CatalinaProperties.class.getResourceAsStream(
						"/org/apache/catalina/startup/catalina.properties");
			}
			catch (Throwable t)
			{
				// Ignore
			}
		}

		if (is != null)
		{
			try
			{
				properties = new Properties();
				properties.load(is);
				is.close();
			}
			catch (Throwable t)
			{
				error = t;
			}
		}

		if ((is == null) || (error != null))
		{
			// Do something
			System.out.println("Error");
		}

		// Register the properties as system properties
		Enumeration enum = properties.propertyNames();
		while (enum.hasMoreElements())
		{
			String name = (String) enum.nextElement();
			String value = properties.getProperty(name);
			if (value != null)
			{
				System.setProperty(name, value);
			}
		}

	}

	/**
	 * Get the value of the catalina.home environment variable.
	 */
	private static String getCatalinaHome()
	{
		return System.getProperty("catalina.home", System.getProperty("user.dir"));
	}

	/**
	 * Get the value of the configuration URL.
	 */
	private static String getConfigUrl()
	{
		return System.getProperty("catalina.config");
	}

}