File:  [Repository] / upload-applet / RWServlet.java
Revision 1.1.1.1 (vendor branch): download - view: text, annotated - select for diffs - revision graph
Tue Jun 17 14:59:39 2003 UTC (20 years, 10 months ago) by rogo
Branches: bli, MAIN
CVS tags: bla, HEAD
First checkin.


import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

import sun.security.x509.*;
import java.security.*;
/**
 * Read/Write Servlet
 *
 *
 * @version     0.85 , 30/04/2003
 * @author      Robert Gordesch
 */
public class RWServlet extends HttpServlet
{

  String md5 = "";
  static String basePath=null;

  public void init(ServletConfig config) throws ServletException
  {
    basePath=config.getInitParameter("basePath");
    System.out.println("path"+basePath);
  }
  public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  {
    Enumeration header = req.getHeaderNames();
    while(header.hasMoreElements())
    System.out.println(header.nextElement());
   System.out.println(req.getCookies()[0].getValue());
   /*
    //value chosen to limit denial of service
    if (req.getContentLength() > 8 * 1024)
    {
      res.setContentType("text/html");
      ServletOutputStream out = res.getOutputStream();
      out.println("<html><head><title>Too big</title></head>");
      out.println("<body><h1>Error - content length &gt;8k not ");
      out.println("</h1></body></html>");
    } else
    {
      doGet(req, res);
    }*/
  }

  public void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  {
    ServletOutputStream out = res.getOutputStream();
    ServletInputStream in = req.getInputStream();
    String mimeType = "text/plain";

     /*  if(req.getContentLength()==-1)
        {
    res.setContentType(mimeType);
        res.sendError(res.SC_BAD_REQUEST,"You must specifiy Content-Length!");
        out.close();in.close();}*/
    //else { res.setContentType(mimeType);
    //     res.setStatus(res.SC_CREATED);
    // }
    String query = req.getQueryString();
    String id = "", count = "", numFiles = "", cMD5 = "";
    String mode = "";
    try
    {
      if (query != null)
      {
        //    System.out.println(query);
        //      System.out.println("Query parameter got" + req.getParameter("id") + " count" + req.getParameter("count") + " nf" + req.getParameter("nf") + " md5 " + req.getParameter("md5"));
        id = req.getParameter("id");
        count = req.getParameter("count");
        numFiles = req.getParameter("nf");
        cMD5 = req.getParameter("md5");
        mode = req.getParameter("mode");
      }
      String fileToPut = (basePath!=null) ? basePath+"/"+req.getPathInfo():req.getPathTranslated();
      System.out.println("fileToWrite " + fileToPut);
     /*
     if (exists(fileToPut, id) && !mode.equals("update") && !mode.equals("replace"))
      {
        res.setContentType(mimeType);
        res.setStatus(res.SC_CONFLICT,"Conflict");
        //res.sendError(HttpServletResponse.SC_CONFLICT, "Conflict");
        // in.close();
        //out.close();
        System.out.println("why here ? " );
        return;
      }
      */

      // creates the Directorystructure
      new File(fileToPut.substring(0, fileToPut.lastIndexOf(File.separator))).mkdirs();
      //        System.out.println("length"+req.getContentLength());
      FileOutputStream outFile = new FileOutputStream(fileToPut);
      cMD5 = receiveFile(outFile, in, out, req.getContentLength());
      if (md5.equals(cMD5))
      {
        res.setHeader("MD5", md5);
        res.setContentType(mimeType);
        res.setStatus(res.SC_CREATED);
        // all files uploaded?
        if (Integer.parseInt(count) == Integer.parseInt(numFiles))// && md5.equals(cMD5))
        {
          int index = fileToPut.lastIndexOf(File.separator) + 1;
          String source = fileToPut.substring(0, index);
          String fileName = fileToPut.substring(index);
          index = source.indexOf(id);
          int index2 = index + id.length() + 1;
          int index3 = source.indexOf(File.separator, index2);
          String dest = (index3 > 0) ? source.substring(0, index) + source.substring(index2, index3) : source.substring(0, index) + fileName;
          if (index3 < 0)
            source += fileName;
          else
            source = source.substring(0, index3);
          // System.out.println(source);

          //          System.out.println(dest);
          File f = new File(source);
          if (mode.equals("replace"))
          {
            File origFile = new File(dest);
            GregorianCalendar calendar = new GregorianCalendar();
            File saveFile = new File(dest + "_" + calendar.get(calendar.DAY_OF_MONTH) + "." + (calendar.get(calendar.MONTH) + 1) + "." + calendar.get(calendar.YEAR) + "_" + calendar.get(calendar.HOUR_OF_DAY) + "." + calendar.get(calendar.MINUTE) + "." + calendar.get(calendar.SECOND));
            origFile.renameTo(saveFile);
            //  System.out.println(saveFile+" replace");
            //  System.out.println(origFile);

          }
          f.renameTo(new File(dest));

          new File(source.substring(0, index2)).delete();
        }
        in.close();
        out.close();
      } else
      {
        System.out.println("Got an error "+cMD5+" "+md5);
        res.setContentType(mimeType);
        res.setStatus(res.SC_NOT_ACCEPTABLE, " Checksums not identical!");
        res.setHeader("MD5", md5);

          //res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, " Checksums not identical!");
        // out.println("\r\n");
      //  new File(fileToPut).delete();
        in.close();
        out.close();
      }

      //   outFile.close();
      // out.close();
    } catch (FileNotFoundException fnf)
    {

      res.sendError(HttpServletResponse.SC_NOT_FOUND, " Not Found!");
      fnf.printStackTrace();
    } catch (IOException ioe)
    {
      System.out.println("IOException: Unknown file length: " + ioe);
      res.sendError(HttpServletResponse.SC_BAD_REQUEST, "File length!");
    } catch (Exception e5)
    {
      System.out.println(e5);
      e5.printStackTrace();
    }
    // } // to else

  }
  public void doHead(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  {
     System.out.println("Called head");
      ServletOutputStream out = res.getOutputStream();
    ServletInputStream in = req.getInputStream();
    String mimeType = "text/plain";

     /*  if(req.getContentLength()==-1)
        {
    res.setContentType(mimeType);
        res.sendError(res.SC_BAD_REQUEST,"You must specifiy Content-Length!");
        out.close();in.close();}*/
    //else { res.setContentType(mimeType);
    //     res.setStatus(res.SC_CREATED);
    // }
    String query = req.getQueryString();
    String id = "", count = "", numFiles = "", cMD5 = "";
    String mode = "";
    try
    {
      if (query != null)
      {
        //    System.out.println(query);
        //      System.out.println("Query parameter got" + req.getParameter("id") + " count" + req.getParameter("count") + " nf" + req.getParameter("nf") + " md5 " + req.getParameter("md5"));
        System.out.println("header ist "+req.getHeader("Connection"));
        id = req.getParameter("id");
        count = req.getParameter("count");
        numFiles = req.getParameter("nf");
        cMD5 = req.getParameter("md5");
        mode = req.getParameter("mode");
      }
      String fileToPut = (basePath!=null) ? basePath+"/"+req.getPathInfo():req.getPathTranslated();
      System.out.println("fileToWrite " + fileToPut);
      if (new File(fileToPut).exists())// && !mode.equals("update") && !mode.equals("replace"))
      {
        res.setHeader("Connection", "keep-alive");
        res.setContentType(mimeType);
        res.setStatus(res.SC_OK);
        //res.sendError(HttpServletResponse.SC_CONFLICT, "Conflict");
        // in.close();
        //out.close();
        return;
      } else
        {
        res.setHeader("Connection", "keep-alive");
        res.setContentType(mimeType);
        res.setStatus(res.SC_ACCEPTED);
        }
       } catch(Exception e) { System.out.println(e);}
  }
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  {
    ServletOutputStream out = res.getOutputStream();
    ServletInputStream in = req.getInputStream();
    // start
    String mimeType = "text/html";
    String fileToGet = req.getPathTranslated(); //req.getPathInfo();
    String query = req.getQueryString();
    System.out.println(req.getQueryString());
    try
    {
      if (query != null)
      {
        System.out.println("Query parameter got" + req.getParameter("baseURL") + " " + req.getContextPath() + req.getServletPath());
        String baseURL = req.getParameter("baseURL");
        res.setContentType(mimeType);
        /*       Cookie cookie = new Cookie("Rogo", "idiot");
               cookie.setPath("http://localhost:8080");

               res.addCookie(cookie);
        */

        out.println("<APPLET");

        // out.println("CODEBASE = \".\"");
        out.println("CODE     = \"ServerWriter.class\"");
        out.println("ARCHIVE=\"upload.jar\"");
        out.println("NAME     = \"Upload Applet\"");
        out.println("  WIDTH    = 160");

        out.println("  HEIGHT   = 25");

        out.println("  HSPACE   = 0 ");

        out.println("  VSPACE   = 0 ");

        out.println("  ALIGN    = middle>");
        out.println("  <PARAM NAME=\"baseURL\" VALUE=" + baseURL + ">");
        out.println("  <PARAM NAME=\"servletURL\" VALUE=\"" + req.getContextPath() + req.getServletPath() + "\">");

        StringTokenizer querys = new StringTokenizer(query, "+");
        out.println("</APPLET>");
      }

      if (query == null)
      {
        File f = new File(fileToGet);
        if (f.isDirectory())
        {
          int i = 0;
          ByteArrayOutputStream tempfile = new ByteArrayOutputStream(1024);
          try
          {

            while (i <= f.list().length - 1)
            {
              tempfile.write(f.list()[i].getBytes());
              tempfile.write('\n');
              ++i;
            } // to while

          } catch (IOException ioe)
          {
            System.out.println(ioe);
          }
          res.setHeader("Content-Length", new Integer(tempfile.size()).toString());
          res.setContentType(mimeType);
          tempfile.writeTo(out);
        } else
        {
          FileInputStream inFile = new FileInputStream(fileToGet);
          if (fileToGet.endsWith(".html") || fileToGet.endsWith(".htm"))
            mimeType = "text/html";
          res.setHeader("Content-Length", new Integer(inFile.available()).toString());
          res.setContentType(mimeType);
          sendFile(inFile, out, in);
          inFile.close();
        }
      } // to sec if
    } catch (FileNotFoundException fnf)
    {
      res.sendError(HttpServletResponse.SC_NOT_FOUND, " Not Found!");

    } catch (IOException ioe)
    {
      System.out.println("IOException: Unknown file length: " + ioe);
      res.sendError(HttpServletResponse.SC_BAD_REQUEST, " Bad Request");
    }

    // end

  }

  public String getServletInfo()
  {
    return "A Servlet that reads data from and writes data to the server\n" + "If the requested data is a directory it sends the list of files in the directory back";
  }
  public void sendFile(FileInputStream inFile, ServletOutputStream outbound, ServletInputStream inbound)
  {

    try
    {

      byte dataBody[] = new byte[1024];
      int cnt;
      while ((cnt = inFile.read(dataBody)) != -1)
      {
        outbound.write(dataBody, 0, cnt);
      }
    } catch (IOException ioe)
    {
      System.out.println("IOException while sending file: " + ioe);
    }
    try
    {
      // Cleanup
      outbound.close();
      inbound.close();
    } catch (IOException ioe)
    {
      System.out.println("IOException closing streams in sendFile: " + ioe);
    }
  }
  public String receiveFile(FileOutputStream outFile, ServletInputStream inbound, ServletOutputStream outbound, int length)
  {
    StringBuffer buf=new StringBuffer();
    try
    {
      length-=32;
      System.out.println("File size " +length+" available "+inbound.available());
      byte[] b = new byte[512];
      int  readCount = 0;
      int available  = 0;
      int bufSize    = b.length;
      int readSize    = b.length;

      MessageDigest md = MessageDigest.getInstance("MD5");

       while (readCount < length)
      {
        available=inbound.available();

        if(available>=bufSize)
        readSize=bufSize;
        else
        readSize=available;

      if(readCount + readSize > length)
      {
        inbound.read(b, 0, length - readCount); //  mout.flush();
	    md.update(b, 0, length-readCount);
         outFile.write(b,0, length - readCount);

	  }
      else
      {
        inbound.read(b,0,readSize);
        md.update(b, 0, readSize);
         outFile.write(b,0,readSize);

      }

      readCount += readSize;
        //System.out.println("rock " + readCount);

      }
      int c=0;
      System.out.println("rock ");

      while((c=inbound.read())!=-1)
      {
        System.out.print((char)c);
         buf.append((char)c);
      }
        md5 = getMD5(md);
      System.out.println(md5);

      // System.out.println(cnt);
      // one byte version
      /* int cnt = 0;
       // System.out.println(cnt);
        while (cnt < size)
        {
          outFile.write(inbound.read());
          ++cnt;
        }*/

    } catch (IOException ioe)
    {
      System.out.println("IOException while receiving file: " + ioe);
    }
       catch (Exception e6)
      {
        System.out.println("error while getting MD5 "+e6);
      }

    try
    {
      // Cleanup
      outFile.flush();
      outFile.close();
      //      outbound.close();
      //    inbound.close();

    } catch (IOException ioe)
    {
      System.out.println("IOException closing streams in receiveFile: " + ioe);
    }
    return buf.toString();
  }
  public static String getMD5(MessageDigest md) throws Exception
  {
    System.out.println("digest");
    byte[] bytes = md.digest();
    StringBuffer sb = new StringBuffer();
    int decValue;
    for (int i = 0; i < bytes.length; i++)
    {
      String hexVal = Integer.toHexString(bytes[i] & 0xFF);
      if (hexVal.length() == 1)
        hexVal = "0" + hexVal; // put a leading zero
      sb.append(hexVal);
    }
    return sb.toString();
  }
  public static String getSHA(byte[] b) throws Exception
  {
    MessageDigest md = MessageDigest.getInstance("sha1");
    md.update(b, 0, b.length);
    //System.out.println("digest");
    byte[] bytes = md.digest();
    StringBuffer sb = new StringBuffer();
    int decValue;
    for (int i = 0; i < bytes.length; i++)
    {
      String hexVal = Integer.toHexString(bytes[i] & 0xFF);
      if (hexVal.length() == 1)
        hexVal = "0" + hexVal; // put a leading zero
      sb.append(hexVal);
    }

    return sb.toString();
  }
  public boolean exists(String fileToPut, String id)
  {
    int index = fileToPut.lastIndexOf(File.separator) + 1;
    String source = fileToPut.substring(0, index);
    String fileName = fileToPut.substring(index);
    index = source.indexOf(id);
    int index2 = index + id.length() + 1;
    int index3 = source.indexOf(File.separator, index2);
    String dest = (index3 > 0) ? source.substring(0, index) + source.substring(index2, index3) : source.substring(0, index) + fileName;
    if (index3 < 0)
      source += fileName;
    else
      source = source.substring(0, index3);
    //System.out.println(source);

    //    System.out.println(dest);
    File f = new File(dest);
    return f.exists();
  }
}

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>