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

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 Administrator
 *
 * To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
public class WillowProperties
{
	// ------------------------------------------------------- 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(getWillowHome());
				File conf = new File(home, "conf");
				File properties = new File(conf, "willow.properties");
				is = new FileInputStream(properties);
			}
			catch (Throwable t)
			{
				// Ignore
			}
		}

		if (is == null)
		{
			try
			{
				is =
					WillowProperties.class.getResourceAsStream(
						"/org/huihoo/willow/startup/willow.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 willow.home environment variable.
	 */
	private static String getWillowHome()
	{
		return System.getProperty("willow.home", System.getProperty("user.dir"));
	}

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

}
