package com.infopulse.efs.webdavconnection;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.ServletConfig;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.util.Enumeration;
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
import org.apache.commons.httpclient.*;
import org.apache.webdav.lib.*;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.util.*;

import com.infopulse.efs.EFSFile;
import java.io.FileInputStream;

public class Test2 {

  public Test2() {
  }
  public static void main(String[] args) {

    try{

      String path = args[0];
      String name = args[1];
      String newname = args[2];

      HttpURL http_url = new HttpURL("http://maik:9000/webdav");

      http_url.setUserInfo("mylogin", "mypasswd"); 

      WebdavResource webdav_resource = new WebdavResource(http_url);
      webdav_resource.setPath("/webdav/"+newname);  // /webdav it's the dav root dir
      
      HttpClient client = webdav_resource.getSessionInstance(webdav_resource.getHttpURL());
      PutMethod method = new PutMethod(webdav_resource.getPath());
      
      
      // it may seem stupid this block - you maybe wondering why is this guy making a reader of a file, 
      // saving it to a temp_file and then sending the temp_file, instead of sending the original file?
      // well as i said, this are only test classes, in my project i really do need to receive a InputStream 
      // and send it. So, due to inputStream limitations i use the temp file proccess.
      
      File temp_file =  new File("D:\\Temp", newname);
      BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(path+"/"+name)));

      PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(temp_file)));
      
      while (in.ready())
      
        out.write(in.read());
        
      in.close();
      out.flush();
      out.close();
      
      method.sendData(temp_file);
      client.setDebug(1);
      client.executeMethod(method);
      temp_file.delete();
      
    }
    catch(Exception ex){ex.printStackTrace();}

  }
}