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 GetDavFile TheWebDavLocationPath [TheLocalFile] [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 GetDavFile shopping-list.xml /documents/thingsToDo/     
  *
  * Bugs:
  *   If you finish the remote file path with a forward slash / then the program seems to 
  *   'amalgamate' the two command line variables into one
  *</pre>  
  *  
  *  
  *  
  *  
  * This appears to be working (2 august 2003).  
  * @author mjb
  * @see "http://www.ella-associates.org/utils/TestJavaMail.java"
  */
public class GetDavFile 
{


  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/";

    if (args.length == 1)
    {
      sRemoteLocation = args[0];
    }
    else if (args.length == 2)
    {
      sRemoteLocation = args[0];
      sLocalFileName = args[1];
    }
    else if (args.length == 4)
    {
      sRemoteLocation = args[0];
      sLocalFileName = args[1];
      sWebdavUser = args[2];
      sWebdavPassword = args[3];
    }
    else if (args.length == 5)
    {
      sRemoteLocation = args[0];
      sLocalFileName = 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/GetDavFile.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]
  
     
   HttpURL httpURL = new HttpURL(sWebdavServer);
   httpURL.setUserInfo(sWebdavUser, sWebdavPassword);
   WebdavResource webdavResource = new WebdavResource(httpURL, sRemoteLocation);

   if (!webdavResource.exists())
   {
     System.out.println(
       "The resource [" + sRemoteLocation + "] which you specified to get from the \n" +
       "WebDav server [" + sWebdavServer + "] does not appear to exist. If you enter a directory \n" +
       "name you should see a list of resources in that directory. This may help you locate what \n" +
       "you are looking for");
     System.exit(-1);
     
   } //-- if 

   if (webdavResource.isCollection())
   {

     StringBuffer sbFolder = new StringBuffer();
     String[] aaFiles = webdavResource.list();
     for (int ii = 0; ii < aaFiles.length; ii++)
     {
       sbFolder.append(aaFiles[ii] + "\n");
     }
     System.out.println("WEB DAV COLLECTION LISTING FOR: " + sRemoteLocation);
     System.out.println(sbFolder);
     System.exit(0);
     
   } //-- if 
   
   if (sLocalFileName == "") 
   {
     sLocalFileName = webdavResource.getDisplayName();
   } //-- if 
   
   File fLocalFile = new File(sLocalFileName);
   if (fLocalFile.exists()) 
   {
      System.out.println(
        "PLEASE NOTE:   \n" +
        "  The file '" + fLocalFile.getAbsolutePath() + "' already exists. \n" +
	"  If you continue this file will be overwritten. Do you wish to continue? \n" + 
	"   ");
      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);    
   }
   */

   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"); 
   }

   //-- for debugging the webdav resource
   if (0 == 0)
   {
     System.out.println("webdavResource.exists()=" + webdavResource.exists());
     System.out.println("webdavResource.getExistence()=" + webdavResource.getExistence());
     System.out.println("webdavResource.getDisplayName()=" + webdavResource.getDisplayName());
     System.out.println("webdavResource.getGetLastModified()=" + webdavResource.getGetLastModified());
     System.out.println("webdavResource.getGetContentLength()=" + webdavResource.getGetContentLength());
     System.out.println("webdavResource.getHost()=" + webdavResource.getHost());
     System.out.println("webdavResource.getHttpURL()=" + webdavResource.getHttpURL());
     System.out.println("webdavResource.getHttpURLExceptForUserInfo()=" + webdavResource.getHttpURLExceptForUserInfo());
     System.out.println("webdavResource.getIsCollection()=" + webdavResource.getIsCollection());
     System.out.println("webdavResource.isCollection()=" + webdavResource.isCollection());
     System.out.println("webdavResource.getIsHidden()=" + webdavResource.getIsHidden());
     System.out.println("webdavResource.getPath()=" + webdavResource.getPath());
     System.out.println("webdavResource.getHost()=" + webdavResource.getHost());
     System.out.println("webdavResource.getHost()=" + webdavResource.getHost());
     System.out.println("webdavResource.getHost()=" + webdavResource.getHost());
     System.out.println("webdavResource.getHost()=" + webdavResource.getHost());
     
   }

   if (fLocalFile.isDirectory()) 
   {
      System.out.println(
        "The file " + fLocalFile.getName() + " appears to be a directory \n" +
	" \n" +
	" ");
      // Then add the remote name and continue
      // sLocalFileName = sLocalFileName + HttpURL.getName(sRemoteLocation);
      // fLocalFile = new File(sLocalFileName); 
      System.exit(-1);    
   } 


   try
   {

      //--The ella associates doc directory = /slide/files/documents/alexis_docs/
      //--
      System.out.print("downloading  '" + sRemoteLocation + "' to '" + sLocalFileName + "': ");
      if (webdavResource.getMethod(fLocalFile))
      {
        System.out.println("The file download succeeded.");
      }
      else 
      {
	String sServerResponse = webdavResource.getStatusMessage();
	System.out.println("The file download 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 downloading the file from the WebDav Server. Sorry");
    }

   webdavResource.close();

   System.out.println("disconnected from the WebDav Server");
  }   // main
  
    
} // class: GetDavFile 

