import java.io.*;
import java.net.*;
import java.util.*;


/**
 * A stream protocol handler for the SFP protocol
 *
 *
 * @version 1.0
 * @author  Prof. David Bernstein, James madison University
 */
public class SFPStreamHandler extends URLStreamHandler
{



     /**
      * Opens a connection to an SFP host
      *
      * @param u   The URL of the SFP host (sfp://host:port/)
      * 
      */
    protected URLConnection openConnection(URL u) throws IOException
    {
	return new SFPConnection(u);
    }



    

     /**
      * Parses an SFP URL
      *
      * @param u      The URL to fill
      * @param spec   The String representation of the URL to parse
      * @param start  The character index at which parsing should start
      * @param limit  The character index at which parsing should stop
      * 
      */
    protected void parseURL(URL u, String spec, int start, int limit)
    {
	int             port;
	String          file, host, protocol, ref;
	StringTokenizer st;


	st = new StringTokenizer(spec.substring(start,limit), "/:");

	protocol = null;
	host = null;
	file = null;
	ref = null;
	port = SFPConnection.DEFAULT_PORT;

	try 
        {
           if (start == 0) protocol = st.nextToken().toLowerCase(); // sfp
	    host = st.nextToken();
	    port = Integer.parseInt(st.nextToken());
	} 
        catch (Exception e) 
        {
	    // Use the default values
	}
	setURL(u, protocol, host, port, file, ref);
    }


     /**
      * Converts an SFP URL to a String
      *
      * @param u      The URL to convert
      * @return       A String representation of the SFP URL
      * 
      */
    protected String toExternalForm(URL u)
    {
	return "sfp://"+u.getHost()+":"+u.getPort();
    }


}
