Java Source Code: com.portalbook.portlets.WebDAVHelper


   1: package com.portalbook.portlets;
   2: 
   3: import java.io.*;
   4: 
   5: import org.apache.commons.httpclient.HttpException;
   6: import org.apache.commons.httpclient.HttpURL;
   7: 
   8: import org.apache.webdav.lib.WebdavResource;
   9: 
  10: public class WebDAVHelper
  11:	  {
  12:    private WebdavResource resource = null;
  13:
  14:    protected void openURL(String uri, String username, String password)
  15:        throws HttpException, IOException
  16:	      {
  17:        HttpURL url = new HttpURL(uri);
  18:
  19:        if (resource == null)
  20:	          {
  21:            url.setUserinfo(username, password);
  22:            resource = new WebdavResource(url);
  23:        }
  24:        else
  25:	          {
  26:            resource.close();
  27:            resource.setHttpURL(url);
  28:        }
  29:    }
  30:
  31:    protected void setPath(String path) throws WebDAVException
  32:	      {
  33:        try
  34:	          {
  35:            String collPath = fixPath(path);
  36:            resource.setPath(collPath);
  37:            if (!resource.exists())
  38:	              {
  39:                throw new WebDAVException("Path does not exist.");
  40:            }
  41:        }
  42:        catch (Exception e)
  43:	          {
  44:            throw new WebDAVException(e.getMessage(), e);
  45:        }
  46:    }
  47:
  48:    protected String getParentPath(String path)
  49:	      {
  50:        path = fixPath(path);
  51:
  52:        //for the root and any paths right beneath it.
  53:        if (path.lastIndexOf('/') == path.indexOf('/', 1))
  54:	          {
  55:            return path;
  56:        }
  57:
  58:        //our paths have a trailing slash        
  59:        int trailingSlashIndex = path.lastIndexOf('/');
  60:        String cleanedPath = path.substring(0, trailingSlashIndex);
  61:
  62:        int lastSlashIndex = cleanedPath.lastIndexOf('/');
  63:        String parentPath = cleanedPath.substring(0, lastSlashIndex + 1);
  64:
  65:        System.out.println("parent path: " + parentPath);
  66:        return parentPath;
  67:
  68:    }
  69:
  70:    protected String fixPath(String path)
  71:	      {
  72:        if (!path.startsWith("/"))
  73:	          {
  74:            path = resource.getPath() + "/" + path;
  75:        }
  76:
  77:        //clean up any double slashes
  78:        path = path.replaceAll("//", "/");
  79:
  80:        return path;
  81:    }
  82:
  83:    public WebdavResource getResource()
  84:	      {
  85:        return resource;
  86:    }
  87:
  88:}