/*
 * $Header: /home/cvspublic/jakarta-slide/src/tests/client/WebdavTest.java,v 1.3 2002/04/25 21:15:14 jericho Exp $
 * $Revision: 1.3 $
 * $Date: 2002/04/25 21:15:14 $
 *
 * ====================================================================
 *
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Slide", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * [Additional notices, if required by prior licensing conditions]
 *
 */

//package client;

import org.apache.webdav.lib.WebdavResource;
import java.io.IOException;
import org.apache.util.HttpURL;
import org.apache.commons.httpclient.HttpException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;

public class WebdavTest {

  final String baseHost = "localhost";
  final int basePort = 7001;
  final String basePath = "/slide-webdav";

  public WebdavTest() {
  }

  public void testRead() throws IOException, HttpException {
    testRead(baseHost, basePort, basePath);
  }

  private void testRead(String baseHost, int basePort, String basePath) throws IOException, HttpException {
    WebdavResource base = null;
    try {
      base = new WebdavResource(new HttpURL("tomcat", "tomcat", baseHost, basePort, basePath));
      WebdavResource content [] = base.listWebdavResources();
      for(int i=0; i<content.length; i++) {
        System.out.println(
          i + ": " +
          content[i].getDisplayName() + ", " +
          content[i].getGetContentType()  + ", " +
          content[i].getGetContentLength()  + ", " +
          content[i].getCreationDate() + ", " +
          content[i].getResourceType().getPropertyAsString()
        );
        load(content[i]);
      }
      if(content.length==0)
        System.out.println("no entries in " + base);

    } finally {
      if(base!=null)
        base.close();
    }

  }

  private void load(WebdavResource wres) throws IOException, HttpException {
    if(wres.getResourceType().isCollection()) {
      System.out.println("   Collection " + wres.getDisplayName() +  " cannot be loaded");
      return;
    }
    InputStream is = null;
    try {
      is = wres.getMethodData();
      byte [] buf = new byte[1024];
      int totals = 0;
      int cnt = 0;
      while((cnt=is.read(buf))>0) {
        totals+=cnt;
      }
      System.out.println("   " + totals + " Bytes read for " + wres.getDisplayName());
    } finally {
      if(is!=null)
        is.close();
    }
  }

  private void testWrite() throws IOException, HttpException {
    WebdavResource base = null;
    try {
      base = new WebdavResource(new HttpURL("OpalSystem", "opal", baseHost, basePort, basePath+"/out"));
      if(!base.mkcolMethod())
        throw new RuntimeException("Could not create " + base.getHttpURL());

      WebdavResource file = null;
      try {
        file = new WebdavResource(base.getHttpURL(), "test.html");
        file.setUserInfo("tomcat", "tomcat");
        if(!file.putMethod("<html><head><title>Test</title><body>"+ new Date() + "</body></html>"))
          throw new RuntimeException("could not write to file");

        String target;

        target = new HttpURL(base.getHttpURL(), "test-one.html").toExternalForm();
        if(!file.copyMethod(target))
          throw new RuntimeException("could not copy file");

        target = new HttpURL(base.getHttpURL(), "test-two.html").toExternalForm();
        if(!file.moveMethod(target))
          throw new RuntimeException("could not move file");

        target = new HttpURL(base.getHttpURL(), "test-one.html").toExternalForm();
        if(!file.deleteMethod(target))
          throw new RuntimeException("could not delete file 1");

        target = new HttpURL(base.getHttpURL(), "test-two.html").toExternalForm();
        if(!file.deleteMethod(target))
          throw new RuntimeException("could not delete file 2");
        if(!base.deleteMethod())
          throw new RuntimeException("could not delete directory");
      } finally {
        if(file!=null)
          file.close();
      }

    } finally {
      if(base!=null)
        base.close();
    }
  }

  private void testWebInf() throws IOException, HttpException {
    testRead(baseHost, basePort, basePath + "/WEB-INF");
  }
int cnt=0;
  private void testLock() throws IOException, HttpException {
    WebdavResource base = null;
    try {
      base = new WebdavResource(new HttpURL("tomcat", "tomcat", baseHost, basePort, basePath+"/test-dir/tes.txt"));
      if (!base.exists()) {
        System.out.println(base + " does not exist");
        return;
      }
      Enumeration en = base.getActiveLockOwners();
      if(en==null || !en.hasMoreElements()) {
        System.out.println("No locks on " + base);
        if(cnt==0) {
          cnt++;
          if(!base.lockMethod())
            throw new RuntimeException("Could not lock " + base);
          System.out.println("Locked " + base);
          try {
            testLock();
          } finally {
            if(!base.unlockMethod())
              throw new RuntimeException("Could not unlock " + base);
            System.out.println("Unlocked " + base);
          }
          testLock();
        }
      }
      else {
        while(en.hasMoreElements())
          System.out.println("Lock on " + base + " by " + en.nextElement());
      }

    } finally {
      if(base!=null)
        base.close();
    }
  }

  private void testUser() throws IOException {
    WebdavResource base = null;
    try {
      base = new WebdavResource(new HttpURL("xxx", "xxx", baseHost, basePort, basePath+"/index.html"));
      throw new RuntimeException("Illegal user was granted access");
    } catch(HttpException e) {
      System.out.println("user test ok");
    } finally {
      if(base!=null)
        base.close();
    }
  }

  public static void main(String[] args) throws Exception {
    WebdavTest test = new WebdavTest();
    test.testRead();
    test.testWrite();
    test.testWebInf();
    test.testLock();
    test.testUser();
    System.out.println("Test complete");
  }
}

