//[singleton1.
package io;

import java.io.*;
import java.net.*;
import java.util.*;


/**
 * A ResourceFinder is used to find a "resource" either in
 * the .jar file (containing the ResourceFinder class)
 * or in the local file system
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class ResourceFinder
{
    private static final ResourceFinder instance = 
                                         new ResourceFinder();    


    /**
     * Create an instance of a ResourceFinder
     *
     * @return   The instance
     */
    public static ResourceFinder createInstance()
    {
       return instance;       
    }
//]singleton1.    

//[findInputStream.

    /**
     * Find a resource
     *
     * @return  The InputStream of the resource (or null)
     */
    public InputStream findInputStream(String name)
    {
       Class          c;       
       InputStream    is;

       // Get the Class for this class
       c     = this.getClass(); 

       // Get a URL for the resource
       is    = c.getResourceAsStream(name);

       
       return is;       
    }
//]findInputStream.

//[findURL.

    /**
     * Find a resource
     *
     * @return  The URL of the resource (or null)
     */
    public URL findURL(String name)
    {
       Class          c;       
       URL            url;

       // Get the Class for this class
       c     = this.getClass(); 

       // Get a URL for the resource
       url   = c.getResource(name);

       
       return url;       
    }
//]findURL.


//[loadResourceNames.

    /**
     * Load a list of resource names from a list (e.g., file)
     *
     * Note: This method does not return an array of InputStream
     * objects to conserver resources.
     *
     * @param  listName  The name of the list
     * @return           The resource names
     */
    public String[] loadResourceNames(String listName)
    {
       ArrayList<String>        buffer;       
       BufferedReader           in;       
       InputStream              is;
       String                   line;       
       String[]                 names;
       
       names = null;       
       is    = findInputStream(listName);

       if (is != null)
       {
          try
          {
             in     = new BufferedReader(new InputStreamReader(is));
             buffer = new ArrayList<String>();
             
             while ((line=in.readLine()) != null)
             {
                buffer.add(line);
             }
             names = new String[buffer.size()];             
             buffer.toArray(names);             
          }
          catch (IOException ioe)
          {
             // Can't read the list
          }
       }
       return names;       
    }
//[loadResourceNames.


//[singleton2.
    
}
//]singleton2.
