package examples.security.util;


import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Properties;

/**
 *
 * @author Copyright (c) 2000 by BEA Systems, Inc. All Rights Reserved.
 */

public class RealmProperties
{
  private Properties props;
  
  private String prefix;
  
  public RealmProperties(Class clazz, String source, String prefix)
    throws IOException
  {
    props = getProperties(clazz, source);
    this.prefix = prefix;
  }

  
  public RealmProperties(Class clazz, String source)
    throws IOException
  {
    this(clazz, source, "");
  }

  
  public static Properties getProperties(Class clazz, String source)
    throws IOException
  {
    Properties props = new Properties(System.getProperties());
    InputStream in = null;
    
    try
    {
      in = new FileInputStream(source);
    }
    catch (IOException e)
    {
      // ignore
    }

    if (in == null)
    {
      in = clazz.getResourceAsStream(source);

      if (in == null)
      {
	throw new FileNotFoundException("properties file not found in current directory or classpath");
      }
    }
      
    props.load(in);

    return props;
  }


  public String get(String name, String fallback)
  {
    return getString(name, fallback);
  }


  public String get(String name)
  {
    return getString(name, null);
  }


  public String getString(String name, String fallback)
  {
    return props.getProperty(prefix + name, fallback);
  }


  public String getString(String name)
  {
    return props.getProperty(prefix + name);
  }


  public int getInteger(String name, int fallback)
  {
    String val;

    if ((val = props.getProperty(prefix + name)) == null)
    {
      return fallback;
    }

    return Integer.parseInt(val);
  }


  public long getLong(String name, long fallback)
  {
    String val;

    if ((val = props.getProperty(prefix + name)) == null)
    {
      return fallback;
    }

    return Long.parseLong(val);
  }


  public short getShort(String name, short fallback)
  {
    String val;

    if ((val = props.getProperty(prefix + name)) == null)
    {
      return fallback;
    }

    return Short.parseShort(val);
  }


  public boolean getBoolean(String name, boolean fallback)
  {
    String val;

    if ((val = props.getProperty(prefix + name)) == null)
    {
      return fallback;
    }

    return Boolean.valueOf(val).booleanValue();
  }


  public float getFloat(String name, float fallback)
  {
    String val;

    if ((val = props.getProperty(prefix + name)) == null)
    {
      return fallback;
    }

    return Float.valueOf(val).floatValue();
  }


  public double getDouble(String name, double fallback)
  {
    String val;

    if ((val = props.getProperty(prefix + name)) == null)
    {
      return fallback;
    }

    return Double.valueOf(val).doubleValue();
  }
}
