//----------------------------BEGIN LICENSE----------------------------
/* 
 * Willow : the Open Source WorkFlow Project
 * Distributable under GNU LGPL license by gun.org
 *
 * Copyright (C) 2004-2010 huihoo.org 
 * Copyright (C) 2004-2010  ZosaTapo <dertyang@hotmail.com> 
 * 
 * ====================================================================
 * Project Homepage : http://www.huihoo.org/willow
 * Source Forge     : http://sourceforge.net/projects/huihoo
 * Mailing list     : willow@lists.sourceforge.net 
 */
//----------------------------END  LICENSE----------------------------
package org.huihoo.workflow.desktop.helpers;

import java.io.InputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Properties;

import org.huihoo.workflow.desktop.WorkflowDesktop;

public class PropertyUtils
{
	private static PropertyUtils helper = null;
	private boolean getSystemPropsFailed = false;

	final static String[] PROPS = new String[] { WorkflowDesktop.INITIAL_DESKTOP_FACTORY, WorkflowDesktop.PROVIDER_URL };

	public final static int INITIAL_CLIENT_FACTORY = 0;
	public final static int PROVIDER_URL = 1;

	PropertyUtils()
	{
	} 

	static {
		helper = new PropertyUtils();
	}

	public static PropertyUtils getUtils()
	{
		return helper;
	}

	String getProperty(final int i)
	{
		return (String) AccessController.doPrivileged(new PrivilegedAction()
		{
			public Object run()
			{
				try
				{
					return System.getProperty(PROPS[i]);
				}
				catch (SecurityException e)
				{
					return null;
				}
			}
		});
	}

	String[] getProperties()
	{
		if (getSystemPropsFailed)
		{
			return null; // after one failure, don't bother trying again
		}
		Properties sysProps = (Properties) AccessController.doPrivileged(new PrivilegedAction()
		{
			public Object run()
			{
				try
				{
					return System.getProperties();
				}
				catch (SecurityException e)
				{
					getSystemPropsFailed = true;
					return null;
				}
			}
		});
		if (sysProps == null)
		{
			return null;
		}
		String[] wfnProps = new String[PROPS.length];
		for (int i = 0; i < PROPS.length; i++)
		{
			wfnProps[i] = sysProps.getProperty(PROPS[i]);
		}
		return wfnProps;
	}

	InputStream getResourceAsStream(final Class c, final String name)
	{
		return (InputStream) AccessController.doPrivileged(new PrivilegedAction()
		{
			public Object run()
			{
				return c.getResourceAsStream(name);
			}
		});
	}
}