File:  [Repository] / upload-applet / ServerWriter.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.


/**
 * @author rogo
 *
 * To change this generated comment edit the template variable "typecomment":
 * Window>Preferences>Java>Templates.
 * To enable and disable the creation of type comments go to
 * Window>Preferences>Java>Code Generation.
 */
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.security.*;
import java.util.*;

public class ServerWriter extends JApplet implements ActionListener
{
  static File startFile;
  static int count = 0;
  static JFileChooser fileChooser;
  static String url;
  static long id = 0L;
  static Hashtable connections=new Hashtable();
  JButton upload = new JButton("Upload");
  JRadioButton proxy = new JRadioButton("Proxy");
  static int fileCount = 0;
  // static UploadInfo dialog = new UploadInfo();
  static String mode = "";
  static String destination = "";
  static String prefix = "";
  static String proxyHost = "";
  ServerWriter uploader = this;
  static final int md5Length = 32;
  public ServerWriter()
  {

  }
  public void init()
  {
    this.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
    this.getContentPane().add(upload);
    this.getContentPane().add(proxy);
    upload.addActionListener(this);
    proxy.addActionListener(this);
    id = System.currentTimeMillis();
       Properties prop = System.getProperties();

    // prop.put("proxySet", "true"); 
    // prop.put("http.proxyHost","proxy.unibe.ch");
    // prop.put("proxyPort", "80"); 
      prop.put("java.protocol.handler.pkgs","HTTPClient");
     fileChooser=null;
  }
  public void actionPerformed(ActionEvent e)
  {
    if (e.getSource().equals(proxy))
    {
      proxyHost = JOptionPane.showInputDialog("Please enter proxy host (format host:port)!");
      if (proxyHost != null)
      {
        if (proxyHost.length() == 0)
          {
          proxyHost = "";
          Properties prop = System.getProperties();
          prop.remove("proxySet"); 
          prop.remove("http.proxyHost");
          prop.remove("proxyPort");   
        
          }
         else
         {
           Properties prop = System.getProperties();
        int index = proxyHost.indexOf(":");
        String pHost = proxyHost.substring(0, (index > 0) ? index : proxyHost.length());
        String pPort = (index > 0) ? proxyHost.substring(index + 1) : "80";

       prop.put("proxySet", "true"); 
       prop.put("http.proxyHost",pHost);
       prop.put("proxyPort", pPort);   
         }
        System.out.println("pr "); // proxyHost="";
      } else
        proxyHost = "";
      // proxy.setSelected(false);
    }

    if (e.getActionCommand().equals("Upload"))
    {

      //url=getParameter("url");
      set();
      System.out.println("url " + url); //+ " " + getCodeBase());
      upload.setEnabled(false);
      main(new String[] { "", "" });
      upload.setEnabled(true);
    }

  }
  public void set()
  {
    String url = getParameter("baseURL");
    String servletURL = getParameter("servletURL");
    destination = "";
    destination = getParameter("destinationFolder");
    if (destination == null)
      destination = "";
    prefix = getParameter("prefix");
     if(prefix == null) prefix="";
    // e.g."/rogo/servlet/RWServlet/"
    URL appletUrl = getCodeBase();
    String serverInfo = appletUrl.getHost() + ":" + appletUrl.getPort();
    this.url = (servletURL.startsWith("http")) ? servletURL + url : "http://" + serverInfo + servletURL + url;
    Properties prop = System.getProperties();

    // prop.put("proxySet", "true"); 
    // prop.put("http.proxyHost","proxy.unibe.ch");
    // prop.put("proxyPort", "80"); 
   //   prop.put("java.protocol.handler.pkgs","HTTPClient");
    Enumeration en = prop.propertyNames();
    while (en.hasMoreElements())
    {
      String key = (String) en.nextElement();
      System.out.println("key: " + key + " value: " + prop.get(key));

    }
  }
  public static void main(String[] args)
  {
    try
    {
      if (fileChooser == null)
      {
        fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(fileChooser.FILES_AND_DIRECTORIES);
        fileChooser.setFileFilter(new ImageFilter());
        fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
        fileChooser.addActionListener(new ActionListener()
        {
          public void actionPerformed(ActionEvent e2)
          {
            System.out.println(e2.getActionCommand());
            if (!e2.getActionCommand().toString().equals("ApproveSelection")) return;
            // {

            Thread thread = new Thread()
            {
              public void run()
              {
                UploadInfo dialog = new UploadInfo();
               
                File startFile=new File(".");
                try
                {
                  dialog.thread=Thread.currentThread();
                  System.out.println("Called run with " + fileChooser.getSelectedFile());
                  dialog.setTitle("Upload Status Window");
                  dialog.setSize(400, 175);
                  dialog.setLocation(new java.awt.Point(150, 100));
                  Update update = new Update();
                  startFile = fileChooser.getSelectedFile(); //new File(fileChooser.getFile());
                  int fileCount = 0;
                  int count = 1;
                  System.out.println(startFile);
                  long time = System.currentTimeMillis();
                   if( connections.get(startFile.getAbsolutePath())!=null) 
                   throw new Error("Upload already running!");
  
                  if (startFile.isDirectory())
                  {
                    fileCount = countFiles(startFile, fileCount);
                    System.out.println("Number of files to send: " + fileCount);
                    writeDirectory(startFile, startFile, fileCount, count, dialog, update);

                  } else
                  {
                    fileCount = 1;
                    writeStream(startFile, startFile, fileCount, count, dialog, update);

                  }

                  long time2 = System.currentTimeMillis();
                  System.out.println("needed " + (time2 - time) + " ms for " + count--);
                  dialog.setVisible(false);
                  if (startFile.isDirectory())
                    showDialog("Finished upload of " + startFile + " containing " + fileCount + " " + ((fileCount > 1) ? " files" : " file") + " in " + ((time2 - time) / 1000) + " seconds", "Finished Upload");
                  else
                    showDialog("Finished upload of " + startFile + " in " + ((time2 - time) / 1000) + " seconds", "Finished Upload");
                 connections.remove(startFile.getAbsolutePath());
                } catch (Exception e)
                {
                  dialog.setVisible(false);
                  ByteArrayOutputStream b = new ByteArrayOutputStream();
                  PrintStream stream = new PrintStream(b);
                  e.printStackTrace(stream);
                  connections.remove(startFile.getAbsolutePath());
                 
                  showErrorDialog(b.toString(), "Upload failed");
                } catch (Error e8)
                {
                   dialog.setVisible(false);
                   if( e8.toString().indexOf("Upload already running!")<0)
                   connections.remove(startFile.getAbsolutePath());
                   showErrorDialog(e8.toString(), "Upload failed");
                }

              }
            };
            thread.setPriority(Thread.MIN_PRIORITY);
            /* dialog = new UploadInfo();
             dialog.setTitle("Upload Status Window");
             dialog.setSize(400, 155);
             dialog.setLocation(new java.awt.Point(150, 100));
             */
            thread.start();
            //          } // else
            //System.exit(0);
          }
        });

      }
      count = 1;
      mode = "";
      fileChooser.showDialog(new JFrame(), "Upload");

    } catch (Exception e)
    {
      System.out.println("Ha " + e);
    }
  }
  private static int countFiles(File file, int fileCount)
  {
    if (file.isDirectory())
    {
      String[] files = file.list(new DotFileFilter());

      for (int j = 0; j < files.length; ++j)
      {
        File f = new File(file + File.separator + files[j]);
        if (f.isDirectory())
        {
          fileCount = countFiles(f, fileCount);
        } else
          fileCount = fileCount + 1;
      }

    }
    return fileCount;
  }

  private static int writeDirectory(File file, File startFile, int fileCount, int count, UploadInfo dialog, Update update) throws Exception
  {
    if (file.isDirectory())
    {
      String[] files = file.list(new DotFileFilter());
      for (int j = 0; j < files.length; ++j)
      {
        File f = new File(file + File.separator + files[j]);
        System.out.println(file + " " + f);

        if (f.isDirectory())
        {
          count = writeDirectory(f, startFile, fileCount, count, dialog, update);
        } else
          count = writeStream(f, startFile, fileCount, count, dialog, update);
      }
    }
    return count;
  }
  private static int writeStream(File file, File startFile, int fileCount, int count, UploadInfo dialog, Update updateMode) throws Exception
  {
    // try
    //{
    String response = "", mode = "";
    String path = file.getAbsolutePath();
    String fName=file.getName();
    String name = (startFile.isDirectory()) ? startFile.getName() + "/" + path.substring(startFile.getAbsolutePath().length() + 1) : file.getName();
    if (destination != "")
      name = (startFile.isDirectory()) ? destination + "/" + path.substring(startFile.getAbsolutePath().length() + 1) : destination + "/" + file.getName();
if(prefix!="")
name=name.substring(0,name.indexOf(fName))+prefix+fName;
    System.out.println("hi " + name + " " + destination + " " + startFile.getName()+" "+file.getName());
    FileInputStream f = new FileInputStream(file.getAbsolutePath());
    int length = f.available();
    int readCount = 0;
    byte[] b = (length > 8192) ? new byte[8192] : new byte[length];
    System.out.println(file.getName() + " " + ((length > 1000000) ? (length / 1048576) + " MByte" : length + " Bytes"));
    String fileName = file.getName() + " " + ((length > 1000000) ? (length / 1048576) + " MByte" : length + " Bytes");
    dialog.title.setText("Uploading " + startFile);
    dialog.progress.setValue(0);
    dialog.file.setText(fileName);
    dialog.status.setText(count + " of " + fileCount + ((fileCount > 1) ? " files" : " file"));
    //dialog.pack();
    //dialog.validate();
    if (dialog.isVisible())
      dialog.repaint();
    else
      dialog.show();

    MessageDigest md = MessageDigest.getInstance("MD5");
    FileInputStream f2 = new FileInputStream(file.getAbsolutePath());

    readCount = 0;
   
  /*  while (readCount < length)
    {
      if (readCount + b.length > length)
        f2.read(b, 0, length - readCount); //  mout.flush();
      else
        f2.read(b);
      if (readCount + b.length > length)
        md.update(b, 0, length - readCount);
      else
        md.update(b, 0, b.length);
      readCount += b.length;
      //System.out.println("rock " + readCount);

    }*/
    String md5 = "rogo";getMD5(md);
    //md = null;
    f2.close();
    f2 = null;
    if (updateMode.value)
      mode = "replace";

    URL httpCon = new URL(url + getSHA((id + "").getBytes()) + "/" + convertUml(name) + "?id=" + getSHA((id + "").getBytes()) + "&count=" + count + "&nf=" + fileCount + "&md5=" + md5 + "&mode=" + mode);
    /*  HttpURLConnection con = (HttpURLConnection) httpCon.openConnection(); 
      con.setUseCaches(false);
      con.setRequestMethod("PUT");
      con.setDoOutput(true);
      con.connect();
      */
    Connection con = null;
    con=(Connection)connections.get(startFile.getAbsolutePath());
    if(con==null)
    {
      con=new Connection(httpCon);
      connections.put(startFile.getAbsolutePath(),con);
    } else
    con.url=httpCon;
    OutputStream mout = con.out; //con.getOutputStream();
    // InputStream  min= con.getInputStream();
    //    System.out.println(httpCon);
    //System.out.println("Response " + con.getResponseMessage()+" "+con.getContentLength());
    boolean update =  con.update();
    
    System.out.println("update is" + update);
    
    if (!update || mode.equals("update") || mode.equals("replace"))
      //if(true)
    {
      con.connect(length+md5Length);
      mout = con.out;
      md.reset();
      /*  System.out.println("Free memory "+(Runtime.getRuntime().freeMemory()/ 1048576));
        System.gc(); 
        System.out.println("Free memory after"+(Runtime.getRuntime().freeMemory()/ 1048576));
        System.out.println("Total memory after"+(Runtime.getRuntime().totalMemory()/ 1048576));
       */
      readCount = 0;
      while (readCount < length)
      {
        if (readCount + b.length > length)
          f.read(b, 0, length - readCount); //  mout.flush();
        else
          f.read(b);
        if (readCount + b.length > length)
          mout.write(b, 0, length - readCount); //  mout.flush();
        else
          mout.write(b);
       if (readCount + b.length > length)
          md.update(b, 0, length - readCount);
       else
        md.update(b, 0, b.length);
         readCount += b.length;
        if(((PrintStream)mout).checkError()) throw new Error("Error while sending data");
        dialog.progress.setValue((int) (((double) readCount / (double) length) * 100.0));

        if (readCount % 1000 == 0)
        {
          //System.out.println("Free memory while writing"+(Runtime.getRuntime().freeMemory()/ 1048576));
          //System.out.println("Total memory while writing"+(Runtime.getRuntime().totalMemory()/ 1048576));
          //mout.flush();
          //System.out.println(con.getClass());
        }
      }
      md5 = getMD5(md);
      mout.write(md5.getBytes());
       if(((PrintStream)mout).checkError()) throw new Error("Error while sending md5");
      //mout.close();
      //con.disconnect();
       
      response = con.getResponseMessage();
      System.out.println(response + " " + md5);
    }
    if (update && !mode.equals("update") && !mode.equals("replace"))
      //(response.indexOf("Conflict")>=0 && !mode.equals("update") && !mode.equals("replace"))
    {
      updateMode.value = true;
      Object[] options = new Object[] { "Replace folder", "Cancel" }, options2 = new Object[] { "Replace file", "Cancel" };

      int option = showDialog("Warning destination exists! \n What do you want to do?", "Destination exists!", (startFile.isDirectory()) ? options : options2);
      if (option == 0)
        mode = "replace";
      //System.out.println("performing update");
      else
        throw new Error("Upload cancelled");
      //mode = "cancel"; //System.out.println("performing replace");
      //System.out.println("Watershine" + name + " " + mode);
      // mout.close();
   
      con.disconnect();
      httpCon = new URL(url + getSHA((id + "").getBytes()) + "/" + convertUml(name) + "?id=" + getSHA((id + "").getBytes()) + "&count=" + count + "&nf=" + fileCount + "&md5=" + md5 + "&mode=" + mode);
      /*    con = (HttpURLConnection) httpCon.openConnection(); 
          con.setRequestMethod("PUT");
          con.setDoOutput(true);
          con.connect();
          mout = con.getOutputStream();
          */
      //con=new Connection(httpCon);
      con.url = httpCon;
      con.connect(length+md5Length);
      md.reset();
      mout = con.out;
      readCount = 0;
      FileInputStream f3 = new FileInputStream(file.getAbsolutePath());
      while (readCount < length)
      {
        if (readCount + b.length > length)
          f3.read(b, 0, length - readCount); //  mout.flush();
        else
          f3.read(b);
        if (readCount + b.length > length)
          mout.write(b, 0, length - readCount); //  mout.flush();
        else
          mout.write(b);
        if (readCount + b.length > length)
        md.update(b, 0, length - readCount);
        else
        md.update(b, 0, b.length);
        readCount += b.length;
       
        if(((PrintStream)mout).checkError()) throw new Error("Error while sending data");
        
        dialog.progress.setValue((int) (((double) readCount / (double) length) * 100.0));

      }
      f3.close();
     // mout.flush();
      md5=getMD5(md);
      mout.write(md5.getBytes()); // write md5 code
      if(((PrintStream)mout).checkError()) throw new Error("Error while sending md5");

      response = con.getResponseMessage();
      System.out.println("MyResponse " + response);

    } else if (response.indexOf(" Checksums not identical!") >= 0)
    {
      Object[] options = { "Retry", "Cancel" };

      int option = showDialog("Transfer failed! \n What do you want to do?", "Transfer failed ", options);
      con.disconnect();
      if (option == 0)
      {
        httpCon = new URL(url + getSHA((id + "").getBytes()) + "/" + convertUml(name) + "?id=" + getSHA((id + "").getBytes()) + "&count=" + count + "&nf=" + fileCount + "&md5=" + md5 + "&mode=" + mode);
        /*  con = (HttpURLConnection) httpCon.openConnection(); // con.setRequestMethod("GET");
          con.setRequestMethod("PUT");
          con.setDoOutput(true);
          con.connect();
          mout = con.getOutputStream();
          //     System.out.println(htt  readCount = 0;
        */

        con.url = httpCon;
        con.connect(length+md5Length);
        mout = con.out;
        FileInputStream f4 = new FileInputStream(file.getAbsolutePath());
        readCount = 0;
        while (readCount < length)
        {
          if (readCount + b.length > length)
            f4.read(b, 0, length - readCount); //  mout.flush();
          else
            f4.read(b);
          if (readCount + b.length > length)
            mout.write(b, 0, length - readCount); //  mout.flush();
          else
            mout.write(b);
          readCount += b.length;
          if(((PrintStream)mout).checkError()) throw new Error("Error while sending data");
          dialog.progress.setValue((int) (((double) readCount / (double) length) * 100.0));
           
        }
        f4.close();
        mout.write(md5.getBytes());
        if(((PrintStream)mout).checkError()) throw new Error("Error while sending md5");
        response = con.getResponseMessage();
        System.out.println("MyResponse " + response);
      }

    } else
      con.disconnect();

    f.close();
    count++;
    /*
       } catch (IOException ioe)
       {
         System.out.println("IOException: " + ioe);
         ioe.printStackTrace();
        throw(ioe);
            } catch (Exception e)
       {
         System.out.println("IOException: " + e);
         showErrorDialog(e.toString(),"Upload failed");
       }*/
    return count;
  }
  public static String getMD5(MessageDigest md) throws Exception
  {
    byte[] bytes = md.digest();
    System.out.println("digest " + bytes.length);
    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("SHA");
    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 static String convertUml(String newName)
  {
    StringBuffer alterMe = new StringBuffer(newName.trim());
    int length = alterMe.length();
    int j = 0;
    while (j < length)
    { //if(Character.isSpaceChar(alterMe.charAt(j)))
      //  alterMe.setCharAt(j,'_');
      if (alterMe.charAt(j) == ' ')
      {
        alterMe.setCharAt(j, '%');
        alterMe.insert(j + 1, "20");
        length = length + 2;
      }
      /* if(Character.isSpaceChar(alterMe.charAt(j))
       alterMe.setCharAt(j,'_');
      */
      ++j;
    }
    return alterMe.toString();
  }
  public static class UploadInfo extends JDialog
  {
    JLabel file = new JLabel("    ");
    JLabel status = new JLabel("    ");
    JLabel title = new JLabel("     ");
    JPanel content = new JPanel();
    JPanel titlePanel = new JPanel();
    JPanel labelPanel = new JPanel();
    JPanel statusPanel = new JPanel();
    JPanel buttonPanel = new JPanel();

    JProgressBar progress = new JProgressBar();
    JButton cancel = new JButton("Cancel");
    Thread thread;
    public UploadInfo()
    {

      content = new JPanel(true);
      //content.setBorder(BorderFactory.createRaisedBevelBorder());
      content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
      title = new JLabel("Uploading " + startFile);
      title.setHorizontalTextPosition(title.CENTER);
      titlePanel.add(title);
      buttonPanel.add(cancel);
      // content.add(titlePanel);
      content.add(Box.createRigidArea(new java.awt.Dimension(0, 15)));
      content.add(labelPanel);
      content.add(new JLabel(""));
      content.add(progress);
      content.add(statusPanel);
      content.add(buttonPanel);
      content.add(Box.createRigidArea(new java.awt.Dimension(0, 15)));
      labelPanel.add(file);
      statusPanel.add(status);
      getContentPane().add(titlePanel, "North");
      getContentPane().add(content, "Center");
      cancel.addActionListener(new ActionListener()
      {
        public void actionPerformed(ActionEvent e)
        {
          setVisible(false);
          thread.stop();
        }

      });
      pack();

    }

  }
  public static int showDialog(String message, String title, Object[] options)
  {
    int option = JOptionPane.showOptionDialog(null, message, title, JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
    return option;

  }
  public static void showDialog(String message, String title)
  {
    JOptionPane.showMessageDialog(null, message, title, JOptionPane.PLAIN_MESSAGE);

  }
  public static void showErrorDialog(String message, String title)
  {
    JOptionPane.showMessageDialog(null, message, title, JOptionPane.ERROR_MESSAGE);
  }

  static class Connection
  {
    Socket socket;
    URL url;
    BufferedInputStream in;
    PrintStream out;
    String pHost;
    int pPort = 80;
    HttpURLConnection con;
    public Connection(URL url) throws Exception
    {
      Properties prop = System.getProperties();
      pHost = null;
      pPort = 80;
      Enumeration en = prop.propertyNames();
      while (en.hasMoreElements())
      {
        String key = (String) en.nextElement();
        if (key.toString().indexOf("proxyHost") >= 0)
        {
          Object host = prop.get(key);
          if (host != null)
            pHost = host.toString();
        }
        if (key.toString().indexOf("proxyPort") >= 0)
        {
          Object port = prop.get(key);
          if (port != null)
            pPort = Integer.parseInt(port.toString());
        }
      }

      if (proxyHost != "")
      {
        int index = proxyHost.indexOf(":");
        pHost = proxyHost.substring(0, (index > 0) ? index : proxyHost.length());
        pPort = (index > 0) ? Integer.parseInt(proxyHost.substring(index + 1)) : 80;
      }
  socket = new Socket((pHost != null) ? pHost : url.getHost(), (pHost != null) ? pPort : url.getPort());
     socket.setTcpNoDelay(true);
       in = new BufferedInputStream(socket.getInputStream());
      out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()),true);
      this.url = url;
    }
    public void connect(int size) throws Exception
    {
      try
      {
        //System.out.println("Yeah i called connect");
        //  socket = new Socket((pHost != null) ? pHost : url.getHost(), (pHost != null) ? pPort : url.getPort());
         // socket.setTcpNoDelay(true);
        in = new BufferedInputStream(socket.getInputStream());
        out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()),true);
    
          out.print(("PUT " + url + " HTTP/1.1\r\nContent-Type: text/html\r\nContent-Length:" + size + "\r\nHost: " + url.getHost() + "\r\n\r\n"));//.getBytes());
        out.flush();
      } catch (Exception e)
      {
        socket = new Socket((pHost != null) ? pHost : url.getHost(), (pHost != null) ? pPort : url.getPort());
          socket.setTcpNoDelay(true);
        in = new BufferedInputStream(socket.getInputStream());
        out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()),true);
        out.print(("PUT " + url + " HTTP/1.1\r\nContent-Type:text/html\r\nContent-Length:" + size + "\r\nHost: " + url.getHost() + "\r\n\r\n"));//).getBytes());
        out.flush();
        //System.out.println("Error "+e);
      }
      
  /*    con = new HTTPClient.HttpURLConnection(url);//(HttpURLConnection) url.openConnection(); // con.setRequestMethod("GET");
      con.setUseCaches(false);
      con.setRequestMethod("PUT");
      con.setDoOutput(true);
      con.setRequestProperty("Content-Length", ""+size);
    //  con.connect();      
      System.out.println(con.getClass());
      out = new DataOutputStream(con.getOutputStream());
      */
    }
    public boolean update() throws Exception
    {
      boolean exists = false;
      String response = "";
      try
      {

        URL url = createURL(this.url.toString(), getSHA((id + "").getBytes()));
      //  con = new HTTPClient.HttpURLConnection(url);//(HttpURLConnection) url.openConnection(); // con.setRequestMethod("GET");
        //con.setUseCaches(false);
       // con.setRequestMethod("HEAD");
        //con.setDoOutput(true);
       // con.connect();

        out.print(("HEAD " + url + " HTTP/1.1\r\nConnection:Keep-Alive\r\nHost: " + url.getHost() + "\r\n\r\n"));//.getBytes());
          out.flush();
        response = getResponseMessage();
        exists = response.indexOf("OK") >= 0;
        System.out.println("Head "+response);
      
         } catch (Exception e)
      {
        socket = new Socket((pHost != null) ? pHost : url.getHost(), (pHost != null) ? pPort : url.getPort());
          socket.setTcpNoDelay(true);
        in = new BufferedInputStream(socket.getInputStream());
        out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()),true);
    //    out.writeBytes("HEAD " + url + " HTTP/1.1\r\n Connection:Keep-Alive\r\n \r\nHost: " + url.getHost() + //"\r\n\r\n");
        URL url = createURL(this.url.toString(), getSHA((id + "").getBytes()));
        out.print(("HEAD " + url + " HTTP/1.1\r\nConnection:Keep-Alive\r\nHost: " + url.getHost() + "\r\n\r\n"));//.getBytes());
        out.flush();
        response = getResponseMessage();
        System.out.println("Head " + response);
        exists = response.indexOf("OK") >= 0;
        //System.out.println("Error from Head "+e);
        // e.printStackTrace();
             return exists;
      
      }
      return exists;
    }
    public URL createURL(String fileToPut, String id) throws Exception
    {
      int index = fileToPut.lastIndexOf("/") + 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("/", index2);

      //  System.out.println(fileToPut+" "+index2+" "+index3+" "+id);
      //   String dest = (index3 > 0) ? source.substring(0, index) + source.substring(index2, index3)+"/"+fileName : //source.substring(0, index) + fileName;
      // file check versus folder Check if destination !="" folder check is performed
      String dest = (destination!="") ? source.substring(0, index) + source.substring(index2,index3):source.substring(0, index) + source.substring(index2);
      // System.out.println("dest "+source.substring(0,index)+ source.substring(index2));
      // File f = new File(dest);
      //return f.exists();
      return new URL(dest);
    }

    public String getResponseMessage()
    {
      
      int b=0;StringBuffer between=new StringBuffer();int count=0;
                  // while(!between.toString().equals("\r"))
                  // {
                   // between=new StringBuffer(40);
          try 
          {
            int loop =0;int available = 0;
            while((available=in.available())==0) 
            {
              if(loop>=600) throw new Error("Connection timed out");
              long time = System.currentTimeMillis();
              while(System.currentTimeMillis()-time<100);
              if(available==0) loop++; else loop=0;
            }
       // System.out.println("heh there are bytes "+in.available()+" available");
        int limit = in.available();
                   while(true )
                   {
                     //Thread.sleep(10);
                     b=in.read();
                     /*
                     if(b=='\r')
                     {
                       b=in.read();
                       b=in.read();
                       count=count+2;
                       // if(b=='\r') break;
                       //else
                        between.append('\n');
                    }
                    */
                    between.append((char)b);
                    //   System.out.print((char)b);
                     //System.out.println("read "+count+" bytes");
                    count++;            
                    if(count==limit) break;
                    }
     
      } catch(Exception e) { 
      e.printStackTrace();
      System.out.println("Error found");
      if(e.toString().indexOf("peer")>=0)
      return getResponseMessage();
      else throw new Error("Error while reading response");
      }
      String response = between.toString();
      if(response.indexOf("close") >= 0)
       reconnect();
      return response; 
      
      /*
      String response = "";
      try
      {
        response = con.getResponseMessage();
      // con.disconnect();
      } catch (Exception e)
      {
        showErrorDialog(e.getMessage(),"Shit happens");
      }
      */

    //  return response;
    }
    public void disconnect() throws Exception
    {
     //socket.close();
     // con.disconnect();
    }
    public void reconnect() 
    {
      try 
      {
        System.out.println("Reconnect called");
        int port= (url.getPort()>=0) ? url.getPort():80;
        socket = new Socket((pHost != null) ? pHost : url.getHost(), (pHost != null) ? pPort :port);
        socket.setTcpNoDelay(true);
        in = new BufferedInputStream(socket.getInputStream());
        out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()),true);
        
      } catch(Exception e) 
        {
          showErrorDialog(e.getMessage(),"Shit happens");
        }

    }
  }
  static class Update
  {
    boolean value = false;
    public Update()
    {
      value = false;
    }
  }
static class DotFileFilter implements FilenameFilter
{
     public DotFileFilter() {}
    public boolean accept(File dir, String name) 
    {
      if(name.startsWith(".")) return false;
      else return true;
    }
  }
  static class ImageFilter extends javax.swing.filechooser.FileFilter
  {
    public boolean accept(java.io.File file)
    {
       String name=file.getName().toLowerCase();
     if(name.endsWith(".gif")||name.endsWith(".jpg")||name.endsWith(".tif")||name.endsWith(".png")||name.endsWith(".jpeg")||file.isDirectory())
     return true ; 
     else return false;
    }
     public String getDescription()
     {
     return "Image File";
     }
 }

}

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