import java.io.*;
import java.net.*;
import java.util.*;
//import javax.mail.*;

//import javax.activation.*;
//import javax.mail.internet.*;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.HttpClient;
import org.apache.util.HttpURL;
import org.apache.util.QName;
import org.apache.webdav.lib.Ace;
import org.apache.webdav.lib.Lock;
import org.apache.webdav.lib.Privilege;
import org.apache.webdav.lib.Property;
import org.apache.webdav.lib.PropertyName;
import org.apache.webdav.lib.ResponseEntity;
import org.apache.webdav.lib.WebdavResource;
import org.apache.webdav.lib.methods.DepthSupport;
import org.apache.webdav.lib.properties.AclProperty;
import org.apache.webdav.lib.properties.LockDiscoveryProperty;
import org.apache.webdav.lib.properties.PrincipalCollectionSetProperty;

import org.apache.webdav.lib.WebdavResource;
import org.apache.util.HttpURL;

 /**
  * This class is designed to put a file from the local filesystem to a WebDav Server
  * On the American Redhat Linux Server rented by ella-associates.org it is necessary 
  * to place the following paths on the java classpath
  *   /var/jakarta-slide-1.0.16/client/lib/webdav.jar:/var/jakarta-slide-1.0.16/client/lib/commons-httpclient.jar:
  *   /var/jakarta-slide-1.0.16/client/lib/webdavlib.jar:/var/www/utils/ 
  *
  *-------------------------------                 
  *<pre>
  *  Command line usage:                           
  *  java PutDavFile TheLocalFile TheWebDavLocationPath [user] [password] [server-url]  
  *    The purpose of this program is to put a file from the local file system onto a WebDav server 
  *    A WebDav Server is similar to an HTTP server but it allows the user to edit the files on the 
  *    server rather than just looking at them                      
  *  The program requires two parameters: 
  *    TheLocalFile  This is the file on the local file system which you wish to put on the WebDav Server 
  *    TheWebDavLocationPath  This is the location on the WebDav server where you want to put the file 
  *      which you are uploading. This should be a path using forward slashes (eg /some/directory/)   
  *  
  *  There are other option parameters  
  *    user       
  *    password   
  *    webdav-server-url    
  *  
  *  Examples:              
  *  ---------              
  *    java PutDavFile shopping-list.xml /documents/thingsToDo/     
  *
  *</pre>  
  *  
  *  
  *  
  *  
  * 
  * @author mjb
  * @see "http://www.ella-associates.org/utils/TestJavaMail.java"
  */
public class PutDavFile 
{


  public static void main (String[]args) throws Exception
  {

    String sLocalFileName = "";
    String sLocalFileFullName = "";
    String sRemoteLocation = "";
    String sWebdavUser = "matthew";
    String sWebdavPassword = "bish";
    String sWebdavServer = "http://ella-associates.org:8081/slide";

    if (args.length == 2)
    {
      sLocalFileName = args[0];
      sRemoteLocation = args[1];
    }
    else if (args.length == 4)
    {
      sLocalFileName = args[0];
      sRemoteLocation = args[1];
      sWebdavUser = args[2];
      sWebdavPassword = args[3];
    }
    else if (args.length == 5)
    {
      sLocalFileName = args[0];
      sRemoteLocation = args[1];
      sWebdavUser = args[2];
      sWebdavPassword = args[3];
      sWebdavServer = args[4];
    }
    else 
    {
      //-- The following attempts to display the javadoc from this file
      //--
      FileReader firTheFile = new FileReader ("/var/www/utils/PutDavFile.java");
      BufferedReader buffrTextFile = new BufferedReader (firTheFile);

      String sTextLine;

      sTextLine = buffrTextFile.readLine();
      while (sTextLine != null)
      {
	if (sTextLine.matches("\\s*\\*.*"))
	 { System.out.println(sTextLine); }

        sTextLine = buffrTextFile.readLine();
      }
      System.exit (-1);
       
    }  //-- if, else [Command Line Arguments]
  
     
    
   File fLocalFile = new File(sLocalFileName);
   if (!fLocalFile.exists()) 
   {
      System.out.println(
        "A PROBLEM OCCURRED:   \n" +
        "  The file '" + fLocalFile.getName() + "' does not appear to exist. \n" +
	"  The program is interpreting this as the file: " + fLocalFile.getAbsolutePath() + "\n" +
	"  Please check the name and try again. Sorry for the inconvenience. \n" + 
	"  Type 'java PutDavFile' to see a brief help message. ");
      System.exit(-1);    
   }
    
   if (!fLocalFile.canRead()) 
   {
      System.out.println(
        "The file " + fLocalFile.getName() + " cannot be 'read' by this program. In order for this program \n" +
	"to work the permission for the file will need to be changed. For example, on a Unix system you \n" +
	"can make the file 'readable' by everyone by typing 'chmod a+r TheFileName'. However, you will only \n" +
	"be able to do this if you are the 'owner' of the file, or if you are the 'system administrator'. \n" +
	"For more extensive Unix help please consult a worthy manual such as http://www.dsl.org/ ");
      System.exit(-1);    
   }

   if (fLocalFile.isDirectory()) 
   {
      System.out.println(
        "The file " + fLocalFile.getName() + " appears to be a directory \n" +
	"This program is not able to upload whole directories of files, at the moment \n" +
	" ");
      System.exit(-1);    
   } 

   sLocalFileName = fLocalFile.getName();
   sLocalFileFullName = fLocalFile.getAbsolutePath();

   if (sRemoteLocation.matches(".*/$"))
   {
     //System.out.println("yep");
     sRemoteLocation = sRemoteLocation + sLocalFileName;
   }
   
   // Used for debugging
   if (0 == 0)
   {
     System.out.println(
      "VARIABLES     \n" +
      "  sLocalFileName=" + sLocalFileName + "\n" +
      "  sLocalFileFullName=" + sLocalFileFullName  + "\n" +
      "  sRemoteLocation=" + sRemoteLocation  + "\n" +
      "  sWebdavUser=" + sWebdavUser + "\n" +
      "  sWebdavPassword=" + sWebdavPassword + "\n" +
      "  sWebdavServer=" + sWebdavServer  + "\n" +
      "INFORMATION ABOUT THE LOCAL FILE   \n" +
      "  File Exists=" + fLocalFile.exists() + "\n" +
      "  File is Readable=" + fLocalFile.canRead() + "\n" +
      "  File is Writable=" + fLocalFile.canWrite() + "\n" +
      "  File is a Directory=" + fLocalFile.isDirectory() + "\n" + 
      "  Absolute Path=" + fLocalFile.getAbsolutePath() + "\n" +
      "  Canonical Path=" + fLocalFile.getCanonicalPath() + "\n" +
      "  File Name=" + fLocalFile.getName() + "\n" +
      "  File Parent=" + fLocalFile.getParent() + "\n" +
      "  File Path=" + fLocalFile.getPath() + "\n"); 
   }

   HttpURL httpURL = new HttpURL(sWebdavServer);
   httpURL.setUserInfo(sWebdavUser, sWebdavPassword);
   WebdavResource webdavResource = new WebdavResource(httpURL);
   //webdavResource.setDebug();
   //webdavResource.getPath());

   //-- This is some basic code to list the contents of a webdav folder
   /*
   StringBuffer sbFolder = new StringBuffer();
   String[] aaFiles = webdavResource.list();
   for (int ii = 0; ii < aaFiles.length; ii++)
   {
     sbFolder.append(aaFiles[ii] + "\n");
   }
   System.out.println(sbFolder);
   System.out.println(webdavResource.getHttpURL().toString());

   */


   try
   {
      String src = sLocalFileName;
      String dest =  sRemoteLocation;
      // /slide/files/documents/alexis_docs/
      //File fLocalFile = new File(dir.getCanonicalPath(), src);
      System.out.print("Uploading  '" + src + "' to '" + dest + "': ");
      if (webdavResource.putMethod(dest, fLocalFile))
      {
        System.out.println("The file upload succeeded.");
      }
      else 
      {
	String sServerResponse = webdavResource.getStatusMessage();
	System.out.println("The file upload failed. The following message was provided:");
        System.out.println(sServerResponse);
	if (sServerResponse.matches(".*Conflict.*409.*"))
	{
	  System.out.println(
	    "This message means that the location you specified was probably invalid");
	} //-- if is 'conflict'
      } //-- if, else
    }
    catch (Exception ex)
    {
      System.out.println(
	"an unspecified problem ocurred while uploading the file to the WebDav Server. Sorry");
    }

   webdavResource.close();

   System.out.println("disconnected from the WebDav Server");
  }   // main
  
  
    /**
     * This method transfers a file from the local filesystem onto the WebDav Server
     * The method was cut and paste from the source code for the Apache Slide WebDav client
     * This code can be found at 
     *   http://cvs.apache.org/viewcvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/cmd/
     *
     * The code was then modified by me
     *
     * @param sLocalFileName  This is the file which will be transfered
     * @param sRemoteLocation This is the path on the WebDav server where the file will be put
     *
     *
     * @see http://cvs.apache.org/viewcvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/cmd/
     *
     */
    void put(String sLocalFileName, String sRemoteLocation)
    {
       System.out.println("This method does nothing with " + sLocalFileName + " " + sRemoteLocation);
    } //method: put

    
} // class: GetDavFile 

