package streams;

import java.io.*;
import http.*;


/**
 * A utility class for creating streams of various kinds
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class StreamFactory
{
//[String
    /**
     * Create a "line-based" InputStream from a String that is
     * delimited using other characters
     *
     * @param s          The source String to use
     * @param delimiter  The String used to delimit the "lines" in the source
     */
    public static InputStream createInputStream(String s, String delimiter)
    {
       ByteArrayInputStream       bis;
       
       s   = s.replaceAll(delimiter, "\r\n");
       s   = s.concat("\r\n");
       bis = new ByteArrayInputStream(s.getBytes());
       
       return bis;
    }
//]String    

//[HttpInputStream
    /**
     * Create a "line-based" and EOF-terminated InputStream from the
     * remainder of an HttpInputStream
     *
     * @param is   The HttpInputStream to use
     */
    public static InputStream createInputStream(HttpInputStream is)
                              throws IOException
    {
       PipedInputStream     pin;
       PipedOutputStream    pout;
       PipedStreamFactory   factory;       
       PrintWriter          pw;
       String               line;
       

       factory = new PipedStreamFactory();          
       pin     = factory.getInputStream();
       pout    = factory.getOutputStream();
       pw      = new PrintWriter(pout);
       
       while (((line = is.readLine()) != null) && (!line.equals(""))) 
       {
          pw.println(line);
       }
       pw.flush();
       pw.close();
       
       
       return pin;        
    }
//]HttpInputStream    
    
}
