import java.io.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.oroinc.text.regex.*;

/*
REVISION HISTORY
1997-08-10 Written and published by Sten Hjelmqvist,sten@Mailhost.org
1999-05-02 Bugfix: 'String Last100' was not used. Its now fixed.
1999-05-08 Unused variables has been removed.
*/

public class UploadServlet extends HttpServlet
{
   public void service( HttpServletRequest _req, HttpServletResponse _res ) throws ServletException, IOException 
   {

      _res.setContentType("text/html");
      String FileNameRegex = ".*filename=.*\\W(\\w+\\.\\w+)";
      String FooterRegex = "(\r\n\\-+\\d+\\-+\r\n)";

      // Create Perl5Compiler and Perl5Matcher instances.

      Perl5Compiler FileNameCompiler = new Perl5Compiler();;
      Perl5Compiler FooterCompiler = new Perl5Compiler();;

      Perl5Matcher FileNameMatcher = new Perl5Matcher();;
      Perl5Matcher FooterMatcher = new Perl5Matcher();;

      Perl5Pattern FileNamePattern = null;
      Perl5Pattern FooterPattern = null;


      Perl5StreamInput input;
      MatchResult result;

      BufferedReader InFile = new BufferedReader(new InputStreamReader(_req.getInputStream()));
      ServletOutputStream HTMLout = _res.getOutputStream();
      String   FileName=null;
      String HeaderData=null;

      // Attempt to compile the pattern.  If the pattern is not valid,
      // report the error and exit.
      try
      {
         FileNamePattern = (Perl5Pattern)FileNameCompiler.compile(FileNameRegex);
      }
      catch(MalformedPatternException e) 
      {
         HTMLout.println("Bad pattern."+"&lt;br&gt;");
         HTMLout.println(e.getMessage()+"&lt;br&gt;");
         //System.exit(1);
      }

      // Attempt to compile the Filepattern.  If the Filepattern is not valid,
      // report the error and exit.
      try
      {
         FooterPattern = (Perl5Pattern)FooterCompiler.compile(FooterRegex);
      }
      catch(MalformedPatternException e)
      {
         HTMLout.println("Bad pattern."+"&lt;br&gt;");
         HTMLout.println(e.getMessage()+"&lt;br&gt;");
         //System.exit(1);
      }

      // Open and read InFile, get the HTML header. It ends whith a empty line.
      //The readLine 'eats' the \n
      try
      {
         String s="";
         StringBuffer sb = new StringBuffer();

         for(; (s = InFile.readLine()) != null; )
         {
            sb.append(s+"\n");

            if( s.length() == 0 )//Is this the End?
               break;
         }

         HeaderData = sb.toString();

         HTMLout.print("Header= (" + HeaderData + ")&lt;br&gt;");

         //System.out.println("Header= (" + HeaderData + ")");

      }
      catch(IOException e) 
      {
         HTMLout.println("Error opening streamInput."+"&lt;br&gt;");
         HTMLout.println(e.getMessage()+"&lt;br&gt;");
         //System.exit(1);
      }


      //Get fileinfo
      do
      {
         FileNameMatcher.contains(HeaderData, FileNamePattern);

         result = FileNameMatcher.getMatch(); 

      }while(result == null );

      FileName = result.group(1);



      // Print group 1.
      HTMLout.print("FileName (" + result.group(1)+ ")&lt;br&gt;");
      //System.out.println("FileName (" + result.group(1)+ ")");


      // Now get the footer.
      //It looks something like this '\n-----------------------------46541840611274--\n'
      try
      {
         int len=0;
         String s = "";
         StringBuffer sb = new StringBuffer();

         char[] b = new char[4096];
   
         while( (len = InFile.read(b,0,4096)) != -1 )
         {
            s = new String(b);

            sb.append( s.substring(0,len) );
         }
         
         int TotLen = sb.toString().length();

         //Look for the footer only in the last 100 bytes.
         String Last100 = new String( sb.toString().substring( TotLen - 100<0 ?0 :TotLen - 100 ) );

         FooterMatcher.contains(Last100, FooterPattern);

         result = FooterMatcher.getMatch(); 

         //Is this the End?
         int FooterLen = 0;
         if( result != null )//This may be the beginning of the End
            if( result.group(1).length() != 0 )//Yes my friend, this is the End 
               FooterLen = result.group(1).length();

         
         String FileData = new String( sb.toString().substring(0,TotLen-FooterLen) );

         FileOutputStream fos =  new FileOutputStream("\\OS2httpd\\servlets\\upload\\"+FileName);
         OutputStreamWriter osw = new OutputStreamWriter( fos );
         Writer OutFile = new BufferedWriter( osw );
         OutFile.write( FileData );
         OutFile.close();

         InFile.close();
      }
      catch(IOException e)
      {
            HTMLout.println("Error opening RandomAccessFile " + FileName + " for writing."+"&lt;br&gt;");
            HTMLout.println(e.getMessage()+"&lt;br&gt;");
            //System.exit(1);
      }
   }
}
