[jboss-svn-commits] JBL Code SVN: r20121 - in labs/jbossrules/trunk/drools-jbrms/src: main/java/net/sf/webdav/exceptions and 6 other directories.
jboss-svn-commits at lists.jboss.org
jboss-svn-commits at lists.jboss.org
Thu May 22 22:05:19 EDT 2008
Author: michael.neale at jboss.com
Date: 2008-05-22 22:05:18 -0400 (Thu, 22 May 2008)
New Revision: 20121
Added:
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/LocalFileSystemStore.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/MethodExecutor.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/MimeTyper.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/ResourceLocks.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/WebDavServletBean.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/WebdavStatus.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/WebdavStore.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/AccessDeniedException.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/ObjectAlreadyExistsException.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/ObjectNotFoundException.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/UnauthenticatedException.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/WebdavException.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/fromcatalina/
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/fromcatalina/MD5Encoder.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/fromcatalina/RequestUtil.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/fromcatalina/URLEncoder.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/fromcatalina/XMLWriter.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/AbstractMethod.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DeterminableMethod.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoCopy.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoDelete.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoGet.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoHead.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoLock.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoMkcol.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoMove.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoNotImplemented.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoOptions.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoPropfind.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoPut.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/ReportingMethod.java
labs/jbossrules/trunk/drools-jbrms/src/main/java/org/drools/brms/server/files/WebdavServlet.java
Removed:
labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/WebdavServlet.java
Modified:
labs/jbossrules/trunk/drools-jbrms/src/main/java/org/drools/brms/JBRMS.gwt.xml
labs/jbossrules/trunk/drools-jbrms/src/main/java/org/drools/brms/server/files/WebDAVImpl.java
labs/jbossrules/trunk/drools-jbrms/src/main/webapp/WEB-INF/web.xml
labs/jbossrules/trunk/drools-jbrms/src/test/java/org/drools/brms/server/files/WebDAVImplTest.java
Log:
JBRULES-1612 WebDAV - works on all known webdav type 2 clients
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/LocalFileSystemStore.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/LocalFileSystemStore.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/LocalFileSystemStore.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,233 @@
+/*
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package net.sf.webdav;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import net.sf.webdav.exceptions.WebdavException;
+
+/**
+ * Reference Implementation of WebdavStore
+ *
+ * @author joa
+ * @author re
+ */
+public class LocalFileSystemStore implements WebdavStore {
+
+ private static org.slf4j.Logger log = org.slf4j.LoggerFactory
+ .getLogger(LocalFileSystemStore.class);
+
+ private static int BUF_SIZE = 50000;
+
+ private File root = null;
+
+ public LocalFileSystemStore(File root) {
+ this.root = root;
+ }
+
+ public void begin(Principal principal) throws WebdavException {
+ log.trace("LocalFileSystemStore.begin()");
+ if (!root.exists()) {
+ if (!root.mkdirs()) {
+ throw new WebdavException("root path: "
+ + root.getAbsolutePath()
+ + " does not exist and could not be created");
+ }
+ }
+ }
+
+ public void checkAuthentication() throws SecurityException {
+ log.trace("LocalFileSystemStore.checkAuthentication()");
+ // do nothing
+
+ }
+
+ public void commit() throws WebdavException {
+ // do nothing
+ log.trace("LocalFileSystemStore.commit()");
+ }
+
+ public void rollback() throws WebdavException {
+ // do nothing
+ log.trace("LocalFileSystemStore.rollback()");
+
+ }
+
+ public boolean objectExists(String uri) throws WebdavException {
+ File file = new File(root, uri);
+ log.trace("LocalFileSystemStore.objectExists(" + uri + ")="
+ + file.exists());
+ return file.exists();
+ }
+
+ public boolean isFolder(String uri) throws WebdavException {
+ File file = new File(root, uri);
+ log.trace("LocalFileSystemStore.isFolder(" + uri + ")="
+ + file.isDirectory());
+ return file.isDirectory();
+ }
+
+ public boolean isResource(String uri) throws WebdavException {
+ File file = new File(root, uri);
+ log.trace("LocalFileSystemStore.isResource(" + uri + ") "
+ + file.isFile());
+ return file.isFile();
+ }
+
+ public void createFolder(String uri) throws WebdavException {
+ log.trace("LocalFileSystemStore.createFolder(" + uri + ")");
+ File file = new File(root, uri);
+ if (!file.mkdir())
+ throw new WebdavException("cannot create folder: " + uri);
+ }
+
+ public void createResource(String uri) throws WebdavException {
+ log.trace("LocalFileSystemStore.createResource(" + uri + ")");
+ File file = new File(root, uri);
+ try {
+ if (!file.createNewFile())
+ throw new WebdavException("cannot create file: " + uri);
+ } catch (IOException e) {
+ log
+ .error("LocalFileSystemStore.createResource(" + uri
+ + ") failed");
+ throw new WebdavException(e);
+ }
+ }
+
+ /**
+ * tries to save the given InputStream to the file at path "uri". content
+ * type and charachter encoding are ignored
+ */
+ public void setResourceContent(String uri, InputStream is,
+ String contentType, String characterEncoding)
+ throws WebdavException {
+
+ log.trace("LocalFileSystemStore.setResourceContent(" + uri + ")");
+ File file = new File(root, uri);
+ try {
+ OutputStream os = new BufferedOutputStream(new FileOutputStream(
+ file));
+ try {
+ int read;
+ byte[] copyBuffer = new byte[BUF_SIZE];
+
+ while ((read = is.read(copyBuffer, 0, copyBuffer.length)) != -1) {
+ os.write(copyBuffer, 0, read);
+ }
+ } finally {
+ try {
+ is.close();
+ } finally {
+ os.close();
+ }
+ }
+ } catch (IOException e) {
+ log.error("LocalFileSystemStore.setResourceContent(" + uri
+ + ") failed");
+ throw new WebdavException(e);
+ }
+ }
+
+ public Date getLastModified(String uri) throws WebdavException {
+ log.trace("LocalFileSystemStore.getLastModified(" + uri + ")");
+ File file = new File(root, uri);
+ return new Date(file.lastModified());
+ }
+
+ /**
+ * @return the lastModified date of the file, java.io.file does not support
+ * a creation date
+ */
+ public Date getCreationDate(String uri) throws WebdavException {
+ log.trace("LocalFileSystemStore.getCreationDate(" + uri + ")");
+ // TODO return creation date instead of last modified
+ File file = new File(root, uri);
+ return new Date(file.lastModified());
+ }
+
+ /**
+ * @return a (possibly empty) list of children, or <code>null</code> if
+ * the uri points to a file
+ */
+ public String[] getChildrenNames(String uri) throws WebdavException {
+ log.trace("LocalFileSystemStore.getChildrenNames(" + uri + ")");
+ File file = new File(root, uri);
+ if (file.isDirectory()) {
+
+ File[] children = file.listFiles();
+ List childList = new ArrayList();
+ for (int i = 0; i < children.length; i++) {
+ String name = children[i].getName();
+ childList.add(name);
+
+ }
+ String[] childrenNames = new String[childList.size()];
+ childrenNames = (String[]) childList.toArray(childrenNames);
+ return childrenNames;
+ } else {
+ return null;
+ }
+
+ }
+
+ /**
+ * @return an input stream to the specified resource
+ */
+ public InputStream getResourceContent(String uri) throws WebdavException {
+ log.trace("LocalFileSystemStore.getResourceContent(" + uri + ")");
+ File file = new File(root, uri);
+
+ InputStream in;
+ try {
+ in = new BufferedInputStream(new FileInputStream(file));
+ } catch (IOException e) {
+ log.error("LocalFileSystemStore.getResourceContent(" + uri
+ + ") failed");
+
+ throw new WebdavException(e);
+ }
+ return in;
+ }
+
+ public long getResourceLength(String uri) throws WebdavException {
+ log.trace("LocalFileSystemStore.getResourceLength(" + uri + ")");
+ File file = new File(root, uri);
+ return file.length();
+ }
+
+ public void removeObject(String uri) throws WebdavException {
+ File file = new File(root, uri);
+ boolean success = file.delete();
+ log.trace("LocalFileSystemStore.removeObject(" + uri + ")=" + success);
+ if (!success) {
+ throw new WebdavException("cannot delete object: " + uri);
+ }
+
+ }
+
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/LocalFileSystemStore.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/MethodExecutor.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/MethodExecutor.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/MethodExecutor.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,27 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package net.sf.webdav;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+public interface MethodExecutor {
+
+ void execute(HttpServletRequest req, HttpServletResponse resp)
+ throws IOException;
+
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/MethodExecutor.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/MimeTyper.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/MimeTyper.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/MimeTyper.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,6 @@
+package net.sf.webdav;
+
+public interface MimeTyper {
+
+ String getMimeType(String path);
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/MimeTyper.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/ResourceLocks.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/ResourceLocks.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/ResourceLocks.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,445 @@
+/*
+ * Copyright 2005-2006 webdav-servlet group.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.sf.webdav;
+
+import java.util.Hashtable;
+
+/**
+ * some very simple locking management for concurrent data access, NOT the
+ * webdav locking. ( could that be used instead? )
+ *
+ * @author re
+ */
+public class ResourceLocks {
+
+ /**
+ * after creating this much LockObjects, a cleanup delets unused LockObjects
+ */
+ private final int fCleanupLimit = 100000;
+
+ private int fCleanupCounter = 0;
+
+ /**
+ * keys: path value: LockObject from that path
+ */
+ private Hashtable fLocks = null;
+
+ // REMEMBER TO REMOVE UNUSED LOCKS FROM THE HASHTABLE AS WELL
+
+ private LockObject fRoot = null;
+
+ public ResourceLocks() {
+ this.fLocks = new Hashtable();
+ fRoot = new LockObject("/");
+ }
+
+ /**
+ * trys to lock the resource at "path".
+ *
+ *
+ * @param path
+ * what resource to lock
+ * @param owner
+ * the owner of the lock
+ * @param exclusive
+ * if the lock should be exclusive (or shared)
+ * @return true if the resource at path was successfully locked, false if an
+ * existing lock prevented this
+ * @param depth
+ * depth
+ */
+ public synchronized boolean lock(String path, String owner,
+ boolean exclusive, int depth) {
+
+ LockObject lo = generateLockObjects(path);
+ if (lo.checkLocks(exclusive, depth)) {
+ if (lo.addLockObjectOwner(owner)) {
+ lo.fExclusive = exclusive;
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ // can not lock
+ return false;
+ }
+ }
+
+ /**
+ * unlocks all resources at "path" (and all subfolders if existing)<p/>
+ * that have the same owner
+ *
+ * @param path
+ * what resource to unlock
+ * @param owner
+ * who wants to unlock
+ */
+ public synchronized void unlock(String path, String owner) {
+
+ if (this.fLocks.containsKey(path)) {
+ LockObject lo = (LockObject) this.fLocks.get(path);
+ lo.removeLockObjectOwner(owner);
+ // System.out.println("number of LockObjects in the hashtable: "
+ // + fLocks.size());
+
+ } else {
+ // there is no lock at that path. someone tried to unlock it
+ // anyway. could point to a problem
+ System.out
+ .println("net.sf.webdav.ResourceLocks.unlock(): no lock for path "
+ + path);
+ }
+
+ if (fCleanupCounter > fCleanupLimit) {
+ fCleanupCounter = 0;
+ cleanLockObjects(fRoot);
+ }
+ }
+
+ /**
+ * generates LockObjects for the resource at path and its parent folders.
+ * does not create new LockObjects if they already exist
+ *
+ * @param path
+ * path to the (new) LockObject
+ * @return the LockObject for path.
+ */
+ private LockObject generateLockObjects(String path) {
+ if (!this.fLocks.containsKey(path)) {
+ LockObject returnObject = new LockObject(path);
+ String parentPath = getParentPath(path);
+ if (parentPath != null) {
+ LockObject parentLockObject = generateLockObjects(parentPath);
+ parentLockObject.addChild(returnObject);
+ returnObject.fParent = parentLockObject;
+ }
+
+ return returnObject;
+ } else {
+ return (LockObject) this.fLocks.get(path);
+ }
+
+ }
+
+ /**
+ * deletes unused LockObjects and resets the counter. works recursively
+ * starting at the given LockObject
+ *
+ * @param lo
+ * lock object
+ *
+ * @return if cleaned
+ */
+ private boolean cleanLockObjects(LockObject lo) {
+
+ if (lo.fChildren == null) {
+ if (lo.fOwner == null) {
+ lo.removeLockObject();
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ boolean canDelete = true;
+ int limit = lo.fChildren.length;
+ for (int i = 0; i < limit; i++) {
+ if (!cleanLockObjects(lo.fChildren[i])) {
+ canDelete = false;
+ } else {
+
+ // because the deleting shifts the array
+ i--;
+ limit--;
+ }
+ }
+ if (canDelete) {
+ if (lo.fOwner == null) {
+ lo.removeLockObject();
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ return false;
+ }
+ }
+ }
+
+ /**
+ * creates the parent path from the given path by removing the last '/' and
+ * everything after that
+ *
+ * @param path
+ * the path
+ * @return parent path
+ */
+ private String getParentPath(String path) {
+ int slash = path.lastIndexOf('/');
+ if (slash == -1) {
+ return null;
+ } else {
+ if (slash == 0) {
+ // return "root" if parent path is empty string
+ return "/";
+ } else {
+ return path.substring(0, slash);
+ }
+ }
+ }
+
+ // ----------------------------------------------------------------------------
+
+ /**
+ * a helper class for ResourceLocks, represents the Locks
+ *
+ * @author re
+ *
+ */
+ private class LockObject {
+
+ String fPath;
+
+ /**
+ * owner of the lock. shared locks can have multiple owners. is null if
+ * no owner is present
+ */
+ String[] fOwner = null;
+
+ /**
+ * children of that lock
+ */
+ LockObject[] fChildren = null;
+
+ LockObject fParent = null;
+
+ /**
+ * weather the lock is exclusive or not. if owner=null the exclusive
+ * value doesn't matter
+ */
+ boolean fExclusive = false;
+
+ /**
+ *
+ * @param path
+ * the path to the locked object
+ */
+ LockObject(String path) {
+ this.fPath = path;
+ fLocks.put(path, this);
+
+ fCleanupCounter++;
+ }
+
+ /**
+ * adds a new owner to a lock
+ *
+ * @param owner
+ * string that represents the owner
+ * @return true if the owner was added, false otherwise
+ */
+ boolean addLockObjectOwner(String owner) {
+ if (this.fOwner == null) {
+ this.fOwner = new String[1];
+ } else {
+
+ int size = this.fOwner.length;
+ String[] newLockObjectOwner = new String[size + 1];
+
+ // check if the owner is already here (that should actually not
+ // happen)
+ for (int i = 0; i < size; i++) {
+ if (this.fOwner[i].equals(owner)) {
+ return false;
+ }
+ }
+
+ System.arraycopy(this.fOwner, 0, newLockObjectOwner, 0, size);
+ this.fOwner = newLockObjectOwner;
+ }
+
+ this.fOwner[this.fOwner.length - 1] = owner;
+ return true;
+ }
+
+ /**
+ * tries to remove the owner from the lock
+ *
+ * @param owner
+ * string that represents the owner
+ */
+ void removeLockObjectOwner(String owner) {
+ if (this.fOwner != null) {
+ int size = this.fOwner.length;
+ for (int i = 0; i < size; i++) {
+ // check every owner if it is the requested one
+ if (this.fOwner[i].equals(owner)) {
+ // remove the owner
+ String[] newLockObjectOwner = new String[size - 1];
+ for (int i2 = 0; i2 < (size - 1); i2++) {
+ if (i2 < i) {
+ newLockObjectOwner[i2] = this.fOwner[i2];
+ } else {
+ newLockObjectOwner[i2] = this.fOwner[i2 + 1];
+ }
+ }
+ this.fOwner = newLockObjectOwner;
+
+ }
+ }
+ if (this.fOwner.length == 0) {
+ this.fOwner = null;
+ }
+ }
+ }
+
+ /**
+ * adds a new child lock to this lock
+ *
+ * @param newChild
+ * new child
+ */
+ void addChild(LockObject newChild) {
+ if (this.fChildren == null) {
+ this.fChildren = new LockObject[0];
+ }
+ int size = this.fChildren.length;
+ LockObject[] newChildren = new LockObject[size + 1];
+ System.arraycopy(this.fChildren, 0, newChildren, 0, size);
+ newChildren[size] = newChild;
+ this.fChildren = newChildren;
+ }
+
+ /**
+ * deletes this Lock object. assumes that it has no children and no
+ * owners (does not check this itself)
+ *
+ */
+ void removeLockObject() {
+ if (this != fRoot) {
+ // removing from tree
+ int size = this.fParent.fChildren.length;
+ for (int i = 0; i < size; i++) {
+ if (this.fParent.fChildren[i].equals(this)) {
+ LockObject[] newChildren = new LockObject[size - 1];
+ for (int i2 = 0; i2 < (size - 1); i2++) {
+ if (i2 < i) {
+ newChildren[i2] = this.fParent.fChildren[i2];
+ } else {
+ newChildren[i2] = this.fParent.fChildren[i2 + 1];
+ }
+ }
+ if (newChildren.length != 0) {
+ this.fParent.fChildren = newChildren;
+ } else {
+ this.fParent.fChildren = null;
+ }
+ break;
+ }
+ }
+
+ // removing from hashtable
+ fLocks.remove(this.fPath);
+
+ // now the garbage collector has some work to do
+ }
+ }
+
+ /**
+ * checks if a lock of the given exclusivity can be placed, only
+ * considering cildren up to "depth"
+ *
+ * @param exclusive
+ * wheather the new lock should be exclusive
+ * @param depth
+ * the depth to which should be checked
+ * @return true if the lock can be placed
+ */
+ boolean checkLocks(boolean exclusive, int depth) {
+ return (checkParents(exclusive) && checkChildren(exclusive, depth));
+
+ }
+
+ /**
+ * helper of checkLocks(). looks if the parents are locked
+ *
+ * @param exclusive
+ * wheather the new lock should be exclusive
+ * @return true if no locks at the parent path are forbidding a new lock
+ */
+ private boolean checkParents(boolean exclusive) {
+
+ if (this.fPath.equals("/")) {
+ return true;
+ } else {
+
+ if (this.fOwner == null) {
+ // no owner, checking parents
+ return this.fParent != null
+ && this.fParent.checkParents(exclusive);
+ } else {
+ // there already is a owner
+ return !(this.fExclusive || exclusive)
+ && this.fParent.checkParents(exclusive);
+ }
+ }
+ }
+
+ /**
+ * helper of checkLocks(). looks if the children are locked
+ *
+ * @param exclusive
+ * wheather the new lock should be exclusive
+ * @return true if no locks at the children paths are forbidding a new
+ * lock
+ * @param depth
+ * depth
+ */
+ private boolean checkChildren(boolean exclusive, int depth) {
+ if (this.fChildren == null) {
+ // a file
+
+ return this.fOwner == null || !(this.fExclusive || exclusive);
+ } else {
+ // a folder
+
+ if (this.fOwner == null) {
+ // no owner, checking children
+
+ if (depth != 0) {
+ boolean canLock = true;
+ int limit = this.fChildren.length;
+ for (int i = 0; i < limit; i++) {
+ if (!this.fChildren[i].checkChildren(exclusive,
+ depth - 1)) {
+ canLock = false;
+ }
+ }
+ return canLock;
+ } else {
+ // depth == 0 -> we don't care for children
+ return true;
+ }
+ } else {
+ // there already is a owner
+ return !(this.fExclusive || exclusive);
+ }
+ }
+
+ }
+
+ }
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/ResourceLocks.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/WebDavServletBean.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/WebDavServletBean.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/WebDavServletBean.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,159 @@
+package net.sf.webdav;
+
+import net.sf.webdav.exceptions.UnauthenticatedException;
+import net.sf.webdav.exceptions.WebdavException;
+import net.sf.webdav.fromcatalina.MD5Encoder;
+import net.sf.webdav.methods.DoCopy;
+import net.sf.webdav.methods.DoDelete;
+import net.sf.webdav.methods.DoGet;
+import net.sf.webdav.methods.DoLock;
+import net.sf.webdav.methods.DoMkcol;
+import net.sf.webdav.methods.DoMove;
+import net.sf.webdav.methods.DoOptions;
+import net.sf.webdav.methods.DoPropfind;
+import net.sf.webdav.methods.DoPut;
+import net.sf.webdav.methods.DoHead;
+import net.sf.webdav.methods.DoNotImplemented;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Enumeration;
+import java.util.HashMap;
+
+public class WebDavServletBean extends HttpServlet {
+
+ private static org.slf4j.Logger log = org.slf4j.LoggerFactory
+ .getLogger(WebDavServletBean.class);
+
+ private static final boolean readOnly = false;
+ private ResourceLocks resLocks;
+ private WebdavStore store;
+ private HashMap methodMap = new HashMap();
+
+ public WebDavServletBean() {
+ this.resLocks = new ResourceLocks();
+ try {
+ MessageDigest.getInstance("MD5");
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException();
+ }
+ }
+
+ public void init(WebdavStore store, String dftIndexFile,
+ String insteadOf404, int nocontentLenghHeaders,
+ boolean lazyFolderCreationOnPut) throws ServletException {
+
+ this.store = store;
+
+ MimeTyper mimeTyper = new MimeTyper() {
+ public String getMimeType(String path) {
+ return getServletContext().getMimeType(path);
+ }
+ };
+
+ register("GET", new DoGet(store, dftIndexFile, insteadOf404, resLocks,
+ mimeTyper, nocontentLenghHeaders));
+ register("HEAD", new DoHead(store, dftIndexFile, insteadOf404,
+ resLocks, mimeTyper, nocontentLenghHeaders));
+ DoDelete doDelete = (DoDelete) register("DELETE", new DoDelete(store,
+ resLocks, readOnly));
+ DoCopy doCopy = (DoCopy) register("COPY", new DoCopy(store, resLocks,
+ doDelete, readOnly));
+ register("LOCK", new DoLock(store, resLocks, readOnly));
+ register("MOVE", new DoMove(resLocks, doDelete, doCopy, readOnly));
+ register("MKCOL", new DoMkcol(store, resLocks, readOnly));
+ register("OPTIONS", new DoOptions(store, resLocks));
+ register("PUT", new DoPut(store, resLocks, readOnly,
+ lazyFolderCreationOnPut));
+ register("PROPFIND", new DoPropfind(store, resLocks, readOnly,
+ mimeTyper));
+ register("PROPPATCH", new DoNotImplemented(readOnly));
+ register("*NO*IMPL*", new DoNotImplemented(readOnly));
+ }
+
+ private MethodExecutor register(String methodName, MethodExecutor method) {
+ methodMap.put(methodName, method);
+ return method;
+ }
+
+ /**
+ * Handles the special WebDAV methods.
+ */
+ protected void service(HttpServletRequest req, HttpServletResponse resp)
+ throws ServletException, IOException {
+
+ String methodName = req.getMethod();
+
+ debugRequest(methodName, req);
+
+ try {
+ store.begin(req.getUserPrincipal());
+ store.checkAuthentication();
+ resp.setStatus(WebdavStatus.SC_OK);
+
+ try {
+ MethodExecutor methodExecutor = (MethodExecutor) methodMap
+ .get(methodName);
+ if (methodExecutor == null) {
+ methodExecutor = (MethodExecutor) methodMap
+ .get("*NO*IMPL*");
+ }
+ methodExecutor.execute(req, resp);
+
+ store.commit();
+ } catch (IOException e) {
+ java.io.StringWriter sw = new java.io.StringWriter();
+ java.io.PrintWriter pw = new java.io.PrintWriter(sw);
+ e.printStackTrace(pw);
+ log.error("IOException: " + sw.toString());
+ resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
+ store.rollback();
+ throw new ServletException(e);
+ }
+
+ } catch (UnauthenticatedException e) {
+ resp.sendError(WebdavStatus.SC_FORBIDDEN);
+ } catch (WebdavException e) {
+ java.io.StringWriter sw = new java.io.StringWriter();
+ java.io.PrintWriter pw = new java.io.PrintWriter(sw);
+ e.printStackTrace(pw);
+ log.error("WebdavException: " + sw.toString());
+ throw new ServletException(e);
+ } catch (Exception e) {
+ java.io.StringWriter sw = new java.io.StringWriter();
+ java.io.PrintWriter pw = new java.io.PrintWriter(sw);
+ e.printStackTrace(pw);
+ log.error("Exception: " + sw.toString());
+ }
+
+ }
+
+ private void debugRequest(String methodName, HttpServletRequest req) {
+ log.trace("-----------");
+ log.trace("WebdavServlet\n request: methodName = " + methodName);
+ log.trace("time: " + System.currentTimeMillis());
+ log.trace("path: " + req.getRequestURI());
+ log.trace("-----------");
+ Enumeration e = req.getHeaderNames();
+ while (e.hasMoreElements()) {
+ String s = (String) e.nextElement();
+ log.trace("header: " + s + " " + req.getHeader(s));
+ }
+ e = req.getAttributeNames();
+ while (e.hasMoreElements()) {
+ String s = (String) e.nextElement();
+ log.trace("attribute: " + s + " " + req.getAttribute(s));
+ }
+ e = req.getParameterNames();
+ while (e.hasMoreElements()) {
+ String s = (String) e.nextElement();
+ log.trace("parameter: " + s + " " + req.getParameter(s));
+ }
+ }
+
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/WebDavServletBean.java
___________________________________________________________________
Name: svn:eol-style
+ native
Deleted: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/WebdavServlet.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/WebdavServlet.java 2008-05-23 02:03:55 UTC (rev 20120)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/WebdavServlet.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -1,1774 +0,0 @@
-/*
- * Copyright 1999,2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.webdav;
-
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.InputStream;
-import java.io.Writer;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.TimeZone;
-import java.util.Vector;
-
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-
-import org.apache.catalina.util.MD5Encoder;
-import org.apache.catalina.util.RequestUtil;
-import org.apache.catalina.util.URLEncoder;
-import org.apache.catalina.util.XMLWriter;
-import org.drools.brms.server.files.RestAPIServlet;
-import org.drools.brms.server.files.WebDAVImpl;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.InputSource;
-
-/**
- * Servlet which provides support for WebDAV level 2.
- *
- * the original class is org.apache.catalina.servlets.WebdavServlet
- */
-
-public class WebdavServlet extends HttpServlet {
-
- // -------------------------------------------------------------- Constants
-
- private static final String METHOD_HEAD = "HEAD";
-
- private static final String METHOD_PROPFIND = "PROPFIND";
-
- private static final String METHOD_PROPPATCH = "PROPPATCH";
-
- private static final String METHOD_MKCOL = "MKCOL";
-
- private static final String METHOD_COPY = "COPY";
-
- private static final String METHOD_MOVE = "MOVE";
-
- private static final String METHOD_PUT = "PUT";
-
- private static final String METHOD_GET = "GET";
-
- private static final String METHOD_OPTIONS = "OPTIONS";
-
- private static final String METHOD_DELETE = "DELETE";
-
- // header names
-
- /**
- * MD5 message digest provider.
- */
- protected static MessageDigest md5Helper;
-
- /**
- * The MD5 helper object for this class.
- */
- protected static final MD5Encoder md5Encoder = new MD5Encoder();
-
- /**
- * Default depth is infite.
- */
- private static final int INFINITY = 3; // To limit tree browsing a bit
-
- /**
- * PROPFIND - Specify a property mask.
- */
- private static final int FIND_BY_PROPERTY = 0;
-
- /**
- * PROPFIND - Display all properties.
- */
- private static final int FIND_ALL_PROP = 1;
-
- /**
- * PROPFIND - Return property names.
- */
- private static final int FIND_PROPERTY_NAMES = 2;
-
- /**
- * size of the io-buffer
- */
- private static int BUF_SIZE = 50000;
-
- /**
- * Default namespace.
- */
- protected static final String DEFAULT_NAMESPACE = "DAV:";
-
- /**
- * Simple date format for the creation date ISO representation (partial).
- */
- protected static final SimpleDateFormat creationDateFormat = new SimpleDateFormat(
- "yyyy-MM-dd'T'HH:mm:ss'Z'");
-
- /**
- * indicates that the store is readonly ?
- */
- private static final boolean readOnly = false;
-
- static {
- creationDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
- }
-
- /**
- * Array containing the safe characters set.
- */
- protected static URLEncoder urlEncoder;
- /**
- * GMT timezone - all HTTP dates are on GMT
- */
- static {
- urlEncoder = new URLEncoder();
- urlEncoder.addSafeCharacter('-');
- urlEncoder.addSafeCharacter('_');
- urlEncoder.addSafeCharacter('.');
- urlEncoder.addSafeCharacter('*');
- urlEncoder.addSafeCharacter('/');
- }
-
- // ----------------------------------------------------- Instance Variables
-
- private ResourceLocks fResLocks = null;
-
- private IWebdavStorage fStore = null;
-
- private static final String DEBUG_PARAMETER = "servletDebug";
-
- private static int fdebug = -1;
-
- private WebdavStoreFactory fFactory;
-
- private Hashtable fParameter;
-
- /**
- * Initialize this servlet.
- */
- public void init() throws ServletException {
- try {
- md5Helper = MessageDigest.getInstance("MD5");
- } catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- throw new IllegalStateException();
- }
-
- // Parameters from web.xml
-// String clazz = getServletConfig().getInitParameter(
-// "ResourceHandlerImplementation");
- try {
- fFactory = new WebdavStoreFactory(WebDAVImpl.class);
- // parameter
- fParameter = new Hashtable();
- Enumeration initParameterNames = getServletConfig()
- .getInitParameterNames();
- while (initParameterNames.hasMoreElements()) {
- String key = (String) initParameterNames.nextElement();
- fParameter.put(key, getServletConfig().getInitParameter(key));
- }
-
-
- fStore = fFactory.getStore();
- fResLocks = new ResourceLocks();
- String debugString = (String) fParameter.get(DEBUG_PARAMETER);
- if (debugString == null) {
- fdebug = 0;
- } else {
- fdebug = Integer.parseInt(debugString);
- }
-
- } catch (Exception e) {
- e.printStackTrace();
- throw new ServletException(e);
- }
- }
-
-
- /**
- * Will actually check if they are authed.
- */
- @Override
- protected void service(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- String auth = req.getHeader("Authorization");
- if (!RestAPIServlet.allowUser(auth)) {
- resp.setHeader("WWW-Authenticate", "BASIC realm=\"users\"");
- resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
- } else {
- serviceInternal(req, resp);
- }
- }
-
- /**
- * Handles the special WebDAV methods.
- */
- private void serviceInternal(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
-
- String method = req.getMethod();
-
- if (fdebug == 1) {
- System.out.println("-----------");
- System.out.println("WebdavServlet\n request: method = " + method);
- System.out.println("Zeit: " + System.currentTimeMillis());
- System.out.println("path: " + getRelativePath(req));
- System.out.println("-----------");
- Enumeration e = req.getHeaderNames();
- while (e.hasMoreElements()) {
- String s = (String) e.nextElement();
- System.out.println("header: " + s + " " + req.getHeader(s));
- }
- e = req.getAttributeNames();
- while (e.hasMoreElements()) {
- String s = (String) e.nextElement();
- System.out.println("attribute: " + s + " "
- + req.getAttribute(s));
- }
- e = req.getParameterNames();
- while (e.hasMoreElements()) {
- String s = (String) e.nextElement();
- System.out.println("parameter: " + s + " "
- + req.getParameter(s));
- }
- }
-
- try {
- fStore.begin(req.getUserPrincipal(), fParameter);
- fStore.checkAuthentication();
- resp.setStatus(WebdavStatus.SC_OK);
-
- try {
- if (method.equals(METHOD_PROPFIND)) {
- doPropfind(req, resp);
- } else if (method.equals(METHOD_PROPPATCH)) {
- doProppatch(req, resp);
- } else if (method.equals(METHOD_MKCOL)) {
- doMkcol(req, resp);
- } else if (method.equals(METHOD_COPY)) {
- doCopy(req, resp);
- } else if (method.equals(METHOD_MOVE)) {
- doMove(req, resp);
- } else if (method.equals(METHOD_PUT)) {
- doPut(req, resp);
- } else if (method.equals(METHOD_GET)) {
- doGet(req, resp, true);
- } else if (method.equals(METHOD_OPTIONS)) {
- doOptions(req, resp);
- } else if (method.equals(METHOD_HEAD)) {
- doHead(req, resp);
- } else if (method.equals(METHOD_DELETE)) {
- doDelete(req, resp);
- } else {
- super.service(req, resp);
- }
-
- fStore.commit();
- } catch (IOException e) {
- e.printStackTrace();
- resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
- fStore.rollback();
- throw new ServletException(e);
- }
-
- } catch (Exception e) {
- e.printStackTrace();
- throw new ServletException(e);
- } catch (Throwable t) {
- t.printStackTrace();
- }
-
- }
-
- // protected long getLastModified
-
- /**
- * goes recursive through all folders. used by propfind
- *
- */
- private void recursiveParseProperties(String currentPath,
- HttpServletRequest req,
- XMLWriter generatedXML, int propertyFindType, Vector properties,
- int depth) throws IOException {
-
- parseProperties(req, generatedXML, currentPath,
- propertyFindType, properties);
- String[] names = fStore.getChildrenNames(currentPath);
- if ((names!=null) && (depth > 0)) {
-
- for (int i = 0; i < names.length; i++) {
- String name = names[i];
- String newPath = currentPath;
- if (!(newPath.endsWith("/"))) {
- newPath += "/";
- }
- newPath += name;
- recursiveParseProperties(newPath, req, generatedXML,
- propertyFindType, properties, depth - 1);
- }
- }
- }
-
- /**
- * overwrites propNode and type, parsed from xml input stream
- *
- * @param propNode
- * @param type
- * @param req
- * @throws ServletException
- */
- private void getPropertyNodeAndType(Node propNode, int type,
- ServletRequest req) throws ServletException {
- if (req.getContentLength() != 0) {
- DocumentBuilder documentBuilder = getDocumentBuilder();
- try {
- Document document = documentBuilder.parse(new InputSource(req
- .getInputStream()));
- // Get the root element of the document
- Element rootElement = document.getDocumentElement();
- NodeList childList = rootElement.getChildNodes();
-
- for (int i = 0; i < childList.getLength(); i++) {
- Node currentNode = childList.item(i);
- switch (currentNode.getNodeType()) {
- case Node.TEXT_NODE:
- break;
- case Node.ELEMENT_NODE:
- if (currentNode.getNodeName().endsWith("prop")) {
- type = FIND_BY_PROPERTY;
- propNode = currentNode;
- }
- if (currentNode.getNodeName().endsWith("propname")) {
- type = FIND_PROPERTY_NAMES;
- }
- if (currentNode.getNodeName().endsWith("allprop")) {
- type = FIND_ALL_PROP;
- }
- break;
- }
- }
- } catch (Exception e) {
-
- }
- } else {
- // no content, which means it is a allprop request
- type = FIND_ALL_PROP;
- }
- }
-
- private String getParentPath(String path) {
- int slash = path.lastIndexOf('/');
- if (slash != -1) {
- return path.substring(0, slash);
- }
- return null;
- }
-
- /**
- * Return JAXP document builder instance.
- */
- private DocumentBuilder getDocumentBuilder() throws ServletException {
- DocumentBuilder documentBuilder = null;
- DocumentBuilderFactory documentBuilderFactory = null;
- try {
- documentBuilderFactory = DocumentBuilderFactory.newInstance();
- documentBuilderFactory.setNamespaceAware(true);
- documentBuilder = documentBuilderFactory.newDocumentBuilder();
- } catch (ParserConfigurationException e) {
- throw new ServletException("jaxp failed");
- }
- return documentBuilder;
- }
-
- /**
- * Return the relative path associated with this servlet.
- *
- * @param request
- * The servlet request we are processing
- */
- protected String getRelativePath(HttpServletRequest request) {
-
- // Are we being processed by a RequestDispatcher.include()?
- if (request.getAttribute("javax.servlet.include.request_uri") != null) {
- String result = (String) request
- .getAttribute("javax.servlet.include.path_info");
- if (result == null)
- result = (String) request
- .getAttribute("javax.servlet.include.servlet_path");
- if ((result == null) || (result.equals("")))
- result = "/";
- return (result);
- }
-
- // No, extract the desired path directly from the request
- String result = request.getPathInfo();
- if (result == null) {
- result = request.getServletPath();
- }
- if ((result == null) || (result.equals(""))) {
- result = "/";
- }
- return (result);
-
- }
-
- private Vector getPropertiesFromXML(Node propNode) {
- Vector properties;
- properties = new Vector();
- NodeList childList = propNode.getChildNodes();
-
- for (int i = 0; i < childList.getLength(); i++) {
- Node currentNode = childList.item(i);
- switch (currentNode.getNodeType()) {
- case Node.TEXT_NODE:
- break;
- case Node.ELEMENT_NODE:
- String nodeName = currentNode.getNodeName();
- String propertyName = null;
- if (nodeName.indexOf(':') != -1) {
- propertyName = nodeName
- .substring(nodeName.indexOf(':') + 1);
- } else {
- propertyName = nodeName;
- }
- // href is a live property which is handled differently
- properties.addElement(propertyName);
- break;
- }
- }
- return properties;
- }
-
- /**
- * reads the depth header from the request and returns it as a int
- *
- * @param req
- * @return
- */
- private int getDepth(HttpServletRequest req) {
- int depth = INFINITY;
- String depthStr = req.getHeader("Depth");
- if (depthStr != null) {
- if (depthStr.equals("0")) {
- depth = 0;
- } else if (depthStr.equals("1")) {
- depth = 1;
- } else if (depthStr.equals("infinity")) {
- depth = INFINITY;
- }
- }
- return depth;
- }
-
- /**
- * removes a / at the end of the path string, if present
- *
- * @param path
- * @return the path without trailing /
- */
- private String getCleanPath(String path) {
-
- if (path.endsWith("/") && path.length() > 1)
- path = path.substring(0, path.length() - 1);
- return path;
- }
-
- /**
- * OPTIONS Method.</br>
- *
- *
- * @param req
- * HttpServletRequest
- * @param resp
- * HttpServletResponse
- * @param store
- * class that handles the actual storing
- * @throws ServletException
- * @throws IOException
- */
- protected void doOptions(HttpServletRequest req, HttpServletResponse resp
- ) throws ServletException, IOException {
-
- String lockOwner = "doOptions" + System.currentTimeMillis()
- + req.toString();
- String path = getRelativePath(req);
- if (fResLocks.lock(path, lockOwner, false, 0)) {
- try {
- resp.addHeader("DAV", "1, 2");
-
- String methodsAllowed = determineMethodsAllowed(path,fStore.objectExists(path),fStore.isFolder(path));
- resp.addHeader("Allow", methodsAllowed);
- resp.addHeader("MS-Author-Via", "DAV");
- } finally {
- fResLocks.unlock(path, lockOwner);
- }
- } else {
- resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
- }
- }
-
- /**
- * PROPFIND Method.
- *
- * @param req
- * HttpServletRequest
- * @param resp
- * HttpServletResponse
- * @param store
- * class that handles the actual storing
- * @throws ServletException
- * @throws IOException
- */
- protected void doPropfind(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
-
- // Retrieve the resources
- String lockOwner = "doPropfind" + System.currentTimeMillis()
- + req.toString();
- String path = getRelativePath(req);
- int depth = getDepth(req);
- if (fResLocks.lock(path, lockOwner, false, depth)) {
- try {
- if (!fStore.objectExists(path)) {
- resp
- .sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- return;
- // we do not to continue since there is no root
- // resource
- }
-
- Vector properties = null;
- path = getCleanPath(getRelativePath(req));
-
-
- int propertyFindType = FIND_ALL_PROP;
- Node propNode = null;
- getPropertyNodeAndType(propNode, propertyFindType, req);
-
- if (propertyFindType == FIND_BY_PROPERTY) {
- properties = getPropertiesFromXML(propNode);
- }
-
- resp.setStatus(WebdavStatus.SC_MULTI_STATUS);
- resp.setContentType("text/xml; charset=UTF-8");
-
- // Create multistatus object
- XMLWriter generatedXML = new XMLWriter(resp.getWriter());
- generatedXML.writeXMLHeader();
- generatedXML.writeElement(null, "multistatus"
- + generateNamespaceDeclarations(), XMLWriter.OPENING);
- if (depth == 0) {
- parseProperties(req, generatedXML, path,
- propertyFindType, properties);
- } else {
- recursiveParseProperties(path, req, generatedXML,
- propertyFindType, properties, depth);
- }
- generatedXML.writeElement(null, "multistatus",
- XMLWriter.CLOSING);
- generatedXML.sendData();
- } finally {
- fResLocks.unlock(path, lockOwner);
- }
- } else {
- resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
- }
- }
-
- /**
- * PROPPATCH Method.
- *
- * @param req
- * HttpServletRequest
- * @param resp
- * HttpServletResponse
- * @param store
- * class that handles the actual storing
- * @throws ServletException
- * @throws IOException
- */
- protected void doProppatch(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
-
- if (readOnly) {
- resp.sendError(WebdavStatus.SC_FORBIDDEN);
-
- } else
-
- resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
- // TODO implement proppatch
- }
-
- /**
- * GET Method
- *
- * @param req
- * HttpServletRequest
- * @param resp
- * HttpServletResponse
- * @param store
- * class that handles the actual storing
- * @throws ServletException
- * @throws IOException
- */
- protected void doGet(HttpServletRequest req, HttpServletResponse resp,
- boolean includeBody) throws ServletException,
- IOException {
-
- String lockOwner = "doGet" + System.currentTimeMillis()
- + req.toString();
- String path = getRelativePath(req);
- if (fResLocks.lock(path, lockOwner, false, 0)) {
- try {
-
- if (fStore.isResource(path)) {
- // path points to a file but ends with / or \
- if (path.endsWith("/") || (path.endsWith("\\"))) {
- resp.sendError(HttpServletResponse.SC_NOT_FOUND, req
- .getRequestURI());
- } else {
-
- // setting headers
- long lastModified = fStore.getLastModified(path)
- .getTime();
- resp.setDateHeader("last-modified", lastModified);
-
- long resourceLength = fStore.getResourceLength(path);
- if (resourceLength > 0) {
- if (resourceLength <= Integer.MAX_VALUE) {
- resp.setContentLength((int) resourceLength);
- } else {
- resp.setHeader("content-length", ""
- + resourceLength);
- // is "content-length" the right header? is long
- // a valid format?
- }
-
- }
-
-
- String mimeType = getServletContext().getMimeType(path);
- if (mimeType != null) {
- resp.setContentType(mimeType);
- }
-
- //resp.setHeader("ETag", getETag(path));
- // resp.setHeader
- // ("Content-Language", "en-us");
- // resp.setHeader("name","nameFromHeader");
- // resp.setHeader("parentname",getParentPath(path));
- // resp.setHeader("href","hrefFromHeader");
- // resp.setHeader("ishidden","f");
- // resp.setHeader("iscollection","f");
- // resp.setHeader("isreadonly","f");
- // resp.setHeader("getcontenttype","contenttypeFromHeader");
- // resp.setHeader("getcontentlanguage", "en-us");
- // resp.setHeader("contentclass","contentclassFromHeader");
- // resp.setDateHeader("creationdate",
- // store.getLastModified(
- // path).getTime());
- // resp.setDateHeader("getlastmodified",
- // store.getLastModified(
- // path).getTime());
- // resp.setDateHeader("lastaccessed",
- // store.getLastModified(
- // path).getTime());
- // resp.setHeader("getcontentlength",""+store.getResourceLength(path));
- // resp.setHeader("resourcetype","resourcetypeFromHeader");
- // resp.setHeader("isstructureddocument","f");
- // resp.setHeader("defaultdocument","f");
- // resp.setHeader("displayname","displaynameFromHeader");
- // resp.setHeader("isroot","f");
-
- if (includeBody) {
- OutputStream out = resp.getOutputStream();
- InputStream in = fStore.getResourceContent(path);
- try {
- int read = -1;
- byte[] copyBuffer = new byte[BUF_SIZE];
-
- while ((read = in.read(copyBuffer, 0,
- copyBuffer.length)) != -1) {
- out.write(copyBuffer, 0, read);
- }
-
- } finally {
-
- in.close();
- out.flush();
- out.close();
- }
- }
- }
- } else {
- if (includeBody && fStore.isFolder(path)) {
- // TODO some folder response (for browsers, DAV tools
- // use propfind) in html?
- OutputStream out = resp.getOutputStream();
- String[] children = fStore.getChildrenNames(path);
- StringBuffer childrenTemp = new StringBuffer();
- childrenTemp.append("Contents of this Folder:\n");
- for (int i = 0; i < children.length; i++) {
- childrenTemp.append(children[i]);
- childrenTemp.append("\n");
- }
- out.write(childrenTemp.toString().getBytes());
- } else {
- if (!fStore.objectExists(path)) {
- resp.sendError(HttpServletResponse.SC_NOT_FOUND,
- req.getRequestURI());
- }
-
- }
- }
- } finally {
- fResLocks.unlock(path, lockOwner);
- }
- } else {
- resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
- }
- }
-
- /**
- * HEAD Method.
- *
- * @param req
- * HttpServletRequest
- * @param resp
- * HttpServletResponse
- * @param store
- * class that handles the actual storing
- * @throws ServletException
- * @throws IOException
- */
- protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- doGet(req, resp, false);
- }
-
- /**
- * MKCOL Method.
- *
- * @param req
- * HttpServletRequest
- * @param resp
- * HttpServletResponse
- * @param store
- * class that handles the actual storing
- * @throws ServletException
- * @throws IOException
- */
- protected void doMkcol(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
-
- if (req.getContentLength() != 0) {
- resp.sendError(WebdavStatus.SC_NOT_IMPLEMENTED);
- } else {
-
- if (!readOnly) {
- // not readonly
- String path = getRelativePath(req);
- String parentPath = getParentPath(path);
- String lockOwner = "doMkcol" + System.currentTimeMillis()
- + req.toString();
- if (fResLocks.lock(path, lockOwner, true, 0)) {
- try {
-
- if (parentPath != null && fStore.isFolder(parentPath)) {
- if (!fStore.objectExists(path)) {
-
- fStore.createFolder(path);
-
- } else {
- // object already exists
- String methodsAllowed = determineMethodsAllowed(path,true,fStore.isFolder(path));
- resp.addHeader("Allow", methodsAllowed);
- resp
- .sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED);
- }
- } else {
- resp.sendError(WebdavStatus.SC_CONFLICT);
- }
- } finally {
- fResLocks.unlock(path, lockOwner);
- }
- } else {
- resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
- }
- } else {
- resp.sendError(WebdavStatus.SC_FORBIDDEN);
- }
- }
-
- }
-
- /**
- * DELETE Method.
- *
- * @param req
- * HttpServletRequest
- * @param resp
- * HttpServletResponse
- * @param store
- * class that handles the actual storing
- * @throws ServletException
- * @throws IOException
- */
- protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
-
- if (!readOnly) {
- String path = getRelativePath(req);
- String lockOwner = "doDelete" + System.currentTimeMillis()
- + req.toString();
- if (fResLocks.lock(path, lockOwner, true, -1)) {
- try {
- Hashtable errorList = new Hashtable();
- deleteResource(path, errorList, req, resp);
- if (!errorList.isEmpty()) {
- sendReport(req, resp, errorList);
- }
- } finally {
- fResLocks.unlock(path, lockOwner);
- }
- } else {
- resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
- }
- } else {
- resp.sendError(WebdavStatus.SC_FORBIDDEN);
- }
-
- }
-
- /**
- * Process a POST request for the specified resource.
- *
- * @param req
- * The servlet request we are processing
- * @param resp
- * The servlet response we are creating
- *
- * @exception IOException
- * if an input/output error occurs
- * @exception ServletException
- * if a servlet-specified error occurs
- */
- protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- if (!readOnly) {
- String path = getRelativePath(req);
- String parentPath = getParentPath(path);
- String lockOwner = "doPut" + System.currentTimeMillis()
- + req.toString();
- if (fResLocks.lock(path, lockOwner, true, -1)) {
- try {
- if (parentPath != null && fStore.isFolder(parentPath)
- && !fStore.isFolder(path)) {
- if (!fStore.objectExists(path)) {
- fStore.createResource(path);
- resp.setStatus(HttpServletResponse.SC_CREATED);
- } else {
- resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
- }
- fStore.setResourceContent(path, req.getInputStream(),
- null, null);
- resp.setContentLength((int) fStore
- .getResourceLength(path));
- } else {
- resp.sendError(WebdavStatus.SC_CONFLICT);
- }
-
- } finally {
- fResLocks.unlock(path, lockOwner);
- }
- } else {
- resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
- }
- } else {
- resp.sendError(WebdavStatus.SC_FORBIDDEN);
- }
-
- }
-
- /**
- * COPY Method.
- *
- * @param req
- * HttpServletRequest
- * @param resp
- * HttpServletResponse
- * @param store
- * class that handles the actual storing
- * @throws ServletException
- * @throws IOException
- */
- protected void doCopy(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
-
- String path = getRelativePath(req);
- if (!readOnly) {
- String lockOwner = "doCopy" + System.currentTimeMillis()
- + req.toString();
- if (fResLocks.lock(path, lockOwner, false, -1)) {
- try {
- copyResource(req, resp);
- } finally {
- fResLocks.unlock(path, lockOwner);
- }
- } else {
- resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
- }
-
- } else {
- resp.sendError(WebdavStatus.SC_FORBIDDEN);
- }
-
- }
-
- /**
- * MOVE Method.
- *
- * @param req
- * HttpServletRequest
- * @param resp
- * HttpServletResponse
- * @param store
- * class that handles the actual storing
- * @throws ServletException
- * @throws IOException
- */
- protected void doMove(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- if (!readOnly) {
-
- String path = getRelativePath(req);
- String lockOwner = "doMove" + System.currentTimeMillis()
- + req.toString();
- if (fResLocks.lock(path, lockOwner, false, -1)) {
- try {
- if (copyResource(req, resp)) {
-
- Hashtable errorList = new Hashtable();
- deleteResource(path, errorList, req, resp);
- if (!errorList.isEmpty()) {
- sendReport(req, resp, errorList);
- }
-
- } else {
- resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
- }
- } finally {
- fResLocks.unlock(path, lockOwner);
- }
- } else {
- resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
- }
- } else {
- resp.sendError(WebdavStatus.SC_FORBIDDEN);
-
- }
- }
-
- // -------------------------------------------------------- Private Methods
-
- /**
- * Generate the namespace declarations.
- */
- private String generateNamespaceDeclarations() {
- return " xmlns=\"" + DEFAULT_NAMESPACE + "\"";
- }
-
- /**
- * Copy a resource.
- *
- * @param req
- * Servlet request
- * @param resp
- * Servlet response
- * @return boolean true if the copy is successful
- */
- private boolean copyResource(HttpServletRequest req,
- HttpServletResponse resp)
- throws ServletException, IOException {
-
- // Parsing destination header
-
- String destinationPath = req.getHeader("Destination");
-
- if (destinationPath == null) {
- resp.sendError(WebdavStatus.SC_BAD_REQUEST);
- return false;
- }
-
- // Remove url encoding from destination
- destinationPath = RequestUtil.URLDecode(destinationPath, "UTF8");
-
- int protocolIndex = destinationPath.indexOf("://");
- if (protocolIndex >= 0) {
- // if the Destination URL contains the protocol, we can safely
- // trim everything upto the first "/" character after "://"
- int firstSeparator = destinationPath
- .indexOf("/", protocolIndex + 4);
- if (firstSeparator < 0) {
- destinationPath = "/";
- } else {
- destinationPath = destinationPath.substring(firstSeparator);
- }
- } else {
- String hostName = req.getServerName();
- if ((hostName != null) && (destinationPath.startsWith(hostName))) {
- destinationPath = destinationPath.substring(hostName.length());
- }
-
- int portIndex = destinationPath.indexOf(":");
- if (portIndex >= 0) {
- destinationPath = destinationPath.substring(portIndex);
- }
-
- if (destinationPath.startsWith(":")) {
- int firstSeparator = destinationPath.indexOf("/");
- if (firstSeparator < 0) {
- destinationPath = "/";
- } else {
- destinationPath = destinationPath.substring(firstSeparator);
- }
- }
- }
-
- // Normalise destination path (remove '.' and '..')
- destinationPath = normalize(destinationPath);
-
- String contextPath = req.getContextPath();
- if ((contextPath != null) && (destinationPath.startsWith(contextPath))) {
- destinationPath = destinationPath.substring(contextPath.length());
- }
-
- String pathInfo = req.getPathInfo();
- if (pathInfo != null) {
- String servletPath = req.getServletPath();
- if ((servletPath != null)
- && (destinationPath.startsWith(servletPath))) {
- destinationPath = destinationPath.substring(servletPath
- .length());
- }
- }
-
- String path = getRelativePath(req);
-
- // if source = destination
- if (path.equals(destinationPath)) {
- resp.sendError(HttpServletResponse.SC_FORBIDDEN);
- }
-
- // Parsing overwrite header
-
- boolean overwrite = true;
- String overwriteHeader = req.getHeader("Overwrite");
-
- if (overwriteHeader != null) {
- overwrite = overwriteHeader.equalsIgnoreCase("T");
- }
-
- // Overwriting the destination
- String lockOwner = "copyResource" + System.currentTimeMillis()
- + req.toString();
- if (fResLocks.lock(destinationPath, lockOwner, true, -1)) {
- try {
-
- // Retrieve the resources
- if (!fStore.objectExists(path)) {
- resp
- .sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- return false;
- }
-
- boolean exists = fStore.objectExists(destinationPath);
- Hashtable errorList = new Hashtable();
-
- if (overwrite) {
-
- // Delete destination resource, if it exists
- if (exists) {
- deleteResource(destinationPath, errorList, req, resp);
-
- } else {
- resp.setStatus(WebdavStatus.SC_CREATED);
- }
- } else {
-
- // If the destination exists, then it's a conflict
- if (exists) {
- resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED);
- return false;
- } else {
- resp.setStatus(WebdavStatus.SC_CREATED);
- }
-
- }
- copy(path, destinationPath, errorList, req, resp);
- if (!errorList.isEmpty()) {
- sendReport(req, resp, errorList);
- }
-
- } finally {
- fResLocks.unlock(destinationPath, lockOwner);
- }
- } else {
- resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
- return false;
- }
- return true;
-
- }
-
- /**
- * copies the specified resource(s) to the specified destination.
- * preconditions must be handled by the caller. Standard status codes must
- * be handled by the caller. a multi status report in case of errors is
- * created here.
- *
- * @param sourcePath
- * path from where to read
- * @param destinationPath
- * path where to write
- * @param req
- * HttpServletRequest
- * @param resp
- * HttpServletResponse
- * @param store
- * class that handles the actual storing
- * @throws IOException
- * if an error in the underlying store occurs
- * @throws ServletException
- */
- private void copy(String sourcePath, String destinationPath,
- Hashtable errorList, HttpServletRequest req,
- HttpServletResponse resp) throws IOException,
- ServletException {
-
- if (fStore.isResource(sourcePath)) {
- fStore.createResource(destinationPath);
- fStore.setResourceContent(destinationPath, fStore
- .getResourceContent(sourcePath), null, null);
- } else {
-
- if (fStore.isFolder(sourcePath)) {
- copyFolder(sourcePath, destinationPath, errorList, req, resp);
- } else {
- resp.sendError(WebdavStatus.SC_NOT_FOUND);
- }
- }
- }
-
- /**
- * helper method of copy() recursively copies the FOLDER at source path to
- * destination path
- *
- * @param sourcePath
- * @param destinationPath
- * @param errorList
- * @param req
- * @param resp
- * @param store
- * @throws IOException
- * @throws ServletException
- */
- private void copyFolder(String sourcePath, String destinationPath,
- Hashtable errorList, HttpServletRequest req,
- HttpServletResponse resp) throws IOException,
- ServletException {
-
- fStore.createFolder(destinationPath);
- boolean infiniteDepth = true;
- if (req.getHeader("depth") != null) {
- if (req.getHeader("depth").equals("0")) {
- infiniteDepth = false;
- }
- }
- if (infiniteDepth) {
- String[] children = fStore.getChildrenNames(sourcePath);
-
- for (int i = children.length - 1; i >= 0; i--) {
- children[i] = "/" + children[i];
- try {
- if (fStore.isResource(sourcePath + children[i])) {
- fStore.createResource(destinationPath + children[i]);
- fStore.setResourceContent(destinationPath + children[i],
- fStore.getResourceContent(sourcePath
- + children[i]), null, null);
-
- } else {
- copyFolder(sourcePath + children[i], destinationPath
- + children[i], errorList, req, resp);
- }
- } catch (IOException e) {
- errorList.put(destinationPath + children[i], new Integer(
- WebdavStatus.SC_INTERNAL_SERVER_ERROR));
- }
- }
- }
- }
-
- /**
- * deletes the recources at "path"
- *
- * @param path
- * @param errorList
- * @param req
- * @param resp
- * @param store
- * @throws IOException
- * @throws ServletException
- */
- private void deleteResource(String path, Hashtable errorList,
- HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
- resp.setStatus(WebdavStatus.SC_NO_CONTENT);
- if (!readOnly) {
-
- if (fStore.isResource(path)) {
- fStore.removeObject(path);
- } else {
- if (fStore.isFolder(path)) {
-
- deleteFolder(path, errorList, req, resp);
- fStore.removeObject(path);
- } else {
- resp.sendError(WebdavStatus.SC_NOT_FOUND);
- }
- }
-
- } else {
- resp.sendError(WebdavStatus.SC_FORBIDDEN);
- }
- }
-
- /**
- *
- * helper method of deleteResource() deletes the folder and all of its
- * contents
- *
- * @param path
- * the folder to be deleted
- * @param req
- * HttpServletRequest
- * @param resp
- * HttpServletResponse
- * @param store
- * class that handles the actual storing
- * @return
- * @throws IOException
- * @throws ServletException
- */
- private void deleteFolder(String path, Hashtable errorList,
- HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
-
- String[] children = fStore.getChildrenNames(path);
- for (int i = children.length - 1; i >= 0; i--) {
- children[i] = "/" + children[i];
- try {
- if (fStore.isResource(path + children[i])) {
- fStore.removeObject(path + children[i]);
-
- } else {
- deleteFolder(path + children[i], errorList, req, resp);
-
- fStore.removeObject(path + children[i]);
-
- }
- } catch (IOException e) {
- errorList.put(path + children[i], new Integer(
- WebdavStatus.SC_INTERNAL_SERVER_ERROR));
- }
- }
-
- }
-
- /**
- * Return a context-relative path, beginning with a "/", that represents the
- * canonical version of the specified path after ".." and "." elements are
- * resolved out. If the specified path attempts to go outside the boundaries
- * of the current context (i.e. too many ".." path elements are present),
- * return <code>null</code> instead.
- *
- * @param path
- * Path to be normalized
- */
- protected String normalize(String path) {
-
- if (path == null)
- return null;
-
- // Create a place for the normalized path
- String normalized = path;
-
- // if (normalized == null)
- // return (null);
-
- if (normalized.equals("/."))
- return "/";
-
- // Normalize the slashes and add leading slash if necessary
- if (normalized.indexOf('\\') >= 0)
- normalized = normalized.replace('\\', '/');
- if (!normalized.startsWith("/"))
- normalized = "/" + normalized;
-
- // Resolve occurrences of "//" in the normalized path
- while (true) {
- int index = normalized.indexOf("//");
- if (index < 0)
- break;
- normalized = normalized.substring(0, index)
- + normalized.substring(index + 1);
- }
-
- // Resolve occurrences of "/./" in the normalized path
- while (true) {
- int index = normalized.indexOf("/./");
- if (index < 0)
- break;
- normalized = normalized.substring(0, index)
- + normalized.substring(index + 2);
- }
-
- // Resolve occurrences of "/../" in the normalized path
- while (true) {
- int index = normalized.indexOf("/../");
- if (index < 0)
- break;
- if (index == 0)
- return (null); // Trying to go outside our context
- int index2 = normalized.lastIndexOf('/', index - 1);
- normalized = normalized.substring(0, index2)
- + normalized.substring(index + 3);
- }
-
- // Return the normalized path that we have completed
- return (normalized);
-
- }
-
- /**
- * Send a multistatus element containing a complete error report to the
- * client.
- *
- * @param req
- * Servlet request
- * @param resp
- * Servlet response
- * @param errorList
- * List of error to be displayed
- */
- private void sendReport(HttpServletRequest req, HttpServletResponse resp,
- Hashtable errorList) throws ServletException, IOException {
-
- resp.setStatus(WebdavStatus.SC_MULTI_STATUS);
-
- String absoluteUri = req.getRequestURI();
- String relativePath = getRelativePath(req);
-
- XMLWriter generatedXML = new XMLWriter();
- generatedXML.writeXMLHeader();
-
- generatedXML.writeElement(null, "multistatus"
- + generateNamespaceDeclarations(), XMLWriter.OPENING);
-
- Enumeration pathList = errorList.keys();
- while (pathList.hasMoreElements()) {
-
- String errorPath = (String) pathList.nextElement();
- int errorCode = ((Integer) errorList.get(errorPath)).intValue();
-
- generatedXML.writeElement(null, "response", XMLWriter.OPENING);
-
- generatedXML.writeElement(null, "href", XMLWriter.OPENING);
- String toAppend = errorPath.substring(relativePath.length());
- if (!toAppend.startsWith("/"))
- toAppend = "/" + toAppend;
- generatedXML.writeText(absoluteUri + toAppend);
- generatedXML.writeElement(null, "href", XMLWriter.CLOSING);
- generatedXML.writeElement(null, "status", XMLWriter.OPENING);
- generatedXML.writeText("HTTP/1.1 " + errorCode + " "
- + WebdavStatus.getStatusText(errorCode));
- generatedXML.writeElement(null, "status", XMLWriter.CLOSING);
-
- generatedXML.writeElement(null, "response", XMLWriter.CLOSING);
-
- }
-
- generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING);
-
- Writer writer = resp.getWriter();
- writer.write(generatedXML.toString());
- writer.close();
-
- }
-
- /**
- * Propfind helper method.
- *
- * @param req
- * The servlet request
- * @param resources
- * Resources object associated with this context
- * @param generatedXML
- * XML response to the Propfind request
- * @param path
- * Path of the current resource
- * @param type
- * Propfind type
- * @param propertiesVector
- * If the propfind type is find properties by name, then this
- * Vector contains those properties
- */
- private void parseProperties(HttpServletRequest req,
- XMLWriter generatedXML, String path, int type,
- Vector propertiesVector) throws IOException {
-
- String creationdate = getISOCreationDate(fStore.getCreationDate(path)
- .getTime());
- boolean isFolder = fStore.isFolder(path);
- String lastModified = fStore.getLastModified(path).toString();
- String resourceLength = String.valueOf(fStore.getResourceLength(path));
-
- // ResourceInfo resourceInfo = new ResourceInfo(path, resources);
-
- generatedXML.writeElement(null, "response", XMLWriter.OPENING);
- String status = new String("HTTP/1.1 " + WebdavStatus.SC_OK + " "
- + WebdavStatus.getStatusText(WebdavStatus.SC_OK));
-
- // Generating href element
- generatedXML.writeElement(null, "href", XMLWriter.OPENING);
-
- String href = req.getContextPath();
- if ((href.endsWith("/")) && (path.startsWith("/")))
- href += path.substring(1);
- else
- href += path;
- if ((isFolder) && (!href.endsWith("/")))
- href += "/";
-
- generatedXML.writeText(rewriteUrl(href));
-
- generatedXML.writeElement(null, "href", XMLWriter.CLOSING);
-
- String resourceName = path;
- int lastSlash = path.lastIndexOf('/');
- if (lastSlash != -1)
- resourceName = resourceName.substring(lastSlash + 1);
-
- switch (type) {
-
- case FIND_ALL_PROP:
-
- generatedXML.writeElement(null, "propstat", XMLWriter.OPENING);
- generatedXML.writeElement(null, "prop", XMLWriter.OPENING);
-
- generatedXML.writeProperty(null, "creationdate", creationdate);
- generatedXML.writeElement(null, "displayname", XMLWriter.OPENING);
- generatedXML.writeData(resourceName);
- generatedXML.writeElement(null, "displayname", XMLWriter.CLOSING);
- if (!isFolder) {
- generatedXML.writeProperty(null, "getlastmodified",
- lastModified);
- generatedXML.writeProperty(null, "getcontentlength",
- resourceLength);
- String contentType = getServletContext().getMimeType(path);
- if (contentType != null) {
- generatedXML.writeProperty(null, "getcontenttype",
- contentType);
- }
- generatedXML.writeProperty(null, "getetag",
- getETag(path,resourceLength,lastModified));
- generatedXML.writeElement(null, "resourcetype",
- XMLWriter.NO_CONTENT);
- } else {
- generatedXML.writeElement(null, "resourcetype",
- XMLWriter.OPENING);
- generatedXML.writeElement(null, "collection",
- XMLWriter.NO_CONTENT);
- generatedXML.writeElement(null, "resourcetype",
- XMLWriter.CLOSING);
- }
-
- generatedXML.writeProperty(null, "source", "");
-
- // String supportedLocks = "<lockentry>"
- // + "<lockscope><exclusive/></lockscope>"
- // + "<locktype><write/></locktype>" + "</lockentry>"
- // + "<lockentry>" + "<lockscope><shared/></lockscope>"
- // + "<locktype><write/></locktype>" + "</lockentry>";
- // generatedXML.writeElement(null, "supportedlock",
- // XMLWriter.OPENING);
- // generatedXML.writeText(supportedLocks);
- // generatedXML.writeElement(null, "supportedlock",
- // XMLWriter.CLOSING);
- //
- // generateLockDiscovery(path, generatedXML);
-
- generatedXML.writeElement(null, "prop", XMLWriter.CLOSING);
- generatedXML.writeElement(null, "status", XMLWriter.OPENING);
- generatedXML.writeText(status);
- generatedXML.writeElement(null, "status", XMLWriter.CLOSING);
- generatedXML.writeElement(null, "propstat", XMLWriter.CLOSING);
-
- break;
-
- case FIND_PROPERTY_NAMES:
-
- generatedXML.writeElement(null, "propstat", XMLWriter.OPENING);
- generatedXML.writeElement(null, "prop", XMLWriter.OPENING);
-
- generatedXML.writeElement(null, "creationdate",
- XMLWriter.NO_CONTENT);
- generatedXML
- .writeElement(null, "displayname", XMLWriter.NO_CONTENT);
- if (!isFolder) {
- generatedXML.writeElement(null, "getcontentlanguage",
- XMLWriter.NO_CONTENT);
- generatedXML.writeElement(null, "getcontentlength",
- XMLWriter.NO_CONTENT);
- generatedXML.writeElement(null, "getcontenttype",
- XMLWriter.NO_CONTENT);
- generatedXML
- .writeElement(null, "getetag", XMLWriter.NO_CONTENT);
- generatedXML.writeElement(null, "getlastmodified",
- XMLWriter.NO_CONTENT);
- }
- generatedXML.writeElement(null, "resourcetype",
- XMLWriter.NO_CONTENT);
- generatedXML.writeElement(null, "source", XMLWriter.NO_CONTENT);
- generatedXML.writeElement(null, "lockdiscovery",
- XMLWriter.NO_CONTENT);
-
- generatedXML.writeElement(null, "prop", XMLWriter.CLOSING);
- generatedXML.writeElement(null, "status", XMLWriter.OPENING);
- generatedXML.writeText(status);
- generatedXML.writeElement(null, "status", XMLWriter.CLOSING);
- generatedXML.writeElement(null, "propstat", XMLWriter.CLOSING);
-
- break;
-
- case FIND_BY_PROPERTY:
-
- Vector propertiesNotFound = new Vector();
-
- // Parse the list of properties
-
- generatedXML.writeElement(null, "propstat", XMLWriter.OPENING);
- generatedXML.writeElement(null, "prop", XMLWriter.OPENING);
-
- Enumeration properties = propertiesVector.elements();
-
- while (properties.hasMoreElements()) {
-
- String property = (String) properties.nextElement();
-
- if (property.equals("creationdate")) {
- generatedXML.writeProperty(null, "creationdate",
- creationdate);
- } else if (property.equals("displayname")) {
- generatedXML.writeElement(null, "displayname",
- XMLWriter.OPENING);
- generatedXML.writeData(resourceName);
- generatedXML.writeElement(null, "displayname",
- XMLWriter.CLOSING);
- } else if (property.equals("getcontentlanguage")) {
- if (isFolder) {
- propertiesNotFound.addElement(property);
- } else {
- generatedXML.writeElement(null, "getcontentlanguage",
- XMLWriter.NO_CONTENT);
- }
- } else if (property.equals("getcontentlength")) {
- if (isFolder) {
- propertiesNotFound.addElement(property);
- } else {
- generatedXML.writeProperty(null, "getcontentlength",
- resourceLength);
- }
- } else if (property.equals("getcontenttype")) {
- if (isFolder) {
- propertiesNotFound.addElement(property);
- } else {
- generatedXML.writeProperty(null, "getcontenttype",
- getServletContext().getMimeType(path));
- }
- } else if (property.equals("getetag")) {
- if (isFolder) {
- propertiesNotFound.addElement(property);
- } else {
- generatedXML.writeProperty(null, "getetag", getETag(
- path,resourceLength,lastModified));
- }
- } else if (property.equals("getlastmodified")) {
- if (isFolder) {
- propertiesNotFound.addElement(property);
- } else {
- generatedXML.writeProperty(null, "getlastmodified",
- lastModified);
- }
- } else if (property.equals("resourcetype")) {
- if (isFolder) {
- generatedXML.writeElement(null, "resourcetype",
- XMLWriter.OPENING);
- generatedXML.writeElement(null, "collection",
- XMLWriter.NO_CONTENT);
- generatedXML.writeElement(null, "resourcetype",
- XMLWriter.CLOSING);
- } else {
- generatedXML.writeElement(null, "resourcetype",
- XMLWriter.NO_CONTENT);
- }
- } else if (property.equals("source")) {
- generatedXML.writeProperty(null, "source", "");
- // } else if (property.equals("supportedlock")) {
- // supportedLocks = "<lockentry>"
- // + "<lockscope><exclusive/></lockscope>"
- // + "<locktype><write/></locktype>" + "</lockentry>"
- // + "<lockentry>"
- // + "<lockscope><shared/></lockscope>"
- // + "<locktype><write/></locktype>" + "</lockentry>";
- // generatedXML.writeElement(null, "supportedlock",
- // XMLWriter.OPENING);
- // generatedXML.writeText(supportedLocks);
- // generatedXML.writeElement(null, "supportedlock",
- // XMLWriter.CLOSING);
- // } else if (property.equals("lockdiscovery")) {
- // if (!generateLockDiscovery(path, generatedXML))
- // propertiesNotFound.addElement(property);
- } else {
- propertiesNotFound.addElement(property);
- }
-
- }
-
- generatedXML.writeElement(null, "prop", XMLWriter.CLOSING);
- generatedXML.writeElement(null, "status", XMLWriter.OPENING);
- generatedXML.writeText(status);
- generatedXML.writeElement(null, "status", XMLWriter.CLOSING);
- generatedXML.writeElement(null, "propstat", XMLWriter.CLOSING);
-
- Enumeration propertiesNotFoundList = propertiesNotFound.elements();
-
- if (propertiesNotFoundList.hasMoreElements()) {
-
- status = new String("HTTP/1.1 " + WebdavStatus.SC_NOT_FOUND
- + " "
- + WebdavStatus.getStatusText(WebdavStatus.SC_NOT_FOUND));
-
- generatedXML.writeElement(null, "propstat", XMLWriter.OPENING);
- generatedXML.writeElement(null, "prop", XMLWriter.OPENING);
-
- while (propertiesNotFoundList.hasMoreElements()) {
- generatedXML.writeElement(null,
- (String) propertiesNotFoundList.nextElement(),
- XMLWriter.NO_CONTENT);
- }
-
- generatedXML.writeElement(null, "prop", XMLWriter.CLOSING);
- generatedXML.writeElement(null, "status", XMLWriter.OPENING);
- generatedXML.writeText(status);
- generatedXML.writeElement(null, "status", XMLWriter.CLOSING);
- generatedXML.writeElement(null, "propstat", XMLWriter.CLOSING);
-
- }
-
- break;
-
- }
-
- generatedXML.writeElement(null, "response", XMLWriter.CLOSING);
-
- }
-
- /**
- * Get the ETag associated with a file.
- *
- * @param resourceInfo
- * File object
- */
- protected String getETag(String path, String resourceLength, String lastModified)
- throws IOException {
- // if (resourceInfo.strongETag != null) {
- // return resourceInfo.strongETag;
- // } else if (resourceInfo.weakETag != null) {
- // return resourceInfo.weakETag;
- // } else {
- return "W/\"" + resourceLength + "-"
- + lastModified + "\"";
- // }
- }
-
- /**
- * URL rewriter.
- *
- * @param path
- * Path which has to be rewiten
- */
- protected String rewriteUrl(String path) {
- return urlEncoder.encode(path);
- }
-
- /**
- * Get creation date in ISO format.
- */
- private String getISOCreationDate(long creationDate) {
- StringBuffer creationDateValue = new StringBuffer(creationDateFormat
- .format(new Date(creationDate)));
- /*
- * int offset = Calendar.getInstance().getTimeZone().getRawOffset() /
- * 3600000; // FIXME ? if (offset < 0) { creationDateValue.append("-");
- * offset = -offset; } else if (offset > 0) {
- * creationDateValue.append("+"); } if (offset != 0) { if (offset < 10)
- * creationDateValue.append("0"); creationDateValue.append(offset +
- * ":00"); } else { creationDateValue.append("Z"); }
- */
- return creationDateValue.toString();
- }
-
- /**
- * Determines the methods normally allowed for the resource.
- *
- */
- private String determineMethodsAllowed(String uri, boolean exists, boolean isFolder) {
- StringBuffer methodsAllowed = new StringBuffer();
- try {
- if (exists) {
- methodsAllowed
- .append("OPTIONS, GET, HEAD, POST, DELETE, TRACE");
- methodsAllowed
- .append(", PROPPATCH, COPY, MOVE, LOCK, UNLOCK, PROPFIND");
- if (isFolder) {
- methodsAllowed.append(", PUT");
- }
- return methodsAllowed.toString();
- }
- } catch (Exception e) {
- // we do nothing, just return less allowed methods
-
- }
- methodsAllowed.append("OPTIONS, MKCOL, PUT, LOCK");
- return methodsAllowed.toString();
-
- }
-
-};
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/WebdavStatus.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/WebdavStatus.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/WebdavStatus.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,273 @@
+package net.sf.webdav;
+
+import java.util.Hashtable;
+
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ * Wraps the HttpServletResponse class to abstract the specific protocol used.
+ * To support other protocols we would only need to modify this class and the
+ * WebDavRetCode classes.
+ *
+ * @author Marc Eaddy
+ * @version 1.0, 16 Nov 1997
+ */
+public class WebdavStatus {
+
+ // ----------------------------------------------------- Instance Variables
+
+ /**
+ * This Hashtable contains the mapping of HTTP and WebDAV status codes to
+ * descriptive text. This is a static variable.
+ */
+ private static Hashtable mapStatusCodes = new Hashtable();
+
+ // ------------------------------------------------------ HTTP Status Codes
+
+ /**
+ * Status code (200) indicating the request succeeded normally.
+ */
+ public static final int SC_OK = HttpServletResponse.SC_OK;
+
+ /**
+ * Status code (201) indicating the request succeeded and created a new
+ * resource on the server.
+ */
+ public static final int SC_CREATED = HttpServletResponse.SC_CREATED;
+
+ /**
+ * Status code (202) indicating that a request was accepted for processing,
+ * but was not completed.
+ */
+ public static final int SC_ACCEPTED = HttpServletResponse.SC_ACCEPTED;
+
+ /**
+ * Status code (204) indicating that the request succeeded but that there
+ * was no new information to return.
+ */
+ public static final int SC_NO_CONTENT = HttpServletResponse.SC_NO_CONTENT;
+
+ /**
+ * Status code (301) indicating that the resource has permanently moved to a
+ * new location, and that future references should use a new URI with their
+ * requests.
+ */
+ public static final int SC_MOVED_PERMANENTLY = HttpServletResponse.SC_MOVED_PERMANENTLY;
+
+ /**
+ * Status code (302) indicating that the resource has temporarily moved to
+ * another location, but that future references should still use the
+ * original URI to access the resource.
+ */
+ public static final int SC_MOVED_TEMPORARILY = HttpServletResponse.SC_MOVED_TEMPORARILY;
+
+ /**
+ * Status code (304) indicating that a conditional GET operation found that
+ * the resource was available and not modified.
+ */
+ public static final int SC_NOT_MODIFIED = HttpServletResponse.SC_NOT_MODIFIED;
+
+ /**
+ * Status code (400) indicating the request sent by the client was
+ * syntactically incorrect.
+ */
+ public static final int SC_BAD_REQUEST = HttpServletResponse.SC_BAD_REQUEST;
+
+ /**
+ * Status code (401) indicating that the request requires HTTP
+ * authentication.
+ */
+ public static final int SC_UNAUTHORIZED = HttpServletResponse.SC_UNAUTHORIZED;
+
+ /**
+ * Status code (403) indicating the server understood the request but
+ * refused to fulfill it.
+ */
+ public static final int SC_FORBIDDEN = HttpServletResponse.SC_FORBIDDEN;
+
+ /**
+ * Status code (404) indicating that the requested resource is not
+ * available.
+ */
+ public static final int SC_NOT_FOUND = HttpServletResponse.SC_NOT_FOUND;
+
+ /**
+ * Status code (500) indicating an error inside the HTTP service which
+ * prevented it from fulfilling the request.
+ */
+ public static final int SC_INTERNAL_SERVER_ERROR = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
+
+ /**
+ * Status code (501) indicating the HTTP service does not support the
+ * functionality needed to fulfill the request.
+ */
+ public static final int SC_NOT_IMPLEMENTED = HttpServletResponse.SC_NOT_IMPLEMENTED;
+
+ /**
+ * Status code (502) indicating that the HTTP server received an invalid
+ * response from a server it consulted when acting as a proxy or gateway.
+ */
+ public static final int SC_BAD_GATEWAY = HttpServletResponse.SC_BAD_GATEWAY;
+
+ /**
+ * Status code (503) indicating that the HTTP service is temporarily
+ * overloaded, and unable to handle the request.
+ */
+ public static final int SC_SERVICE_UNAVAILABLE = HttpServletResponse.SC_SERVICE_UNAVAILABLE;
+
+ /**
+ * Status code (100) indicating the client may continue with its request.
+ * This interim response is used to inform the client that the initial part
+ * of the request has been received and has not yet been rejected by the
+ * server.
+ */
+ public static final int SC_CONTINUE = 100;
+
+ /**
+ * Status code (405) indicating the method specified is not allowed for the
+ * resource.
+ */
+ public static final int SC_METHOD_NOT_ALLOWED = 405;
+
+ /**
+ * Status code (409) indicating that the request could not be completed due
+ * to a conflict with the current state of the resource.
+ */
+ public static final int SC_CONFLICT = 409;
+
+ /**
+ * Status code (412) indicating the precondition given in one or more of the
+ * request-header fields evaluated to false when it was tested on the
+ * server.
+ */
+ public static final int SC_PRECONDITION_FAILED = 412;
+
+ /**
+ * Status code (413) indicating the server is refusing to process a request
+ * because the request entity is larger than the server is willing or able
+ * to process.
+ */
+ public static final int SC_REQUEST_TOO_LONG = 413;
+
+ /**
+ * Status code (415) indicating the server is refusing to service the
+ * request because the entity of the request is in a format not supported by
+ * the requested resource for the requested method.
+ */
+ public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415;
+
+ // -------------------------------------------- Extended WebDav status code
+
+ /**
+ * Status code (207) indicating that the response requires providing status
+ * for multiple independent operations.
+ */
+ public static final int SC_MULTI_STATUS = 207;
+
+ // This one colides with HTTP 1.1
+ // "207 Parital Update OK"
+
+ /**
+ * Status code (418) indicating the entity body submitted with the PATCH
+ * method was not understood by the resource.
+ */
+ public static final int SC_UNPROCESSABLE_ENTITY = 418;
+
+ // This one colides with HTTP 1.1
+ // "418 Reauthentication Required"
+
+ /**
+ * Status code (419) indicating that the resource does not have sufficient
+ * space to record the state of the resource after the execution of this
+ * method.
+ */
+ public static final int SC_INSUFFICIENT_SPACE_ON_RESOURCE = 419;
+
+ // This one colides with HTTP 1.1
+ // "419 Proxy Reauthentication Required"
+
+ /**
+ * Status code (420) indicating the method was not executed on a particular
+ * resource within its scope because some part of the method's execution
+ * failed causing the entire method to be aborted.
+ */
+ public static final int SC_METHOD_FAILURE = 420;
+
+ /**
+ * Status code (423) indicating the destination resource of a method is
+ * locked, and either the request did not contain a valid Lock-Info header,
+ * or the Lock-Info header identifies a lock held by another principal.
+ */
+ public static final int SC_LOCKED = 423;
+
+ // ------------------------------------------------------------ Initializer
+
+ static {
+ // HTTP 1.0 Status Code
+ addStatusCodeMap(SC_OK, "OK");
+ addStatusCodeMap(SC_CREATED, "Created");
+ addStatusCodeMap(SC_ACCEPTED, "Accepted");
+ addStatusCodeMap(SC_NO_CONTENT, "No Content");
+ addStatusCodeMap(SC_MOVED_PERMANENTLY, "Moved Permanently");
+ addStatusCodeMap(SC_MOVED_TEMPORARILY, "Moved Temporarily");
+ addStatusCodeMap(SC_NOT_MODIFIED, "Not Modified");
+ addStatusCodeMap(SC_BAD_REQUEST, "Bad Request");
+ addStatusCodeMap(SC_UNAUTHORIZED, "Unauthorized");
+ addStatusCodeMap(SC_FORBIDDEN, "Forbidden");
+ addStatusCodeMap(SC_NOT_FOUND, "Not Found");
+ addStatusCodeMap(SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
+ addStatusCodeMap(SC_NOT_IMPLEMENTED, "Not Implemented");
+ addStatusCodeMap(SC_BAD_GATEWAY, "Bad Gateway");
+ addStatusCodeMap(SC_SERVICE_UNAVAILABLE, "Service Unavailable");
+ addStatusCodeMap(SC_CONTINUE, "Continue");
+ addStatusCodeMap(SC_METHOD_NOT_ALLOWED, "Method Not Allowed");
+ addStatusCodeMap(SC_CONFLICT, "Conflict");
+ addStatusCodeMap(SC_PRECONDITION_FAILED, "Precondition Failed");
+ addStatusCodeMap(SC_REQUEST_TOO_LONG, "Request Too Long");
+ addStatusCodeMap(SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported Media Type");
+ // WebDav Status Codes
+ addStatusCodeMap(SC_MULTI_STATUS, "Multi-Status");
+ addStatusCodeMap(SC_UNPROCESSABLE_ENTITY, "Unprocessable Entity");
+ addStatusCodeMap(SC_INSUFFICIENT_SPACE_ON_RESOURCE,
+ "Insufficient Space On Resource");
+ addStatusCodeMap(SC_METHOD_FAILURE, "Method Failure");
+ addStatusCodeMap(SC_LOCKED, "Locked");
+ }
+
+ // --------------------------------------------------------- Public Methods
+
+ /**
+ * Returns the HTTP status text for the HTTP or WebDav status code specified
+ * by looking it up in the static mapping. This is a static function.
+ *
+ * @param nHttpStatusCode
+ * [IN] HTTP or WebDAV status code
+ * @return A string with a short descriptive phrase for the HTTP status code
+ * (e.g., "OK").
+ */
+ public static String getStatusText(int nHttpStatusCode) {
+ Integer intKey = new Integer(nHttpStatusCode);
+
+ if (!mapStatusCodes.containsKey(intKey)) {
+ return "";
+ } else {
+ return (String) mapStatusCodes.get(intKey);
+ }
+ }
+
+ // -------------------------------------------------------- Private Methods
+
+ /**
+ * Adds a new status code -> status text mapping. This is a static method
+ * because the mapping is a static variable.
+ *
+ * @param nKey
+ * [IN] HTTP or WebDAV status code
+ * @param strVal
+ * [IN] HTTP status text
+ */
+ private static void addStatusCodeMap(int nKey, String strVal) {
+ mapStatusCodes.put(new Integer(nKey), strVal);
+ }
+
+};
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/WebdavStatus.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/WebdavStore.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/WebdavStore.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/WebdavStore.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,237 @@
+/*
+ * $Header: /home/ak/dev/webdav-servlet/webdav-servlet/src/main/java/net/sf/webdav/WebdavStore.java,v 1.2 2007-01-07 00:02:22 paul-h Exp $
+ * $Revision: 1.2 $
+ * $Date: 2007-01-07 00:02:22 $
+ *
+ * ====================================================================
+ *
+ * Copyright 2004 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package net.sf.webdav;
+
+import net.sf.webdav.exceptions.WebdavException;
+
+import java.io.InputStream;
+import java.security.Principal;
+import java.util.Date;
+
+/**
+ * Interface for simple implementation of any store for the WebdavServlet
+ * <p>
+ * based on the BasicWebdavStore from Oliver Zeigermann, that was part of the
+ * Webdav Construcktion Kit from slide
+ *
+ */
+public interface WebdavStore {
+
+ /**
+ * Indicates that a new request or transaction with this store involved has
+ * been started. The request will be terminated by either {@link #commit()}
+ * or {@link #rollback()}. If only non-read methods have been called, the
+ * request will be terminated by a {@link #commit()}. This method will be
+ * called by (@link WebdavStoreAdapter} at the beginning of each request.
+ *
+ *
+ * @param principal
+ * the principal that started this request or
+ * <code>null</code> if there is non available
+ *
+ * @throws WebdavException
+ */
+ void begin(Principal principal);
+
+ /**
+ * Checks if authentication information passed in is valid. If not throws an
+ * exception.
+ *
+ */
+ void checkAuthentication();
+
+ /**
+ * Indicates that all changes done inside this request shall be made
+ * permanent and any transactions, connections and other temporary resources
+ * shall be terminated.
+ *
+ * @throws WebdavException
+ * if something goes wrong on the store level
+ */
+ void commit();
+
+ /**
+ * Indicates that all changes done inside this request shall be undone and
+ * any transactions, connections and other temporary resources shall be
+ * terminated.
+ *
+ * @throws WebdavException
+ * if something goes wrong on the store level
+ */
+ void rollback();
+
+ /**
+ * Checks if there is an object at the position specified by
+ * <code>uri</code>.
+ *
+ * @param uri
+ * URI of the object to check
+ * @return <code>true</code> if the object at <code>uri</code> exists
+ * @throws WebdavException
+ * if something goes wrong on the store level
+ */
+ boolean objectExists(String uri);
+
+ /**
+ * Checks if there is an object at the position specified by
+ * <code>uri</code> and if so if it is a folder.
+ *
+ * @param uri
+ * URI of the object to check
+ * @return <code>true</code> if the object at <code>uri</code> exists
+ * and is a folder
+ * @throws WebdavException
+ * if something goes wrong on the store level
+ */
+ boolean isFolder(String uri);
+
+ /**
+ * Checks if there is an object at the position specified by
+ * <code>uri</code> and if so if it is a content resource.
+ *
+ * @param uri
+ * URI of the object to check
+ * @return <code>true</code> if the object at <code>uri</code> exists
+ * and is a content resource
+ * @throws WebdavException
+ * if something goes wrong on the store level
+ */
+ boolean isResource(String uri);
+
+ /**
+ * Creates a folder at the position specified by <code>folderUri</code>.
+ *
+ * @param folderUri
+ * URI of the folder
+ * @throws WebdavException
+ * if something goes wrong on the store level
+ */
+ void createFolder(String folderUri);
+
+ /**
+ * Creates a content resource at the position specified by
+ * <code>resourceUri</code>.
+ *
+ * @param resourceUri
+ * URI of the content resource
+ * @throws WebdavException
+ * if something goes wrong on the store level
+ */
+ void createResource(String resourceUri);
+
+ /**
+ * Sets / stores the content of the resource specified by
+ * <code>resourceUri</code>.
+ *
+ * @param resourceUri
+ * URI of the resource where the content will be stored
+ * @param content
+ * input stream from which the content will be read from
+ * @param contentType
+ * content type of the resource or <code>null</code> if
+ * unknown
+ * @param characterEncoding
+ * character encoding of the resource or <code>null</code>
+ * if unknown or not applicable
+ * @throws WebdavException
+ * if something goes wrong on the store level
+ */
+ void setResourceContent(String resourceUri, InputStream content,
+ String contentType, String characterEncoding);
+
+ /**
+ * Gets the date of the last modiciation of the object specified by
+ * <code>uri</code>.
+ *
+ * @param uri
+ * URI of the object, i.e. content resource or folder
+ * @return date of last modification, <code>null</code> declares this
+ * value as invalid and asks the adapter to try to set it from the
+ * properties if possible
+ * @throws WebdavException
+ * if something goes wrong on the store level
+ */
+ Date getLastModified(String uri);
+
+ /**
+ * Gets the date of the creation of the object specified by <code>uri</code>.
+ *
+ * @param uri
+ * URI of the object, i.e. content resource or folder
+ * @return date of creation, <code>null</code> declares this value as
+ * invalid and asks the adapter to try to set it from the properties
+ * if possible
+ * @throws WebdavException
+ * if something goes wrong on the store level
+ */
+ Date getCreationDate(String uri);
+
+ /**
+ * Gets the names of the children of the folder specified by
+ * <code>folderUri</code>.
+ *
+ * @param folderUri
+ * URI of the folder
+ * @return array containing names of the children or null if it is no folder
+ * @throws WebdavException
+ * if something goes wrong on the store level
+ */
+ String[] getChildrenNames(String folderUri);
+
+ /**
+ * Gets the content of the resource specified by <code>resourceUri</code>.
+ *
+ * @param resourceUri
+ * URI of the content resource
+ * @return input stream you can read the content of the resource from
+ * @throws WebdavException
+ * if something goes wrong on the store level
+ */
+ InputStream getResourceContent(String resourceUri);
+
+ /**
+ * Gets the length of the content resource specified by
+ * <code>resourceUri</code>.
+ *
+ * @param resourceUri
+ * URI of the content resource
+ * @return length of the resource in bytes, <code>-1</code> declares this
+ * value as invalid and asks the adapter to try to set it from the
+ * properties if possible
+ * @throws WebdavException
+ * if something goes wrong on the store level
+ */
+ long getResourceLength(String resourceUri);
+
+ /**
+ * Removes the object specified by <code>uri</code>.
+ *
+ * @param uri
+ * URI of the object, i.e. content resource or folder
+ * @throws WebdavException
+ * if something goes wrong on the store level
+ */
+ void removeObject(String uri);
+
+}
\ No newline at end of file
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/WebdavStore.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/AccessDeniedException.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/AccessDeniedException.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/AccessDeniedException.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,36 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.sf.webdav.exceptions;
+
+public class AccessDeniedException extends WebdavException {
+
+ public AccessDeniedException() {
+ super();
+ }
+
+ public AccessDeniedException(String message) {
+ super(message);
+ }
+
+ public AccessDeniedException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public AccessDeniedException(Throwable cause) {
+ super(cause);
+ }
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/AccessDeniedException.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/ObjectAlreadyExistsException.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/ObjectAlreadyExistsException.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/ObjectAlreadyExistsException.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,36 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.sf.webdav.exceptions;
+
+public class ObjectAlreadyExistsException extends WebdavException {
+
+ public ObjectAlreadyExistsException() {
+ super();
+ }
+
+ public ObjectAlreadyExistsException(String message) {
+ super(message);
+ }
+
+ public ObjectAlreadyExistsException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public ObjectAlreadyExistsException(Throwable cause) {
+ super(cause);
+ }
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/ObjectAlreadyExistsException.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/ObjectNotFoundException.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/ObjectNotFoundException.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/ObjectNotFoundException.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,36 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.sf.webdav.exceptions;
+
+public class ObjectNotFoundException extends WebdavException {
+
+ public ObjectNotFoundException() {
+ super();
+ }
+
+ public ObjectNotFoundException(String message) {
+ super(message);
+ }
+
+ public ObjectNotFoundException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public ObjectNotFoundException(Throwable cause) {
+ super(cause);
+ }
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/ObjectNotFoundException.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/UnauthenticatedException.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/UnauthenticatedException.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/UnauthenticatedException.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,36 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.sf.webdav.exceptions;
+
+public class UnauthenticatedException extends WebdavException {
+
+ public UnauthenticatedException() {
+ super();
+ }
+
+ public UnauthenticatedException(String message) {
+ super(message);
+ }
+
+ public UnauthenticatedException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public UnauthenticatedException(Throwable cause) {
+ super(cause);
+ }
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/UnauthenticatedException.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/WebdavException.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/WebdavException.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/WebdavException.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,36 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.sf.webdav.exceptions;
+
+public class WebdavException extends RuntimeException {
+
+ public WebdavException() {
+ super();
+ }
+
+ public WebdavException(String message) {
+ super(message);
+ }
+
+ public WebdavException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public WebdavException(Throwable cause) {
+ super(cause);
+ }
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/exceptions/WebdavException.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/fromcatalina/MD5Encoder.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/fromcatalina/MD5Encoder.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/fromcatalina/MD5Encoder.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,64 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.sf.webdav.fromcatalina;
+
+/**
+ * Encode an MD5 digest into a String.
+ * <p>
+ * The 128 bit MD5 hash is converted into a 32 character long String. Each
+ * character of the String is the hexadecimal representation of 4 bits of the
+ * digest.
+ *
+ * @author Remy Maucherat
+ * @version $Revision: 1.1 $ $Date: 2007-01-05 03:23:22 $
+ */
+
+public final class MD5Encoder {
+
+ // ----------------------------------------------------- Instance Variables
+
+ private static final char[] hexadecimal = { '0', '1', '2', '3', '4', '5',
+ '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
+
+ // --------------------------------------------------------- Public Methods
+
+ /**
+ * Encodes the 128 bit (16 bytes) MD5 into a 32 character String.
+ *
+ * @param binaryData
+ * Array containing the digest
+ * @return Encoded MD5, or null if encoding failed
+ */
+ public String encode(byte[] binaryData) {
+
+ if (binaryData.length != 16)
+ return null;
+
+ char[] buffer = new char[32];
+
+ for (int i = 0; i < 16; i++) {
+ int low = (int) (binaryData[i] & 0x0f);
+ int high = (int) ((binaryData[i] & 0xf0) >> 4);
+ buffer[i * 2] = hexadecimal[high];
+ buffer[i * 2 + 1] = hexadecimal[low];
+ }
+
+ return new String(buffer);
+
+ }
+
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/fromcatalina/MD5Encoder.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/fromcatalina/RequestUtil.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/fromcatalina/RequestUtil.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/fromcatalina/RequestUtil.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,518 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.sf.webdav.fromcatalina;
+
+import java.io.UnsupportedEncodingException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.TimeZone;
+
+import javax.servlet.http.Cookie;
+
+/**
+ * General purpose request parsing and encoding utility methods.
+ *
+ * @author Craig R. McClanahan
+ * @author Tim Tye
+ * @version $Revision: 1.1 $ $Date: 2007-01-05 03:23:22 $
+ */
+
+public final class RequestUtil {
+
+ /**
+ * The DateFormat to use for generating readable dates in cookies.
+ */
+ private static SimpleDateFormat format = new SimpleDateFormat(
+ " EEEE, dd-MMM-yy kk:mm:ss zz");
+
+ static {
+ format.setTimeZone(TimeZone.getTimeZone("GMT"));
+ }
+
+ /**
+ * Encode a cookie as per RFC 2109. The resulting string can be used as the
+ * value for a <code>Set-Cookie</code> header.
+ *
+ * @param cookie
+ * The cookie to encode.
+ * @return A string following RFC 2109.
+ */
+ public static String encodeCookie(Cookie cookie) {
+
+ StringBuffer buf = new StringBuffer(cookie.getName());
+ buf.append("=");
+ buf.append(cookie.getValue());
+
+ if (cookie.getComment() != null) {
+ buf.append("; Comment=\"");
+ buf.append(cookie.getComment());
+ buf.append("\"");
+ }
+
+ if (cookie.getDomain() != null) {
+ buf.append("; Domain=\"");
+ buf.append(cookie.getDomain());
+ buf.append("\"");
+ }
+
+ long age = cookie.getMaxAge();
+ if (cookie.getMaxAge() >= 0) {
+ buf.append("; Max-Age=\"");
+ buf.append(cookie.getMaxAge());
+ buf.append("\"");
+ }
+
+ if (cookie.getPath() != null) {
+ buf.append("; Path=\"");
+ buf.append(cookie.getPath());
+ buf.append("\"");
+ }
+
+ if (cookie.getSecure()) {
+ buf.append("; Secure");
+ }
+
+ if (cookie.getVersion() > 0) {
+ buf.append("; Version=\"");
+ buf.append(cookie.getVersion());
+ buf.append("\"");
+ }
+
+ return (buf.toString());
+ }
+
+ /**
+ * Filter the specified message string for characters that are sensitive in
+ * HTML. This avoids potential attacks caused by including JavaScript codes
+ * in the request URL that is often reported in error messages.
+ *
+ * @param message
+ * The message string to be filtered
+ */
+ public static String filter(String message) {
+
+ if (message == null)
+ return (null);
+
+ char content[] = new char[message.length()];
+ message.getChars(0, message.length(), content, 0);
+ StringBuffer result = new StringBuffer(content.length + 50);
+ for (int i = 0; i < content.length; i++) {
+ switch (content[i]) {
+ case '<':
+ result.append("<");
+ break;
+ case '>':
+ result.append(">");
+ break;
+ case '&':
+ result.append("&");
+ break;
+ case '"':
+ result.append(""");
+ break;
+ default:
+ result.append(content[i]);
+ }
+ }
+ return (result.toString());
+
+ }
+
+ /**
+ * Normalize a relative URI path that may have relative values ("/./",
+ * "/../", and so on ) it it. <strong>WARNING</strong> - This method is
+ * useful only for normalizing application-generated paths. It does not try
+ * to perform security checks for malicious input.
+ *
+ * @param path
+ * Relative path to be normalized
+ */
+ public static String normalize(String path) {
+
+ if (path == null)
+ return null;
+
+ // Create a place for the normalized path
+ String normalized = path;
+
+ if (normalized.equals("/."))
+ return "/";
+
+ // Add a leading "/" if necessary
+ if (!normalized.startsWith("/"))
+ normalized = "/" + normalized;
+
+ // Resolve occurrences of "//" in the normalized path
+ while (true) {
+ int index = normalized.indexOf("//");
+ if (index < 0)
+ break;
+ normalized = normalized.substring(0, index)
+ + normalized.substring(index + 1);
+ }
+
+ // Resolve occurrences of "/./" in the normalized path
+ while (true) {
+ int index = normalized.indexOf("/./");
+ if (index < 0)
+ break;
+ normalized = normalized.substring(0, index)
+ + normalized.substring(index + 2);
+ }
+
+ // Resolve occurrences of "/../" in the normalized path
+ while (true) {
+ int index = normalized.indexOf("/../");
+ if (index < 0)
+ break;
+ if (index == 0)
+ return (null); // Trying to go outside our context
+ int index2 = normalized.lastIndexOf('/', index - 1);
+ normalized = normalized.substring(0, index2)
+ + normalized.substring(index + 3);
+ }
+
+ // Return the normalized path that we have completed
+ return (normalized);
+
+ }
+
+ /**
+ * Parse the character encoding from the specified content type header. If
+ * the content type is null, or there is no explicit character encoding,
+ * <code>null</code> is returned.
+ *
+ * @param contentType
+ * a content type header
+ */
+ public static String parseCharacterEncoding(String contentType) {
+
+ if (contentType == null)
+ return (null);
+ int start = contentType.indexOf("charset=");
+ if (start < 0)
+ return (null);
+ String encoding = contentType.substring(start + 8);
+ int end = encoding.indexOf(';');
+ if (end >= 0)
+ encoding = encoding.substring(0, end);
+ encoding = encoding.trim();
+ if ((encoding.length() > 2) && (encoding.startsWith("\""))
+ && (encoding.endsWith("\"")))
+ encoding = encoding.substring(1, encoding.length() - 1);
+ return (encoding.trim());
+
+ }
+
+ /**
+ * Parse a cookie header into an array of cookies according to RFC 2109.
+ *
+ * @param header
+ * Value of an HTTP "Cookie" header
+ */
+ public static Cookie[] parseCookieHeader(String header) {
+
+ if ((header == null) || (header.length() < 1))
+ return (new Cookie[0]);
+
+ ArrayList cookies = new ArrayList();
+ while (header.length() > 0) {
+ int semicolon = header.indexOf(';');
+ if (semicolon < 0)
+ semicolon = header.length();
+ if (semicolon == 0)
+ break;
+ String token = header.substring(0, semicolon);
+ if (semicolon < header.length())
+ header = header.substring(semicolon + 1);
+ else
+ header = "";
+ try {
+ int equals = token.indexOf('=');
+ if (equals > 0) {
+ String name = token.substring(0, equals).trim();
+ String value = token.substring(equals + 1).trim();
+ cookies.add(new Cookie(name, value));
+ }
+ } catch (Throwable e) {
+ ;
+ }
+ }
+
+ return ((Cookie[]) cookies.toArray(new Cookie[cookies.size()]));
+
+ }
+
+ /**
+ * Append request parameters from the specified String to the specified Map.
+ * It is presumed that the specified Map is not accessed from any other
+ * thread, so no synchronization is performed.
+ * <p>
+ * <strong>IMPLEMENTATION NOTE</strong>: URL decoding is performed
+ * individually on the parsed name and value elements, rather than on the
+ * entire query string ahead of time, to properly deal with the case where
+ * the name or value includes an encoded "=" or "&" character that would
+ * otherwise be interpreted as a delimiter.
+ *
+ * @param map
+ * Map that accumulates the resulting parameters
+ * @param data
+ * Input string containing request parameters
+ *
+ * @exception IllegalArgumentException
+ * if the data is malformed
+ */
+ public static void parseParameters(Map map, String data, String encoding)
+ throws UnsupportedEncodingException {
+
+ if ((data != null) && (data.length() > 0)) {
+
+ // use the specified encoding to extract bytes out of the
+ // given string so that the encoding is not lost. If an
+ // encoding is not specified, let it use platform default
+ byte[] bytes = null;
+ try {
+ if (encoding == null) {
+ bytes = data.getBytes();
+ } else {
+ bytes = data.getBytes(encoding);
+ }
+ } catch (UnsupportedEncodingException uee) {
+ }
+
+ parseParameters(map, bytes, encoding);
+ }
+
+ }
+
+ /**
+ * Decode and return the specified URL-encoded String. When the byte array
+ * is converted to a string, the system default character encoding is
+ * used... This may be different than some other servers.
+ *
+ * @param str
+ * The url-encoded string
+ *
+ * @exception IllegalArgumentException
+ * if a '%' character is not followed by a valid 2-digit
+ * hexadecimal number
+ */
+ public static String URLDecode(String str) {
+
+ return URLDecode(str, null);
+
+ }
+
+ /**
+ * Decode and return the specified URL-encoded String.
+ *
+ * @param str
+ * The url-encoded string
+ * @param enc
+ * The encoding to use; if null, the default encoding is used
+ * @exception IllegalArgumentException
+ * if a '%' character is not followed by a valid 2-digit
+ * hexadecimal number
+ */
+ public static String URLDecode(String str, String enc) {
+
+ if (str == null)
+ return (null);
+
+ // use the specified encoding to extract bytes out of the
+ // given string so that the encoding is not lost. If an
+ // encoding is not specified, let it use platform default
+ byte[] bytes = null;
+ try {
+ if (enc == null) {
+ bytes = str.getBytes();
+ } else {
+ bytes = str.getBytes(enc);
+ }
+ } catch (UnsupportedEncodingException uee) {
+ }
+
+ return URLDecode(bytes, enc);
+
+ }
+
+ /**
+ * Decode and return the specified URL-encoded byte array.
+ *
+ * @param bytes
+ * The url-encoded byte array
+ * @exception IllegalArgumentException
+ * if a '%' character is not followed by a valid 2-digit
+ * hexadecimal number
+ */
+ public static String URLDecode(byte[] bytes) {
+ return URLDecode(bytes, null);
+ }
+
+ /**
+ * Decode and return the specified URL-encoded byte array.
+ *
+ * @param bytes
+ * The url-encoded byte array
+ * @param enc
+ * The encoding to use; if null, the default encoding is used
+ * @exception IllegalArgumentException
+ * if a '%' character is not followed by a valid 2-digit
+ * hexadecimal number
+ */
+ public static String URLDecode(byte[] bytes, String enc) {
+
+ if (bytes == null)
+ return (null);
+
+ int len = bytes.length;
+ int ix = 0;
+ int ox = 0;
+ while (ix < len) {
+ byte b = bytes[ix++]; // Get byte to test
+ if (b == '+') {
+ b = (byte) ' ';
+ } else if (b == '%') {
+ b = (byte) ((convertHexDigit(bytes[ix++]) << 4) + convertHexDigit(bytes[ix++]));
+ }
+ bytes[ox++] = b;
+ }
+ if (enc != null) {
+ try {
+ return new String(bytes, 0, ox, enc);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ return new String(bytes, 0, ox);
+
+ }
+
+ /**
+ * Convert a byte character value to hexidecimal digit value.
+ *
+ * @param b
+ * the character value byte
+ */
+ private static byte convertHexDigit(byte b) {
+ if ((b >= '0') && (b <= '9'))
+ return (byte) (b - '0');
+ if ((b >= 'a') && (b <= 'f'))
+ return (byte) (b - 'a' + 10);
+ if ((b >= 'A') && (b <= 'F'))
+ return (byte) (b - 'A' + 10);
+ return 0;
+ }
+
+ /**
+ * Put name and value pair in map. When name already exist, add value to
+ * array of values.
+ *
+ * @param map
+ * The map to populate
+ * @param name
+ * The parameter name
+ * @param value
+ * The parameter value
+ */
+ private static void putMapEntry(Map map, String name, String value) {
+ String[] newValues = null;
+ String[] oldValues = (String[]) map.get(name);
+ if (oldValues == null) {
+ newValues = new String[1];
+ newValues[0] = value;
+ } else {
+ newValues = new String[oldValues.length + 1];
+ System.arraycopy(oldValues, 0, newValues, 0, oldValues.length);
+ newValues[oldValues.length] = value;
+ }
+ map.put(name, newValues);
+ }
+
+ /**
+ * Append request parameters from the specified String to the specified Map.
+ * It is presumed that the specified Map is not accessed from any other
+ * thread, so no synchronization is performed.
+ * <p>
+ * <strong>IMPLEMENTATION NOTE</strong>: URL decoding is performed
+ * individually on the parsed name and value elements, rather than on the
+ * entire query string ahead of time, to properly deal with the case where
+ * the name or value includes an encoded "=" or "&" character that would
+ * otherwise be interpreted as a delimiter.
+ *
+ * NOTE: byte array data is modified by this method. Caller beware.
+ *
+ * @param map
+ * Map that accumulates the resulting parameters
+ * @param data
+ * Input string containing request parameters
+ * @param encoding
+ * Encoding to use for converting hex
+ *
+ * @exception UnsupportedEncodingException
+ * if the data is malformed
+ */
+ public static void parseParameters(Map map, byte[] data, String encoding)
+ throws UnsupportedEncodingException {
+
+ if (data != null && data.length > 0) {
+ int pos = 0;
+ int ix = 0;
+ int ox = 0;
+ String key = null;
+ String value = null;
+ while (ix < data.length) {
+ byte c = data[ix++];
+ switch ((char) c) {
+ case '&':
+ value = new String(data, 0, ox, encoding);
+ if (key != null) {
+ putMapEntry(map, key, value);
+ key = null;
+ }
+ ox = 0;
+ break;
+ case '=':
+ if (key == null) {
+ key = new String(data, 0, ox, encoding);
+ ox = 0;
+ } else {
+ data[ox++] = c;
+ }
+ break;
+ case '+':
+ data[ox++] = (byte) ' ';
+ break;
+ case '%':
+ data[ox++] = (byte) ((convertHexDigit(data[ix++]) << 4) + convertHexDigit(data[ix++]));
+ break;
+ default:
+ data[ox++] = c;
+ }
+ }
+ // The last value does not end in '&'. So save it now.
+ if (key != null) {
+ value = new String(data, 0, ox, encoding);
+ putMapEntry(map, key, value);
+ }
+ }
+
+ }
+
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/fromcatalina/RequestUtil.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/fromcatalina/URLEncoder.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/fromcatalina/URLEncoder.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/fromcatalina/URLEncoder.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,99 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package net.sf.webdav.fromcatalina;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.util.BitSet;
+
+/**
+ *
+ * This class is very similar to the java.net.URLEncoder class.
+ *
+ * Unfortunately, with java.net.URLEncoder there is no way to specify to the
+ * java.net.URLEncoder which characters should NOT be encoded.
+ *
+ * This code was moved from DefaultServlet.java
+ *
+ * @author Craig R. McClanahan
+ * @author Remy Maucherat
+ */
+public class URLEncoder {
+ protected static final char[] hexadecimal = { '0', '1', '2', '3', '4', '5',
+ '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
+
+ // Array containing the safe characters set.
+ protected BitSet safeCharacters = new BitSet(256);
+
+ public URLEncoder() {
+ for (char i = 'a'; i <= 'z'; i++) {
+ addSafeCharacter(i);
+ }
+ for (char i = 'A'; i <= 'Z'; i++) {
+ addSafeCharacter(i);
+ }
+ for (char i = '0'; i <= '9'; i++) {
+ addSafeCharacter(i);
+ }
+ }
+
+ public void addSafeCharacter(char c) {
+ safeCharacters.set(c);
+ }
+
+ public String encode(String path) {
+ int maxBytesPerChar = 10;
+ int caseDiff = ('a' - 'A');
+ StringBuffer rewrittenPath = new StringBuffer(path.length());
+ ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
+ OutputStreamWriter writer = null;
+ try {
+ writer = new OutputStreamWriter(buf, "UTF8");
+ } catch (Exception e) {
+ e.printStackTrace();
+ writer = new OutputStreamWriter(buf);
+ }
+
+ for (int i = 0; i < path.length(); i++) {
+ int c = (int) path.charAt(i);
+ if (safeCharacters.get(c)) {
+ rewrittenPath.append((char) c);
+ } else {
+ // convert to external encoding before hex conversion
+ try {
+ writer.write((char) c);
+ writer.flush();
+ } catch (IOException e) {
+ buf.reset();
+ continue;
+ }
+ byte[] ba = buf.toByteArray();
+ for (int j = 0; j < ba.length; j++) {
+ // Converting each byte in the buffer
+ byte toEncode = ba[j];
+ rewrittenPath.append('%');
+ int low = (int) (toEncode & 0x0f);
+ int high = (int) ((toEncode & 0xf0) >> 4);
+ rewrittenPath.append(hexadecimal[high]);
+ rewrittenPath.append(hexadecimal[low]);
+ }
+ buf.reset();
+ }
+ }
+ return rewrittenPath.toString();
+ }
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/fromcatalina/URLEncoder.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/fromcatalina/XMLWriter.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/fromcatalina/XMLWriter.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/fromcatalina/XMLWriter.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,237 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.sf.webdav.fromcatalina;
+
+import java.io.IOException;
+import java.io.Writer;
+
+/**
+ * XMLWriter helper class.
+ *
+ * @author <a href="mailto:remm at apache.org">Remy Maucherat</a>
+ */
+public class XMLWriter {
+
+ // -------------------------------------------------------------- Constants
+
+ /**
+ * Opening tag.
+ */
+ public static final int OPENING = 0;
+
+ /**
+ * Closing tag.
+ */
+ public static final int CLOSING = 1;
+
+ /**
+ * Element with no content.
+ */
+ public static final int NO_CONTENT = 2;
+
+ // ----------------------------------------------------- Instance Variables
+
+ /**
+ * Buffer.
+ */
+ protected StringBuffer buffer = new StringBuffer();
+
+ /**
+ * Writer.
+ */
+ protected Writer writer = null;
+
+ // ----------------------------------------------------------- Constructors
+
+ /**
+ * Constructor.
+ */
+ public XMLWriter() {
+ }
+
+ /**
+ * Constructor.
+ */
+ public XMLWriter(Writer writer) {
+ this.writer = writer;
+ }
+
+ // --------------------------------------------------------- Public Methods
+
+ /**
+ * Retrieve generated XML.
+ *
+ * @return String containing the generated XML
+ */
+ public String toString() {
+ return buffer.toString();
+ }
+
+ /**
+ * Write property to the XML.
+ *
+ * @param namespace
+ * Namespace
+ * @param namespaceInfo
+ * Namespace info
+ * @param name
+ * Property name
+ * @param value
+ * Property value
+ */
+ public void writeProperty(String namespace, String namespaceInfo,
+ String name, String value) {
+ writeElement(namespace, namespaceInfo, name, OPENING);
+ buffer.append(value);
+ writeElement(namespace, namespaceInfo, name, CLOSING);
+
+ }
+
+ /**
+ * Write property to the XML.
+ *
+ * @param namespace
+ * Namespace
+ * @param name
+ * Property name
+ * @param value
+ * Property value
+ */
+ public void writeProperty(String namespace, String name, String value) {
+ writeElement(namespace, name, OPENING);
+ buffer.append(value);
+ writeElement(namespace, name, CLOSING);
+ }
+
+ /**
+ * Write property to the XML.
+ *
+ * @param namespace
+ * Namespace
+ * @param name
+ * Property name
+ */
+ public void writeProperty(String namespace, String name) {
+ writeElement(namespace, name, NO_CONTENT);
+ }
+
+ /**
+ * Write an element.
+ *
+ * @param name
+ * Element name
+ * @param namespace
+ * Namespace abbreviation
+ * @param type
+ * Element type
+ */
+ public void writeElement(String namespace, String name, int type) {
+ writeElement(namespace, null, name, type);
+ }
+
+ /**
+ * Write an element.
+ *
+ * @param namespace
+ * Namespace abbreviation
+ * @param namespaceInfo
+ * Namespace info
+ * @param name
+ * Element name
+ * @param type
+ * Element type
+ */
+ public void writeElement(String namespace, String namespaceInfo,
+ String name, int type) {
+ if ((namespace != null) && (namespace.length() > 0)) {
+ switch (type) {
+ case OPENING:
+ if (namespaceInfo != null) {
+ buffer.append("<" + namespace + ":" + name + " xmlns:"
+ + namespace + "=\"" + namespaceInfo + "\">");
+ } else {
+ buffer.append("<" + namespace + ":" + name + ">");
+ }
+ break;
+ case CLOSING:
+ buffer.append("</" + namespace + ":" + name + ">\n");
+ break;
+ case NO_CONTENT:
+ default:
+ if (namespaceInfo != null) {
+ buffer.append("<" + namespace + ":" + name + " xmlns:"
+ + namespace + "=\"" + namespaceInfo + "\"/>");
+ } else {
+ buffer.append("<" + namespace + ":" + name + "/>");
+ }
+ break;
+ }
+ } else {
+ switch (type) {
+ case OPENING:
+ buffer.append("<" + name + ">");
+ break;
+ case CLOSING:
+ buffer.append("</" + name + ">\n");
+ break;
+ case NO_CONTENT:
+ default:
+ buffer.append("<" + name + "/>");
+ break;
+ }
+ }
+ }
+
+ /**
+ * Write text.
+ *
+ * @param text
+ * Text to append
+ */
+ public void writeText(String text) {
+ buffer.append(text);
+ }
+
+ /**
+ * Write data.
+ *
+ * @param data
+ * Data to append
+ */
+ public void writeData(String data) {
+ buffer.append("<![CDATA[" + data + "]]>");
+ }
+
+ /**
+ * Write XML Header.
+ */
+ public void writeXMLHeader() {
+ buffer.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n");
+ }
+
+ /**
+ * Send data and reinitializes buffer.
+ */
+ public void sendData() throws IOException {
+ if (writer != null) {
+ writer.write(buffer.toString());
+ writer.flush();
+ buffer = new StringBuffer();
+ }
+ }
+
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/fromcatalina/XMLWriter.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/AbstractMethod.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/AbstractMethod.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/AbstractMethod.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,78 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.sf.webdav.methods;
+
+import net.sf.webdav.MethodExecutor;
+
+import javax.servlet.http.HttpServletRequest;
+
+public abstract class AbstractMethod implements MethodExecutor {
+
+ /**
+ * size of the io-buffer
+ */
+ protected static int BUF_SIZE = 50000;
+
+ /**
+ * Return the relative path associated with this servlet.
+ *
+ * @param request
+ * The servlet request we are processing
+ */
+ protected String getRelativePath(HttpServletRequest request) {
+
+ // Are we being processed by a RequestDispatcher.include()?
+ if (request.getAttribute("javax.servlet.include.request_uri") != null) {
+ String result = (String) request
+ .getAttribute("javax.servlet.include.path_info");
+ // if (result == null)
+ // result = (String) request
+ // .getAttribute("javax.servlet.include.servlet_path");
+ if ((result == null) || (result.equals("")))
+ result = "/";
+ return (result);
+ }
+
+ // No, extract the desired path directly from the request
+ String result = request.getPathInfo();
+ // if (result == null) {
+ // result = request.getServletPath();
+ // }
+ if ((result == null) || (result.equals(""))) {
+ result = "/";
+ }
+ return (result);
+
+ }
+
+ /**
+ * creates the parent path from the given path by removing the last '/' and
+ * everything after that
+ *
+ * @param path
+ * the path
+ * @return parent path
+ */
+ public String getParentPath(String path) {
+ int slash = path.lastIndexOf('/');
+ if (slash != -1) {
+ return path.substring(0, slash);
+ }
+ return null;
+ }
+
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/AbstractMethod.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DeterminableMethod.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DeterminableMethod.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DeterminableMethod.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,51 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package net.sf.webdav.methods;
+
+public abstract class DeterminableMethod extends AbstractMethod {
+
+ /**
+ * Determines the methods normally allowed for the resource.
+ *
+ * @param exists
+ * does the resource exist?
+ * @param isFolder
+ * is the resource a folder?
+ * @return all allowed methods, separated by commas
+ */
+ protected String determineMethodsAllowed(boolean exists, boolean isFolder) {
+ StringBuffer methodsAllowed = new StringBuffer();
+ try {
+ if (exists) {
+ methodsAllowed
+ .append("OPTIONS, GET, HEAD, POST, DELETE, TRACE");
+ methodsAllowed
+ .append(", PROPPATCH, COPY, MOVE, LOCK, UNLOCK, PROPFIND");
+ if (isFolder) {
+ methodsAllowed.append(", PUT");
+ }
+ return methodsAllowed.toString();
+ }
+ } catch (Exception e) {
+ // we do nothing, just return less allowed methods
+
+ }
+ methodsAllowed.append("OPTIONS, MKCOL, PUT, LOCK");
+ return methodsAllowed.toString();
+
+ }
+
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DeterminableMethod.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoCopy.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoCopy.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoCopy.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,390 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package net.sf.webdav.methods;
+
+import net.sf.webdav.exceptions.AccessDeniedException;
+import net.sf.webdav.exceptions.ObjectAlreadyExistsException;
+import net.sf.webdav.exceptions.ObjectNotFoundException;
+import net.sf.webdav.exceptions.WebdavException;
+import net.sf.webdav.WebdavStatus;
+import net.sf.webdav.WebdavStore;
+import net.sf.webdav.ResourceLocks;
+import net.sf.webdav.fromcatalina.RequestUtil;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.Hashtable;
+
+public class DoCopy extends ReportingMethod {
+
+ private static org.slf4j.Logger log = org.slf4j.LoggerFactory
+ .getLogger("net.sf.webdav.methods");
+
+ private WebdavStore store;
+ private ResourceLocks resourceLocks;
+ private DoDelete doDelete;
+ private boolean readOnly;
+
+ public DoCopy(WebdavStore store, ResourceLocks resourceLocks,
+ DoDelete doDelete, boolean readOnly) {
+ this.store = store;
+ this.resourceLocks = resourceLocks;
+ this.doDelete = doDelete;
+ this.readOnly = readOnly;
+ }
+
+ public void execute(HttpServletRequest req, HttpServletResponse resp)
+ throws IOException {
+ log.trace("-- " + this.getClass().getName());
+
+ String path = getRelativePath(req);
+ if (!readOnly) {
+ String lockOwner = "doCopy" + System.currentTimeMillis()
+ + req.toString();
+ if (resourceLocks.lock(path, lockOwner, false, -1)) {
+ try {
+ copyResource(req, resp);
+ } catch (AccessDeniedException e) {
+ resp.sendError(WebdavStatus.SC_FORBIDDEN);
+ } catch (ObjectAlreadyExistsException e) {
+ resp.sendError(WebdavStatus.SC_CONFLICT, req
+ .getRequestURI());
+ } catch (ObjectNotFoundException e) {
+ resp.sendError(WebdavStatus.SC_NOT_FOUND, req
+ .getRequestURI());
+ } catch (WebdavException e) {
+ resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
+ } finally {
+ resourceLocks.unlock(path, lockOwner);
+ }
+ } else {
+ resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
+ }
+
+ } else {
+ resp.sendError(WebdavStatus.SC_FORBIDDEN);
+ }
+
+ }
+
+ /**
+ * Copy a resource.
+ *
+ * @param req
+ * Servlet request
+ * @param resp
+ * Servlet response
+ * @return true if the copy is successful
+ * @throws WebdavException
+ * if an error in the underlying store occurs
+ * @throws IOException
+ * when an error occurs while sending the response
+ */
+ public boolean copyResource(HttpServletRequest req, HttpServletResponse resp)
+ throws WebdavException, IOException {
+
+ // Parsing destination header
+
+ String destinationPath = req.getHeader("Destination");
+
+ if (destinationPath == null) {
+ resp.sendError(WebdavStatus.SC_BAD_REQUEST);
+ return false;
+ }
+
+ // Remove url encoding from destination
+ destinationPath = RequestUtil.URLDecode(destinationPath, "UTF8");
+
+ int protocolIndex = destinationPath.indexOf("://");
+ if (protocolIndex >= 0) {
+ // if the Destination URL contains the protocol, we can safely
+ // trim everything upto the first "/" character after "://"
+ int firstSeparator = destinationPath
+ .indexOf("/", protocolIndex + 4);
+ if (firstSeparator < 0) {
+ destinationPath = "/";
+ } else {
+ destinationPath = destinationPath.substring(firstSeparator);
+ }
+ } else {
+ String hostName = req.getServerName();
+ if ((hostName != null) && (destinationPath.startsWith(hostName))) {
+ destinationPath = destinationPath.substring(hostName.length());
+ }
+
+ int portIndex = destinationPath.indexOf(":");
+ if (portIndex >= 0) {
+ destinationPath = destinationPath.substring(portIndex);
+ }
+
+ if (destinationPath.startsWith(":")) {
+ int firstSeparator = destinationPath.indexOf("/");
+ if (firstSeparator < 0) {
+ destinationPath = "/";
+ } else {
+ destinationPath = destinationPath.substring(firstSeparator);
+ }
+ }
+ }
+
+ // Normalise destination path (remove '.' and '..')
+ destinationPath = normalize(destinationPath);
+
+ String contextPath = req.getContextPath();
+ if ((contextPath != null) && (destinationPath.startsWith(contextPath))) {
+ destinationPath = destinationPath.substring(contextPath.length());
+ }
+
+ String pathInfo = req.getPathInfo();
+ if (pathInfo != null) {
+ String servletPath = req.getServletPath();
+ if ((servletPath != null)
+ && (destinationPath.startsWith(servletPath))) {
+ destinationPath = destinationPath.substring(servletPath
+ .length());
+ }
+ }
+
+ String path = getRelativePath(req);
+
+ // if source = destination
+ if (path.equals(destinationPath)) {
+ resp.sendError(HttpServletResponse.SC_FORBIDDEN);
+ }
+
+ // Parsing overwrite header
+
+ boolean overwrite = true;
+ String overwriteHeader = req.getHeader("Overwrite");
+
+ if (overwriteHeader != null) {
+ overwrite = overwriteHeader.equalsIgnoreCase("T");
+ }
+
+ // Overwriting the destination
+ String lockOwner = "copyResource" + System.currentTimeMillis()
+ + req.toString();
+ if (resourceLocks.lock(destinationPath, lockOwner, true, -1)) {
+ try {
+
+ // Retrieve the resources
+ if (!store.objectExists(path)) {
+ resp
+ .sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ return false;
+ }
+
+ boolean exists = store.objectExists(destinationPath);
+ Hashtable errorList = new Hashtable();
+
+ if (overwrite) {
+
+ // Delete destination resource, if it exists
+ if (exists) {
+ doDelete.deleteResource(destinationPath, errorList,
+ req, resp);
+
+ } else {
+ resp.setStatus(WebdavStatus.SC_CREATED);
+ }
+ } else {
+
+ // If the destination exists, then it's a conflict
+ if (exists) {
+ resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED);
+ return false;
+ } else {
+ resp.setStatus(WebdavStatus.SC_CREATED);
+ }
+
+ }
+ copy(path, destinationPath, errorList, req, resp);
+ if (!errorList.isEmpty()) {
+ sendReport(req, resp, errorList);
+ }
+
+ } finally {
+ resourceLocks.unlock(destinationPath, lockOwner);
+ }
+ } else {
+ resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
+ return false;
+ }
+ return true;
+
+ }
+
+ /**
+ * copies the specified resource(s) to the specified destination.
+ * preconditions must be handled by the caller. Standard status codes must
+ * be handled by the caller. a multi status report in case of errors is
+ * created here.
+ *
+ * @param sourcePath
+ * path from where to read
+ * @param destinationPath
+ * path where to write
+ * @param req
+ * HttpServletRequest
+ * @param resp
+ * HttpServletResponse
+ * @throws WebdavException
+ * if an error in the underlying store occurs
+ * @throws IOException
+ */
+ private void copy(String sourcePath, String destinationPath,
+ Hashtable errorList, HttpServletRequest req,
+ HttpServletResponse resp) throws WebdavException, IOException {
+
+ if (store.isResource(sourcePath)) {
+ store.createResource(destinationPath);
+ store.setResourceContent(destinationPath, store
+ .getResourceContent(sourcePath), null, null);
+ } else {
+
+ if (store.isFolder(sourcePath)) {
+ copyFolder(sourcePath, destinationPath, errorList, req, resp);
+ } else {
+ resp.sendError(WebdavStatus.SC_NOT_FOUND);
+ }
+ }
+ }
+
+ /**
+ * helper method of copy() recursively copies the FOLDER at source path to
+ * destination path
+ *
+ * @param sourcePath
+ * where to read
+ * @param destinationPath
+ * where to write
+ * @param errorList
+ * all errors that ocurred
+ * @param req
+ * HttpServletRequest
+ * @param resp
+ * HttpServletResponse
+ * @throws WebdavException
+ * if an error in the underlying store occurs
+ */
+ private void copyFolder(String sourcePath, String destinationPath,
+ Hashtable errorList, HttpServletRequest req,
+ HttpServletResponse resp) throws WebdavException {
+
+ store.createFolder(destinationPath);
+ boolean infiniteDepth = true;
+ if (req.getHeader("depth") != null) {
+ if (req.getHeader("depth").equals("0")) {
+ infiniteDepth = false;
+ }
+ }
+ if (infiniteDepth) {
+ String[] children = store.getChildrenNames(sourcePath);
+
+ for (int i = children.length - 1; i >= 0; i--) {
+ children[i] = "/" + children[i];
+ try {
+ if (store.isResource(sourcePath + children[i])) {
+ store.createResource(destinationPath + children[i]);
+ store.setResourceContent(destinationPath + children[i],
+ store.getResourceContent(sourcePath
+ + children[i]), null, null);
+
+ } else {
+ copyFolder(sourcePath + children[i], destinationPath
+ + children[i], errorList, req, resp);
+ }
+ } catch (AccessDeniedException e) {
+ errorList.put(destinationPath + children[i], new Integer(
+ WebdavStatus.SC_FORBIDDEN));
+ } catch (ObjectNotFoundException e) {
+ errorList.put(destinationPath + children[i], new Integer(
+ WebdavStatus.SC_NOT_FOUND));
+ } catch (ObjectAlreadyExistsException e) {
+ errorList.put(destinationPath + children[i], new Integer(
+ WebdavStatus.SC_CONFLICT));
+ } catch (WebdavException e) {
+ errorList.put(destinationPath + children[i], new Integer(
+ WebdavStatus.SC_INTERNAL_SERVER_ERROR));
+ }
+ }
+ }
+ }
+
+ /**
+ * Return a context-relative path, beginning with a "/", that represents the
+ * canonical version of the specified path after ".." and "." elements are
+ * resolved out. If the specified path attempts to go outside the boundaries
+ * of the current context (i.e. too many ".." path elements are present),
+ * return <code>null</code> instead.
+ *
+ * @param path
+ * Path to be normalized
+ */
+ protected String normalize(String path) {
+
+ if (path == null)
+ return null;
+
+ // Create a place for the normalized path
+ String normalized = path;
+
+ if (normalized.equals("/."))
+ return "/";
+
+ // Normalize the slashes and add leading slash if necessary
+ if (normalized.indexOf('\\') >= 0)
+ normalized = normalized.replace('\\', '/');
+ if (!normalized.startsWith("/"))
+ normalized = "/" + normalized;
+
+ // Resolve occurrences of "//" in the normalized path
+ while (true) {
+ int index = normalized.indexOf("//");
+ if (index < 0)
+ break;
+ normalized = normalized.substring(0, index)
+ + normalized.substring(index + 1);
+ }
+
+ // Resolve occurrences of "/./" in the normalized path
+ while (true) {
+ int index = normalized.indexOf("/./");
+ if (index < 0)
+ break;
+ normalized = normalized.substring(0, index)
+ + normalized.substring(index + 2);
+ }
+
+ // Resolve occurrences of "/../" in the normalized path
+ while (true) {
+ int index = normalized.indexOf("/../");
+ if (index < 0)
+ break;
+ if (index == 0)
+ return (null); // Trying to go outside our context
+ int index2 = normalized.lastIndexOf('/', index - 1);
+ normalized = normalized.substring(0, index2)
+ + normalized.substring(index + 3);
+ }
+
+ // Return the normalized path that we have completed
+ return (normalized);
+
+ }
+
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoCopy.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoDelete.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoDelete.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoDelete.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,168 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package net.sf.webdav.methods;
+
+import net.sf.webdav.exceptions.AccessDeniedException;
+import net.sf.webdav.exceptions.ObjectAlreadyExistsException;
+import net.sf.webdav.exceptions.WebdavException;
+import net.sf.webdav.exceptions.ObjectNotFoundException;
+import net.sf.webdav.WebdavStatus;
+import net.sf.webdav.ResourceLocks;
+import net.sf.webdav.WebdavStore;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.Hashtable;
+import java.io.IOException;
+
+public class DoDelete extends ReportingMethod {
+
+ private static org.slf4j.Logger log = org.slf4j.LoggerFactory
+ .getLogger("net.sf.webdav.methods");
+
+ private WebdavStore store;
+ private ResourceLocks resourceLocks;
+ private boolean readOnly;
+
+ public DoDelete(WebdavStore store, ResourceLocks resourceLocks,
+ boolean readOnly) {
+ this.store = store;
+ this.resourceLocks = resourceLocks;
+ this.readOnly = readOnly;
+ }
+
+ public void execute(HttpServletRequest req, HttpServletResponse resp)
+ throws IOException {
+ log.trace("-- " + this.getClass().getName());
+
+ if (!readOnly) {
+ String path = getRelativePath(req);
+ String lockOwner = "doDelete" + System.currentTimeMillis()
+ + req.toString();
+ if (resourceLocks.lock(path, lockOwner, true, -1)) {
+ try {
+ Hashtable errorList = new Hashtable();
+ deleteResource(path, errorList, req, resp);
+ if (!errorList.isEmpty()) {
+ sendReport(req, resp, errorList);
+ }
+ } catch (AccessDeniedException e) {
+ resp.sendError(WebdavStatus.SC_FORBIDDEN);
+ } catch (ObjectAlreadyExistsException e) {
+ resp.sendError(WebdavStatus.SC_NOT_FOUND, req
+ .getRequestURI());
+ } catch (WebdavException e) {
+ resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
+ } finally {
+ resourceLocks.unlock(path, lockOwner);
+ }
+ } else {
+ resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
+ }
+ } else {
+ resp.sendError(WebdavStatus.SC_FORBIDDEN);
+ }
+
+ }
+
+ /**
+ * deletes the recources at "path"
+ *
+ * @param path
+ * the folder to be deleted
+ * @param errorList
+ * all errors that ocurred
+ * @param req
+ * HttpServletRequest
+ * @param resp
+ * HttpServletResponse
+ * @throws WebdavException
+ * if an error in the underlying store occurs
+ * @throws IOException
+ * when an error occurs while sending the response
+ */
+ public void deleteResource(String path, Hashtable errorList,
+ HttpServletRequest req, HttpServletResponse resp)
+ throws IOException, WebdavException {
+
+ resp.setStatus(WebdavStatus.SC_NO_CONTENT);
+ if (!readOnly) {
+
+ if (store.isResource(path)) {
+ store.removeObject(path);
+ } else {
+ if (store.isFolder(path)) {
+
+ deleteFolder(path, errorList, req, resp);
+ store.removeObject(path);
+ } else {
+ resp.sendError(WebdavStatus.SC_NOT_FOUND);
+ }
+ }
+
+ } else {
+ resp.sendError(WebdavStatus.SC_FORBIDDEN);
+ }
+ }
+
+ /**
+ *
+ * helper method of deleteResource() deletes the folder and all of its
+ * contents
+ *
+ * @param path
+ * the folder to be deleted
+ * @param errorList
+ * all errors that ocurred
+ * @param req
+ * HttpServletRequest
+ * @param resp
+ * HttpServletResponse
+ * @throws WebdavException
+ * if an error in the underlying store occurs
+ */
+ private void deleteFolder(String path, Hashtable errorList,
+ HttpServletRequest req, HttpServletResponse resp)
+ throws WebdavException {
+
+ String[] children = store.getChildrenNames(path);
+ for (int i = children.length - 1; i >= 0; i--) {
+ children[i] = "/" + children[i];
+ try {
+ if (store.isResource(path + children[i])) {
+ store.removeObject(path + children[i]);
+
+ } else {
+ deleteFolder(path + children[i], errorList, req, resp);
+
+ store.removeObject(path + children[i]);
+
+ }
+ } catch (AccessDeniedException e) {
+ errorList.put(path + children[i], new Integer(
+ WebdavStatus.SC_FORBIDDEN));
+ } catch (ObjectNotFoundException e) {
+ errorList.put(path + children[i], new Integer(
+ WebdavStatus.SC_NOT_FOUND));
+ } catch (WebdavException e) {
+ errorList.put(path + children[i], new Integer(
+ WebdavStatus.SC_INTERNAL_SERVER_ERROR));
+ }
+ }
+
+ }
+
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoDelete.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoGet.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoGet.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoGet.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,79 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package net.sf.webdav.methods;
+
+import net.sf.webdav.MimeTyper;
+import net.sf.webdav.ResourceLocks;
+import net.sf.webdav.WebdavStore;
+
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+public class DoGet extends DoHead {
+
+ public DoGet(WebdavStore store, String dftIndexFile, String insteadOf404,
+ ResourceLocks resourceLocks, MimeTyper mimeTyper,
+ int contentLengthHeader) {
+ super(store, dftIndexFile, insteadOf404, resourceLocks, mimeTyper,
+ contentLengthHeader);
+
+ }
+
+ protected void doBody(HttpServletResponse resp, String path)
+ throws IOException {
+ OutputStream out = resp.getOutputStream();
+ InputStream in = store.getResourceContent(path);
+ try {
+ int read = -1;
+ byte[] copyBuffer = new byte[BUF_SIZE];
+
+ while ((read = in.read(copyBuffer, 0, copyBuffer.length)) != -1) {
+ out.write(copyBuffer, 0, read);
+ }
+ } finally {
+ in.close();
+ out.flush();
+ out.close();
+ }
+ }
+
+ protected void folderBody(String path, HttpServletResponse resp,
+ HttpServletRequest req) throws IOException {
+ if (store.isFolder(path)) {
+ // TODO some folder response (for browsers, DAV tools
+ // use propfind) in html?
+ OutputStream out = resp.getOutputStream();
+ String[] children = store.getChildrenNames(path);
+ StringBuffer childrenTemp = new StringBuffer();
+ childrenTemp.append("Contents of this Folder:\n");
+ for (int i = 0; i < children.length; i++) {
+ childrenTemp.append(children[i]);
+ childrenTemp.append("\n");
+ }
+ out.write(childrenTemp.toString().getBytes());
+ } else {
+ if (!store.objectExists(path)) {
+ resp.sendError(HttpServletResponse.SC_NOT_FOUND, req
+ .getRequestURI());
+ }
+
+ }
+ }
+
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoGet.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoHead.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoHead.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoHead.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,161 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package net.sf.webdav.methods;
+
+import net.sf.webdav.WebdavStore;
+import net.sf.webdav.ResourceLocks;
+import net.sf.webdav.MimeTyper;
+import net.sf.webdav.WebdavStatus;
+import net.sf.webdav.exceptions.AccessDeniedException;
+import net.sf.webdav.exceptions.ObjectAlreadyExistsException;
+import net.sf.webdav.exceptions.WebdavException;
+
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+
+public class DoHead extends AbstractMethod {
+
+ protected String dftIndexFile;
+ protected WebdavStore store;
+ protected String insteadOf404;
+ protected ResourceLocks resLocks;
+ protected MimeTyper mimeTyper;
+ protected int contLength;
+
+ private static org.slf4j.Logger log = org.slf4j.LoggerFactory
+ .getLogger("net.sf.webdav.methods");
+
+ public DoHead(WebdavStore store, String dftIndexFile, String insteadOf404,
+ ResourceLocks resourceLocks, MimeTyper mimeTyper,
+ int contentLengthHeader) {
+ this.store = store;
+ this.dftIndexFile = dftIndexFile;
+ this.insteadOf404 = insteadOf404;
+ this.resLocks = resourceLocks;
+ this.mimeTyper = mimeTyper;
+ this.contLength = contentLengthHeader;
+ }
+
+ public void execute(HttpServletRequest req, HttpServletResponse resp)
+ throws IOException {
+
+ // determines if the uri exists.
+
+ boolean bUriExists = false;
+
+ String path = getRelativePath(req);
+ log.trace("-- " + this.getClass().getName());
+
+ log.debug("-- do " + req.getMethod());
+
+ if (store.isFolder(path)) {
+ bUriExists = true;
+ if (dftIndexFile != null && !dftIndexFile.trim().equals("")) {
+
+ resp.sendRedirect(resp.encodeRedirectURL(req.getRequestURI()
+ + this.dftIndexFile));
+ return;
+ }
+ }
+ if (!store.objectExists(path)) {
+
+ if (this.insteadOf404 != null && !insteadOf404.trim().equals("")) {
+ path = this.insteadOf404;
+ }
+
+ } else
+ bUriExists = true;
+
+ String lockOwner = "doGet" + System.currentTimeMillis()
+ + req.toString();
+
+ if (resLocks.lock(path, lockOwner, false, 0)) {
+ try {
+
+ if (store.isResource(path)) {
+ // path points to a file but ends with / or \
+ if (path.endsWith("/") || (path.endsWith("\\"))) {
+ resp.sendError(HttpServletResponse.SC_NOT_FOUND, req
+ .getRequestURI());
+ } else {
+
+ // setting headers
+ long lastModified = store.getLastModified(path)
+ .getTime();
+ resp.setDateHeader("last-modified", lastModified);
+
+ long resourceLength = store.getResourceLength(path);
+
+ if (contLength == 1) {
+ if (resourceLength > 0) {
+ if (resourceLength <= Integer.MAX_VALUE) {
+ resp.setContentLength((int) resourceLength);
+ } else {
+ resp.setHeader("content-length", ""
+ + resourceLength);
+ // is "content-length" the right header?
+ // is
+ // long
+ // a valid format?
+ }
+ }
+ }
+
+ String mimeType = mimeTyper.getMimeType(path);
+ if (mimeType != null) {
+ resp.setContentType(mimeType);
+ } else {
+ int lastSlash = path.replace('\\', '/')
+ .lastIndexOf('/');
+ int lastDot = path.indexOf(".", lastSlash);
+ if (lastDot == -1) {
+ resp.setContentType("text/html");
+ }
+ }
+
+ doBody(resp, path);
+ }
+ } else {
+ folderBody(path, resp, req);
+ }
+ } catch (AccessDeniedException e) {
+ resp.sendError(WebdavStatus.SC_FORBIDDEN);
+ } catch (ObjectAlreadyExistsException e) {
+ resp.sendError(WebdavStatus.SC_NOT_FOUND, req.getRequestURI());
+ } catch (WebdavException e) {
+ resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
+ } finally {
+ resLocks.unlock(path, lockOwner);
+ }
+ } else {
+ resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
+ }
+ if (!bUriExists)
+ resp.setStatus(WebdavStatus.SC_NOT_FOUND);
+ }
+
+ protected void folderBody(String path, HttpServletResponse resp,
+ HttpServletRequest req) throws IOException {
+ // no body for HEAD
+ }
+
+ protected void doBody(HttpServletResponse resp, String path)
+ throws IOException {
+ // no body for HEAD
+ }
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoHead.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoLock.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoLock.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoLock.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,48 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package net.sf.webdav.methods;
+
+import java.io.IOException;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import net.sf.webdav.ResourceLocks;
+import net.sf.webdav.WebdavStore;
+
+public class DoLock extends DeterminableMethod {
+
+ private static org.slf4j.Logger log = org.slf4j.LoggerFactory
+ .getLogger("net.sf.webdav.methods");
+
+ private WebdavStore store;
+ private ResourceLocks resourceLocks;
+ private boolean readOnly;
+
+ public DoLock(WebdavStore store, ResourceLocks resourceLocks,
+ boolean readOnly) {
+ this.store = store;
+ this.resourceLocks = resourceLocks;
+ this.readOnly = readOnly;
+ }
+
+ public void execute(HttpServletRequest req, HttpServletResponse resp)
+ throws IOException {
+ log.trace("-- " + this.getClass().getName());
+
+ // Now MacOSX is happy
+ }
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoLock.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoMkcol.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoMkcol.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoMkcol.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,94 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package net.sf.webdav.methods;
+
+import net.sf.webdav.WebdavStatus;
+import net.sf.webdav.WebdavStore;
+import net.sf.webdav.ResourceLocks;
+import net.sf.webdav.exceptions.ObjectAlreadyExistsException;
+import net.sf.webdav.exceptions.AccessDeniedException;
+import net.sf.webdav.exceptions.WebdavException;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+public class DoMkcol extends DeterminableMethod {
+
+ private static org.slf4j.Logger log = org.slf4j.LoggerFactory
+ .getLogger("net.sf.webdav.methods");
+
+ private WebdavStore store;
+ private ResourceLocks resourceLocks;
+ private boolean readOnly;
+
+ public DoMkcol(WebdavStore store, ResourceLocks resourceLocks,
+ boolean readOnly) {
+ this.store = store;
+ this.resourceLocks = resourceLocks;
+ this.readOnly = readOnly;
+ }
+
+ public void execute(HttpServletRequest req, HttpServletResponse resp)
+ throws IOException {
+ log.trace("-- " + this.getClass().getName());
+
+ if (!readOnly) {
+ // not readonly
+ String path = getRelativePath(req);
+ String parentPath = getParentPath(path);
+ String lockOwner = "doMkcol" + System.currentTimeMillis()
+ + req.toString();
+ if (resourceLocks.lock(path, lockOwner, true, 0)) {
+ try {
+ if (parentPath != null && store.isFolder(parentPath)) {
+ boolean isFolder = store.isFolder(path);
+ if (!store.objectExists(path)) {
+ try {
+ store.createFolder(path);
+ resp.setStatus(WebdavStatus.SC_CREATED);
+ } catch (ObjectAlreadyExistsException e) {
+ String methodsAllowed = determineMethodsAllowed(
+ true, isFolder);
+ resp.addHeader("Allow", methodsAllowed);
+ resp
+ .sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED);
+ }
+ } else {
+ // object already exists
+ String methodsAllowed = determineMethodsAllowed(
+ true, isFolder);
+ resp.addHeader("Allow", methodsAllowed);
+ resp.sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED);
+ }
+ } else {
+ resp.sendError(WebdavStatus.SC_CONFLICT);
+ }
+ } catch (AccessDeniedException e) {
+ resp.sendError(WebdavStatus.SC_FORBIDDEN);
+ } catch (WebdavException e) {
+ resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
+ } finally {
+ resourceLocks.unlock(path, lockOwner);
+ }
+ } else {
+ resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
+ }
+ } else {
+ resp.sendError(WebdavStatus.SC_FORBIDDEN);
+ }
+ }
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoMkcol.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoMove.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoMove.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoMove.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,89 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package net.sf.webdav.methods;
+
+import net.sf.webdav.WebdavStatus;
+import net.sf.webdav.WebdavStore;
+import net.sf.webdav.ResourceLocks;
+import net.sf.webdav.exceptions.AccessDeniedException;
+import net.sf.webdav.exceptions.ObjectAlreadyExistsException;
+import net.sf.webdav.exceptions.WebdavException;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.Hashtable;
+import java.io.IOException;
+
+public class DoMove extends ReportingMethod {
+
+ private static org.slf4j.Logger log = org.slf4j.LoggerFactory
+ .getLogger("net.sf.webdav.methods");
+
+ private ResourceLocks resourceLocks;
+ private DoDelete doDelete;
+ private DoCopy doCopy;
+ private boolean readOnly;
+
+ public DoMove(ResourceLocks resourceLocks, DoDelete doDelete,
+ DoCopy doCopy, boolean readOnly) {
+ this.resourceLocks = resourceLocks;
+ this.doDelete = doDelete;
+ this.doCopy = doCopy;
+ this.readOnly = readOnly;
+ }
+
+ public void execute(HttpServletRequest req, HttpServletResponse resp)
+ throws IOException {
+ if (!readOnly) {
+
+ log.trace("-- " + this.getClass().getName());
+
+ String path = getRelativePath(req);
+ String lockOwner = "doMove" + System.currentTimeMillis()
+ + req.toString();
+ if (resourceLocks.lock(path, lockOwner, false, -1)) {
+ try {
+ if (doCopy.copyResource(req, resp)) {
+
+ Hashtable errorList = new Hashtable();
+ doDelete.deleteResource(path, errorList, req, resp);
+ if (!errorList.isEmpty()) {
+ sendReport(req, resp, errorList);
+ }
+
+ } else {
+ resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
+ }
+ } catch (AccessDeniedException e) {
+ resp.sendError(WebdavStatus.SC_FORBIDDEN);
+ } catch (ObjectAlreadyExistsException e) {
+ resp.sendError(WebdavStatus.SC_NOT_FOUND, req
+ .getRequestURI());
+ } catch (WebdavException e) {
+ resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
+ } finally {
+ resourceLocks.unlock(path, lockOwner);
+ }
+ } else {
+ resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
+ }
+ } else {
+ resp.sendError(WebdavStatus.SC_FORBIDDEN);
+
+ }
+
+ }
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoMove.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoNotImplemented.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoNotImplemented.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoNotImplemented.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,34 @@
+package net.sf.webdav.methods;
+
+import java.io.IOException;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import net.sf.webdav.MethodExecutor;
+import net.sf.webdav.WebdavStatus;
+
+public class DoNotImplemented implements MethodExecutor {
+
+ private static org.slf4j.Logger log = org.slf4j.LoggerFactory
+ .getLogger("net.sf.webdav.methods");
+ private boolean readOnly;
+
+ public DoNotImplemented(boolean readOnly) {
+ this.readOnly = readOnly;
+ }
+
+ public void execute(HttpServletRequest req, HttpServletResponse resp)
+ throws IOException {
+ log.trace("-- " + req.getMethod());
+
+ if (readOnly) {
+ resp.sendError(WebdavStatus.SC_FORBIDDEN);
+
+ } else
+
+ resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
+ // TODO implement proppatch
+
+ }
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoNotImplemented.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoOptions.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoOptions.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoOptions.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,68 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package net.sf.webdav.methods;
+
+import net.sf.webdav.WebdavStore;
+import net.sf.webdav.ResourceLocks;
+import net.sf.webdav.WebdavStatus;
+import net.sf.webdav.exceptions.AccessDeniedException;
+import net.sf.webdav.exceptions.WebdavException;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+public class DoOptions extends DeterminableMethod {
+
+ private static org.slf4j.Logger log = org.slf4j.LoggerFactory
+ .getLogger("net.sf.webdav.methods");
+
+ private WebdavStore store;
+ private ResourceLocks resLocks;
+
+ public DoOptions(WebdavStore store, ResourceLocks resLocks) {
+ this.store = store;
+ this.resLocks = resLocks;
+ }
+
+ public void execute(HttpServletRequest req, HttpServletResponse resp)
+ throws IOException {
+
+ log.trace("-- " + this.getClass().getName());
+
+ String lockOwner = "doOptions" + System.currentTimeMillis()
+ + req.toString();
+ String path = getRelativePath(req);
+ if (resLocks.lock(path, lockOwner, false, 0)) {
+ try {
+ resp.addHeader("DAV", "1, 2");
+
+ String methodsAllowed = determineMethodsAllowed(store
+ .objectExists(path), store.isFolder(path));
+ resp.addHeader("Allow", methodsAllowed);
+ resp.addHeader("MS-Author-Via", "DAV");
+ } catch (AccessDeniedException e) {
+ resp.sendError(WebdavStatus.SC_FORBIDDEN);
+ } catch (WebdavException e) {
+ resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
+ } finally {
+ resLocks.unlock(path, lockOwner);
+ }
+ } else {
+ resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
+ }
+ }
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoOptions.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoPropfind.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoPropfind.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoPropfind.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,646 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package net.sf.webdav.methods;
+
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Enumeration;
+import java.util.Locale;
+import java.util.TimeZone;
+import java.util.Vector;
+
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import net.sf.webdav.MimeTyper;
+import net.sf.webdav.ResourceLocks;
+import net.sf.webdav.WebdavStatus;
+import net.sf.webdav.WebdavStore;
+import net.sf.webdav.exceptions.AccessDeniedException;
+import net.sf.webdav.exceptions.WebdavException;
+import net.sf.webdav.fromcatalina.URLEncoder;
+import net.sf.webdav.fromcatalina.XMLWriter;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.InputSource;
+
+public class DoPropfind extends AbstractMethod {
+
+ private static org.slf4j.Logger log = org.slf4j.LoggerFactory
+ .getLogger("net.sf.webdav.methods");
+
+ /**
+ * Array containing the safe characters set.
+ */
+ protected static URLEncoder urlEncoder;
+
+ /**
+ * Simple date format for the creation date ISO representation (partial).
+ */
+ protected static final SimpleDateFormat creationDateFormat = new SimpleDateFormat(
+ "yyyy-MM-dd'T'HH:mm:ss'Z'");
+
+ /**
+ * Default depth is infite.
+ */
+ private static final int INFINITY = 3;
+
+ /**
+ * PROPFIND - Specify a property mask.
+ */
+ private static final int FIND_BY_PROPERTY = 0;
+
+ /**
+ * PROPFIND - Display all properties.
+ */
+ private static final int FIND_ALL_PROP = 1;
+
+ /**
+ * PROPFIND - Return property names.
+ */
+ private static final int FIND_PROPERTY_NAMES = 2;
+
+ private WebdavStore store;
+ private ResourceLocks resLocks;
+ private boolean readOnly;
+ private MimeTyper mimeTyper;
+
+ static {
+ creationDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
+ /**
+ * GMT timezone - all HTTP dates are on GMT
+ */
+ urlEncoder = new URLEncoder();
+ urlEncoder.addSafeCharacter('-');
+ urlEncoder.addSafeCharacter('_');
+ urlEncoder.addSafeCharacter('.');
+ urlEncoder.addSafeCharacter('*');
+ urlEncoder.addSafeCharacter('/');
+ }
+
+ public DoPropfind(WebdavStore store, ResourceLocks resLocks,
+ boolean readOnly, MimeTyper mimeTyper) {
+ this.store = store;
+ this.resLocks = resLocks;
+ this.readOnly = readOnly;
+ this.mimeTyper = mimeTyper;
+ }
+
+ public void execute(HttpServletRequest req, HttpServletResponse resp)
+ throws IOException {
+ log.trace("-- " + this.getClass().getName());
+
+ // Retrieve the resources
+ String lockOwner = "doPropfind" + System.currentTimeMillis()
+ + req.toString();
+ String path = getCleanPath(getRelativePath(req));
+ int depth = getDepth(req);
+ if (resLocks.lock(path, lockOwner, false, depth)) {
+ try {
+ if (!store.objectExists(path)) {
+ resp.sendError(HttpServletResponse.SC_NOT_FOUND, req
+ .getRequestURI());
+ return;
+ }
+
+ Vector properties = null;
+
+ int propertyFindType = FIND_ALL_PROP;
+ Node propNode = null;
+ getPropertyNodeAndType(propNode, propertyFindType, req);
+
+ if (propertyFindType == FIND_BY_PROPERTY) {
+ properties = getPropertiesFromXML(propNode);
+ }
+
+ resp.setStatus(WebdavStatus.SC_MULTI_STATUS);
+ resp.setContentType("text/xml; charset=UTF-8");
+
+ // Create multistatus object
+ XMLWriter generatedXML = new XMLWriter(resp.getWriter());
+ generatedXML.writeXMLHeader();
+ generatedXML.writeElement(null, "multistatus xmlns=\"DAV:\"",
+ XMLWriter.OPENING);
+ if (depth == 0) {
+ parseProperties(req, generatedXML, path, propertyFindType,
+ properties, mimeTyper.getMimeType(path));
+ } else {
+ recursiveParseProperties(path, req, generatedXML,
+ propertyFindType, properties, depth, mimeTyper
+ .getMimeType(path));
+ }
+ generatedXML.writeElement(null, "multistatus",
+ XMLWriter.CLOSING);
+ generatedXML.sendData();
+ } catch (AccessDeniedException e) {
+ resp.sendError(WebdavStatus.SC_FORBIDDEN);
+ } catch (WebdavException e) {
+ log.warn("Sending internal error!");
+ resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
+ } catch (ServletException e) {
+ e.printStackTrace(); // To change body of catch statement use
+ // File | Settings | File Templates.
+ } finally {
+ resLocks.unlock(path, lockOwner);
+ }
+ } else {
+ log.warn("Sending internal error!");
+ resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
+ }
+ }
+
+ /**
+ * reads the depth header from the request and returns it as a int
+ *
+ * @param req
+ * @return the depth from the depth header
+ */
+ private int getDepth(HttpServletRequest req) {
+ int depth = INFINITY;
+ String depthStr = req.getHeader("Depth");
+ if (depthStr != null) {
+ if (depthStr.equals("0")) {
+ depth = 0;
+ } else if (depthStr.equals("1")) {
+ depth = 1;
+ } else if (depthStr.equals("infinity")) {
+ depth = INFINITY;
+ }
+ }
+ return depth;
+ }
+
+ /**
+ * removes a / at the end of the path string, if present
+ *
+ * @param path
+ * the path
+ * @return the path without trailing /
+ */
+ private String getCleanPath(String path) {
+
+ if (path.endsWith("/") && path.length() > 1)
+ path = path.substring(0, path.length() - 1);
+ return path;
+ }
+
+ /**
+ * overwrites propNode and type, parsed from xml input stream
+ *
+ * @param propNode
+ * @param type
+ * @param req
+ * HttpServletRequest
+ * @throws javax.servlet.ServletException
+ */
+ private void getPropertyNodeAndType(Node propNode, int type,
+ ServletRequest req) throws ServletException {
+ if (req.getContentLength() != 0) {
+ DocumentBuilder documentBuilder = getDocumentBuilder();
+ try {
+ Document document = documentBuilder.parse(new InputSource(req
+ .getInputStream()));
+ // Get the root element of the document
+ Element rootElement = document.getDocumentElement();
+ NodeList childList = rootElement.getChildNodes();
+
+ for (int i = 0; i < childList.getLength(); i++) {
+ Node currentNode = childList.item(i);
+ switch (currentNode.getNodeType()) {
+ case Node.TEXT_NODE:
+ break;
+ case Node.ELEMENT_NODE:
+ if (currentNode.getNodeName().endsWith("prop")) {
+ type = FIND_BY_PROPERTY;
+ propNode = currentNode;
+ }
+ if (currentNode.getNodeName().endsWith("propname")) {
+ type = FIND_PROPERTY_NAMES;
+ }
+ if (currentNode.getNodeName().endsWith("allprop")) {
+ type = FIND_ALL_PROP;
+ }
+ break;
+ }
+ }
+ } catch (Exception e) {
+
+ }
+ } else {
+ // no content, which means it is a allprop request
+ type = FIND_ALL_PROP;
+ }
+ }
+
+ /**
+ * Return JAXP document builder instance.
+ */
+ private DocumentBuilder getDocumentBuilder() throws ServletException {
+ DocumentBuilder documentBuilder = null;
+ DocumentBuilderFactory documentBuilderFactory = null;
+ try {
+ documentBuilderFactory = DocumentBuilderFactory.newInstance();
+ documentBuilderFactory.setNamespaceAware(true);
+ documentBuilder = documentBuilderFactory.newDocumentBuilder();
+ } catch (ParserConfigurationException e) {
+ throw new ServletException("jaxp failed");
+ }
+ return documentBuilder;
+ }
+
+ private Vector getPropertiesFromXML(Node propNode) {
+ Vector properties;
+ properties = new Vector();
+ NodeList childList = propNode.getChildNodes();
+
+ for (int i = 0; i < childList.getLength(); i++) {
+ Node currentNode = childList.item(i);
+ switch (currentNode.getNodeType()) {
+ case Node.TEXT_NODE:
+ break;
+ case Node.ELEMENT_NODE:
+ String nodeName = currentNode.getNodeName();
+ String propertyName = null;
+ if (nodeName.indexOf(':') != -1) {
+ propertyName = nodeName
+ .substring(nodeName.indexOf(':') + 1);
+ } else {
+ propertyName = nodeName;
+ }
+ // href is a live property which is handled differently
+ properties.addElement(propertyName);
+ break;
+ }
+ }
+ return properties;
+ }
+
+ /**
+ * goes recursive through all folders. used by propfind
+ *
+ * @param currentPath
+ * the current path
+ * @param req
+ * HttpServletRequest
+ * @param generatedXML
+ * @param propertyFindType
+ * @param properties
+ * @param depth
+ * depth of the propfind
+ * @throws IOException
+ * if an error in the underlying store occurs
+ */
+ private void recursiveParseProperties(String currentPath,
+ HttpServletRequest req, XMLWriter generatedXML,
+ int propertyFindType, Vector properties, int depth, String mimeType)
+ throws WebdavException {
+
+ parseProperties(req, generatedXML, currentPath, propertyFindType,
+ properties, mimeType);
+ String[] names = store.getChildrenNames(currentPath);
+ if ((names != null) && (depth > 0)) {
+
+ for (int i = 0; i < names.length; i++) {
+ String name = names[i];
+ String newPath = currentPath;
+ if (!(newPath.endsWith("/"))) {
+ newPath += "/";
+ }
+ newPath += name;
+ recursiveParseProperties(newPath, req, generatedXML,
+ propertyFindType, properties, depth - 1, mimeType);
+ }
+ }
+ }
+
+ /**
+ * Propfind helper method.
+ *
+ * @param req
+ * The servlet request
+ * @param generatedXML
+ * XML response to the Propfind request
+ * @param path
+ * Path of the current resource
+ * @param type
+ * Propfind type
+ * @param propertiesVector
+ * If the propfind type is find properties by name, then this
+ * Vector contains those properties
+ */
+ private void parseProperties(HttpServletRequest req,
+ XMLWriter generatedXML, String path, int type,
+ Vector propertiesVector, String mimeType) throws WebdavException {
+
+ String creationdate = getISOCreationDate(store.getCreationDate(path)
+ .getTime());
+ boolean isFolder = store.isFolder(path);
+ SimpleDateFormat formatter = new SimpleDateFormat(
+ "EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
+ formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
+ String lastModified = formatter.format(store.getLastModified(path));
+ String resourceLength = String.valueOf(store.getResourceLength(path));
+
+ // ResourceInfo resourceInfo = new ResourceInfo(path, resources);
+
+ generatedXML.writeElement(null, "response", XMLWriter.OPENING);
+ String status = new String("HTTP/1.1 " + WebdavStatus.SC_OK + " "
+ + WebdavStatus.getStatusText(WebdavStatus.SC_OK));
+
+ // Generating href element
+ generatedXML.writeElement(null, "href", XMLWriter.OPENING);
+
+ String href = req.getContextPath();
+ String servletPath = req.getServletPath();
+ if (servletPath != null) {
+ if ((href.endsWith("/")) && (servletPath.startsWith("/")))
+ href += servletPath.substring(1);
+ else
+ href += servletPath;
+ }
+ if ((href.endsWith("/")) && (path.startsWith("/")))
+ href += path.substring(1);
+ else
+ href += path;
+ if ((isFolder) && (!href.endsWith("/")))
+ href += "/";
+
+ generatedXML.writeText(rewriteUrl(href));
+
+ generatedXML.writeElement(null, "href", XMLWriter.CLOSING);
+
+ String resourceName = path;
+ int lastSlash = path.lastIndexOf('/');
+ if (lastSlash != -1)
+ resourceName = resourceName.substring(lastSlash + 1);
+
+ switch (type) {
+
+ case FIND_ALL_PROP:
+
+ generatedXML.writeElement(null, "propstat", XMLWriter.OPENING);
+ generatedXML.writeElement(null, "prop", XMLWriter.OPENING);
+
+ generatedXML.writeProperty(null, "creationdate", creationdate);
+ generatedXML.writeElement(null, "displayname", XMLWriter.OPENING);
+ generatedXML.writeData(resourceName);
+ generatedXML.writeElement(null, "displayname", XMLWriter.CLOSING);
+ if (!isFolder) {
+ generatedXML.writeProperty(null, "getlastmodified",
+ lastModified);
+ generatedXML.writeProperty(null, "getcontentlength",
+ resourceLength);
+ String contentType = mimeType;
+ if (contentType != null) {
+ generatedXML.writeProperty(null, "getcontenttype",
+ contentType);
+ }
+ generatedXML.writeProperty(null, "getetag", getETag(path,
+ resourceLength, lastModified));
+ generatedXML.writeElement(null, "resourcetype",
+ XMLWriter.NO_CONTENT);
+ } else {
+ generatedXML.writeElement(null, "resourcetype",
+ XMLWriter.OPENING);
+ generatedXML.writeElement(null, "collection",
+ XMLWriter.NO_CONTENT);
+ generatedXML.writeElement(null, "resourcetype",
+ XMLWriter.CLOSING);
+ }
+
+ generatedXML.writeProperty(null, "source", "");
+ generatedXML.writeElement(null, "prop", XMLWriter.CLOSING);
+ generatedXML.writeElement(null, "status", XMLWriter.OPENING);
+ generatedXML.writeText(status);
+ generatedXML.writeElement(null, "status", XMLWriter.CLOSING);
+ generatedXML.writeElement(null, "propstat", XMLWriter.CLOSING);
+
+ break;
+
+ case FIND_PROPERTY_NAMES:
+
+ generatedXML.writeElement(null, "propstat", XMLWriter.OPENING);
+ generatedXML.writeElement(null, "prop", XMLWriter.OPENING);
+
+ generatedXML.writeElement(null, "creationdate",
+ XMLWriter.NO_CONTENT);
+ generatedXML
+ .writeElement(null, "displayname", XMLWriter.NO_CONTENT);
+ if (!isFolder) {
+ generatedXML.writeElement(null, "getcontentlanguage",
+ XMLWriter.NO_CONTENT);
+ generatedXML.writeElement(null, "getcontentlength",
+ XMLWriter.NO_CONTENT);
+ generatedXML.writeElement(null, "getcontenttype",
+ XMLWriter.NO_CONTENT);
+ generatedXML
+ .writeElement(null, "getetag", XMLWriter.NO_CONTENT);
+ generatedXML.writeElement(null, "getlastmodified",
+ XMLWriter.NO_CONTENT);
+ }
+ generatedXML.writeElement(null, "resourcetype",
+ XMLWriter.NO_CONTENT);
+ generatedXML.writeElement(null, "source", XMLWriter.NO_CONTENT);
+ generatedXML.writeElement(null, "lockdiscovery",
+ XMLWriter.NO_CONTENT);
+
+ generatedXML.writeElement(null, "prop", XMLWriter.CLOSING);
+ generatedXML.writeElement(null, "status", XMLWriter.OPENING);
+ generatedXML.writeText(status);
+ generatedXML.writeElement(null, "status", XMLWriter.CLOSING);
+ generatedXML.writeElement(null, "propstat", XMLWriter.CLOSING);
+
+ break;
+
+ case FIND_BY_PROPERTY:
+
+ Vector propertiesNotFound = new Vector();
+
+ // Parse the list of properties
+
+ generatedXML.writeElement(null, "propstat", XMLWriter.OPENING);
+ generatedXML.writeElement(null, "prop", XMLWriter.OPENING);
+
+ Enumeration properties = propertiesVector.elements();
+
+ while (properties.hasMoreElements()) {
+
+ String property = (String) properties.nextElement();
+
+ if (property.equals("creationdate")) {
+ generatedXML.writeProperty(null, "creationdate",
+ creationdate);
+ } else if (property.equals("displayname")) {
+ generatedXML.writeElement(null, "displayname",
+ XMLWriter.OPENING);
+ generatedXML.writeData(resourceName);
+ generatedXML.writeElement(null, "displayname",
+ XMLWriter.CLOSING);
+ } else if (property.equals("getcontentlanguage")) {
+ if (isFolder) {
+ propertiesNotFound.addElement(property);
+ } else {
+ generatedXML.writeElement(null, "getcontentlanguage",
+ XMLWriter.NO_CONTENT);
+ }
+ } else if (property.equals("getcontentlength")) {
+ if (isFolder) {
+ propertiesNotFound.addElement(property);
+ } else {
+ generatedXML.writeProperty(null, "getcontentlength",
+ resourceLength);
+ }
+ } else if (property.equals("getcontenttype")) {
+ if (isFolder) {
+ propertiesNotFound.addElement(property);
+ } else {
+ generatedXML.writeProperty(null, "getcontenttype",
+ mimeType);
+ }
+ } else if (property.equals("getetag")) {
+ if (isFolder) {
+ propertiesNotFound.addElement(property);
+ } else {
+ generatedXML.writeProperty(null, "getetag", getETag(
+ path, resourceLength, lastModified));
+ }
+ } else if (property.equals("getlastmodified")) {
+ if (isFolder) {
+ propertiesNotFound.addElement(property);
+ } else {
+ generatedXML.writeProperty(null, "getlastmodified",
+ lastModified);
+ }
+ } else if (property.equals("resourcetype")) {
+ if (isFolder) {
+ generatedXML.writeElement(null, "resourcetype",
+ XMLWriter.OPENING);
+ generatedXML.writeElement(null, "collection",
+ XMLWriter.NO_CONTENT);
+ generatedXML.writeElement(null, "resourcetype",
+ XMLWriter.CLOSING);
+ } else {
+ generatedXML.writeElement(null, "resourcetype",
+ XMLWriter.NO_CONTENT);
+ }
+ } else if (property.equals("source")) {
+ generatedXML.writeProperty(null, "source", "");
+ } else {
+ propertiesNotFound.addElement(property);
+ }
+
+ }
+
+ generatedXML.writeElement(null, "prop", XMLWriter.CLOSING);
+ generatedXML.writeElement(null, "status", XMLWriter.OPENING);
+ generatedXML.writeText(status);
+ generatedXML.writeElement(null, "status", XMLWriter.CLOSING);
+ generatedXML.writeElement(null, "propstat", XMLWriter.CLOSING);
+
+ Enumeration propertiesNotFoundList = propertiesNotFound.elements();
+
+ if (propertiesNotFoundList.hasMoreElements()) {
+
+ status = new String("HTTP/1.1 " + WebdavStatus.SC_NOT_FOUND
+ + " "
+ + WebdavStatus.getStatusText(WebdavStatus.SC_NOT_FOUND));
+
+ generatedXML.writeElement(null, "propstat", XMLWriter.OPENING);
+ generatedXML.writeElement(null, "prop", XMLWriter.OPENING);
+
+ while (propertiesNotFoundList.hasMoreElements()) {
+ generatedXML.writeElement(null,
+ (String) propertiesNotFoundList.nextElement(),
+ XMLWriter.NO_CONTENT);
+ }
+
+ generatedXML.writeElement(null, "prop", XMLWriter.CLOSING);
+ generatedXML.writeElement(null, "status", XMLWriter.OPENING);
+ generatedXML.writeText(status);
+ generatedXML.writeElement(null, "status", XMLWriter.CLOSING);
+ generatedXML.writeElement(null, "propstat", XMLWriter.CLOSING);
+
+ }
+
+ break;
+
+ }
+
+ generatedXML.writeElement(null, "response", XMLWriter.CLOSING);
+
+ }
+
+ /**
+ * Get creation date in ISO format.
+ *
+ * @param creationDate
+ * the date in milliseconds
+ * @return the Date in ISO format
+ */
+ private String getISOCreationDate(long creationDate) {
+ StringBuffer creationDateValue = new StringBuffer(creationDateFormat
+ .format(new Date(creationDate)));
+ /*
+ * int offset = Calendar.getInstance().getTimeZone().getRawOffset() /
+ * 3600000; // FIXME ? if (offset < 0) { creationDateValue.append("-");
+ * offset = -offset; } else if (offset > 0) {
+ * creationDateValue.append("+"); } if (offset != 0) { if (offset < 10)
+ * creationDateValue.append("0"); creationDateValue.append(offset +
+ * ":00"); } else { creationDateValue.append("Z"); }
+ */
+ return creationDateValue.toString();
+ }
+
+ /**
+ * Get the ETag associated with a file.
+ *
+ * @param path
+ * path to the resource
+ * @param resourceLength
+ * filesize
+ * @param lastModified
+ * last-modified date
+ * @return the ETag
+ */
+ protected String getETag(String path, String resourceLength,
+ String lastModified) {
+ // TODO create a real (?) ETag
+ // parameter "path" is not used at the monent
+ return "W/\"" + resourceLength + "-" + lastModified + "\"";
+
+ }
+
+ /**
+ * URL rewriter.
+ *
+ * @param path
+ * Path which has to be rewiten
+ * @return the rewritten path
+ */
+ protected String rewriteUrl(String path) {
+ return urlEncoder.encode(path);
+ }
+
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoPropfind.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoPut.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoPut.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoPut.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,98 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package net.sf.webdav.methods;
+
+import java.io.IOException;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import net.sf.webdav.ResourceLocks;
+import net.sf.webdav.WebdavStatus;
+import net.sf.webdav.WebdavStore;
+import net.sf.webdav.exceptions.AccessDeniedException;
+import net.sf.webdav.exceptions.WebdavException;
+
+public class DoPut extends AbstractMethod {
+
+ private static org.slf4j.Logger log = org.slf4j.LoggerFactory
+ .getLogger("net.sf.webdav.methods");
+
+ private WebdavStore store;
+ private ResourceLocks resLocks;
+ private boolean readOnly;
+ private boolean lazyFolderCreationOnPut;
+
+ public DoPut(WebdavStore store, ResourceLocks resLocks, boolean readOnly,
+ boolean lazyFolderCreationOnPut) {
+ this.store = store;
+ this.resLocks = resLocks;
+ this.readOnly = readOnly;
+ this.lazyFolderCreationOnPut = lazyFolderCreationOnPut;
+ }
+
+ public void execute(HttpServletRequest req, HttpServletResponse resp)
+ throws IOException {
+ log.trace("-- " + this.getClass().getName());
+
+ if (!readOnly) {
+ String path = getRelativePath(req);
+ String parentPath = getParentPath(path);
+ String lockOwner = "doPut" + System.currentTimeMillis()
+ + req.toString();
+ if (resLocks.lock(path, lockOwner, true, -1)) {
+ try {
+ if (parentPath != null && !store.isFolder(parentPath)
+ && lazyFolderCreationOnPut) {
+ store.createFolder(parentPath);
+ }
+ if (!store.isFolder(path)) {
+ if (!store.objectExists(path)) {
+ store.createResource(path);
+ resp.setStatus(HttpServletResponse.SC_CREATED);
+ } else {
+ String userAgent = req.getHeader("User-Agent");
+ if (userAgent.contains("WebDAVFS/1.5")) {
+ log
+ .trace("DoPut.execute() : do workaround for user agent '"
+ + userAgent + "'");
+ resp.setStatus(HttpServletResponse.SC_CREATED);
+ } else {
+ resp
+ .setStatus(HttpServletResponse.SC_NO_CONTENT);
+ }
+ }
+ store.setResourceContent(path, req.getInputStream(),
+ null, null);
+ resp.setContentLength((int) store
+ .getResourceLength(path));
+ }
+ } catch (AccessDeniedException e) {
+ resp.sendError(WebdavStatus.SC_FORBIDDEN);
+ } catch (WebdavException e) {
+ resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
+ } finally {
+ resLocks.unlock(path, lockOwner);
+ }
+ } else {
+ resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
+ }
+ } else {
+ resp.sendError(WebdavStatus.SC_FORBIDDEN);
+ }
+
+ }
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/DoPut.java
___________________________________________________________________
Name: svn:eol-style
+ native
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/ReportingMethod.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/ReportingMethod.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/ReportingMethod.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,86 @@
+/*
+ * Copyright 1999,2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package net.sf.webdav.methods;
+
+import net.sf.webdav.WebdavStatus;
+import net.sf.webdav.fromcatalina.XMLWriter;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.Hashtable;
+import java.util.Enumeration;
+import java.io.IOException;
+import java.io.Writer;
+
+public abstract class ReportingMethod extends AbstractMethod {
+
+ /**
+ * Send a multistatus element containing a complete error report to the
+ * client.
+ *
+ * @param req
+ * Servlet request
+ * @param resp
+ * Servlet response
+ * @param errorList
+ * List of error to be displayed
+ */
+ protected void sendReport(HttpServletRequest req, HttpServletResponse resp,
+ Hashtable errorList) throws IOException {
+
+ resp.setStatus(WebdavStatus.SC_MULTI_STATUS);
+
+ String absoluteUri = req.getRequestURI();
+ String relativePath = getRelativePath(req);
+
+ XMLWriter generatedXML = new XMLWriter();
+ generatedXML.writeXMLHeader();
+
+ generatedXML.writeElement(null, "multistatus xmlns=\"DAV:\"",
+ XMLWriter.OPENING);
+
+ Enumeration pathList = errorList.keys();
+ while (pathList.hasMoreElements()) {
+
+ String errorPath = (String) pathList.nextElement();
+ int errorCode = ((Integer) errorList.get(errorPath)).intValue();
+
+ generatedXML.writeElement(null, "response", XMLWriter.OPENING);
+
+ generatedXML.writeElement(null, "href", XMLWriter.OPENING);
+ String toAppend = errorPath.substring(relativePath.length());
+ if (!toAppend.startsWith("/"))
+ toAppend = "/" + toAppend;
+ generatedXML.writeText(absoluteUri + toAppend);
+ generatedXML.writeElement(null, "href", XMLWriter.CLOSING);
+ generatedXML.writeElement(null, "status", XMLWriter.OPENING);
+ generatedXML.writeText("HTTP/1.1 " + errorCode + " "
+ + WebdavStatus.getStatusText(errorCode));
+ generatedXML.writeElement(null, "status", XMLWriter.CLOSING);
+
+ generatedXML.writeElement(null, "response", XMLWriter.CLOSING);
+
+ }
+
+ generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING);
+
+ Writer writer = resp.getWriter();
+ writer.write(generatedXML.toString());
+ writer.close();
+
+ }
+
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/net/sf/webdav/methods/ReportingMethod.java
___________________________________________________________________
Name: svn:eol-style
+ native
Modified: labs/jbossrules/trunk/drools-jbrms/src/main/java/org/drools/brms/JBRMS.gwt.xml
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/org/drools/brms/JBRMS.gwt.xml 2008-05-23 02:03:55 UTC (rev 20120)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/org/drools/brms/JBRMS.gwt.xml 2008-05-23 02:05:18 UTC (rev 20121)
@@ -17,9 +17,8 @@
<servlet path="/asset" class="org.drools.brms.server.files.AssetFileServlet"/>
<servlet path="/backup" class="org.drools.brms.server.files.RepositoryBackupServlet"/>
<servlet path="/package" class="org.drools.brms.server.files.PackageDeploymentServlet"/>
- <servlet path="/webdav" class="net.sf.webdav.WebdavServlet"/>
+ <servlet path="/webdav" class="org.drools.brms.server.files.WebdavServlet"/>
<servlet path="/api" class="org.drools.brms.server.files.RestAPIServlet"/>
-
</module>
Modified: labs/jbossrules/trunk/drools-jbrms/src/main/java/org/drools/brms/server/files/WebDAVImpl.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/org/drools/brms/server/files/WebDAVImpl.java 2008-05-23 02:03:55 UTC (rev 20120)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/org/drools/brms/server/files/WebDAVImpl.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -1,34 +1,39 @@
package org.drools.brms.server.files;
import java.io.ByteArrayInputStream;
+import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Calendar;
+import java.util.Collections;
import java.util.Date;
-import java.util.HashMap;
-import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.WeakHashMap;
-import net.sf.webdav.IWebdavStorage;
+import net.sf.webdav.WebdavStore;
import org.apache.commons.io.IOUtils;
import org.drools.repository.AssetItem;
import org.drools.repository.PackageItem;
import org.drools.repository.RulesRepository;
-public class WebDAVImpl implements IWebdavStorage {
+public class WebDAVImpl implements WebdavStore {
- static Map<String, byte[]> osxDoubleData = new HashMap<String, byte[]>();
+ /** for the rubbish OSX double data (the ._ rubbish) */
+ static Map<String, byte[]> osxDoubleData = Collections.synchronizedMap(new WeakHashMap<String, byte[]>());
-
final ThreadLocal<RulesRepository> tlRepo = new ThreadLocal<RulesRepository>();;
+ public WebDAVImpl(File f) {
+
+ }
+
public WebDAVImpl() {
}
@@ -40,7 +45,7 @@
return tlRepo.get();
}
- public void begin(Principal pr, Hashtable params) throws Exception {
+ public void begin(Principal pr) {
tlRepo.set(RestAPIServlet.getRepository());
}
@@ -48,14 +53,13 @@
//already done
}
- public void commit() throws IOException {
+ public void commit() {
System.out.println("COMMIT");
-
getRepo().save();
tlRepo.set(null);
}
- public void createFolder(String uri) throws IOException {
+ public void createFolder(String uri) {
System.out.println("creating folder:" + uri);
String[] path = getPath(uri);
if (path[0].equals("packages")) {
@@ -75,7 +79,7 @@
}
}
- public void createResource(String uri) throws IOException {
+ public void createResource(String uri) {
System.out.println("creating resource:" + uri);
//for mac OSX, ignore these annoying things
if (uri.endsWith(".DS_Store")) return;
@@ -111,7 +115,7 @@
}
- public String[] getChildrenNames(String uri) throws IOException {
+ public String[] getChildrenNames(String uri) {
System.out.println("getChildrenNames :" + uri);
RulesRepository repository = getRepo();
@@ -148,7 +152,7 @@
}
}
- public Date getCreationDate(String uri) throws IOException {
+ public Date getCreationDate(String uri) {
System.out.println("getCreationDate :" + uri);
RulesRepository repository = getRepo();
@@ -170,7 +174,7 @@
}
}
- public Date getLastModified(String uri) throws IOException {
+ public Date getLastModified(String uri) {
System.out.println("getLastModified :" + uri);
RulesRepository repository = getRepo();
@@ -194,7 +198,7 @@
- public InputStream getResourceContent(String uri) throws IOException {
+ public InputStream getResourceContent(String uri) {
System.out.println("get resource content:" + uri);
return getContent(uri);
}
@@ -216,13 +220,26 @@
}
}
- public long getResourceLength(String uri) throws IOException {
+ public long getResourceLength(String uri) {
System.out.println("get resource length :" + uri);
+ String[] path = getPath(uri);
+ try {
+ if (path.length == 3 && path[0].equals("packages")) {
+ RulesRepository repo = getRepo();
+ PackageItem pkg = repo.loadPackage(path[1]);
+ AssetItem asset = pkg.loadAsset(AssetItem.getAssetNameFromFileName(path[2])[0]);
+ return asset.getContentLength();
+ } else {
+ return 0;
+ }
+ } catch (Exception e) {
+ System.err.println("Not able to get content length");
+ return 0;
+ }
- return 0;
}
- public boolean isFolder(String uri) throws IOException {
+ public boolean isFolder(String uri) {
System.out.println("is folder :" + uri);
RulesRepository repository = getRepo();
String[] path = getPath(uri);
@@ -236,7 +253,7 @@
}
}
- public boolean isResource(String uri) throws IOException {
+ public boolean isResource(String uri) {
RulesRepository repository = getRepo();
System.out.println("is resource :" + uri);
String[] path = getPath(uri);
@@ -254,14 +271,14 @@
}
- public boolean objectExists(String uri) throws IOException {
- if (uri.endsWith(" copy")) {
+ public boolean objectExists(String uri) {
+ if (uri.indexOf(" copy ") > 0) {
throw new IllegalArgumentException("OSX is not capable of copy and pasting without breaking the file extension.");
}
return internalObjectExists(uri);
}
- public boolean internalObjectExists(String uri) throws IOException {
+ public boolean internalObjectExists(String uri) {
if (uri.contains("Premium_Colour_Combinations.brl copy")) {
System.out.println("");
@@ -294,7 +311,7 @@
}
}
- public void removeObject(String uri) throws IOException {
+ public void removeObject(String uri) {
RulesRepository repository = getRepo();
System.out.println("remove object:" + uri);
String[] path = getPath(uri);
@@ -325,14 +342,14 @@
}
- public void rollback() throws IOException {
+ public void rollback() {
System.out.println("ROLLBACK");
RulesRepository repository = getRepo();
repository.getSession().logout();
}
- public void setResourceContent(String uri, InputStream content, String contentType, String characterEncoding) throws IOException {
+ public void setResourceContent(String uri, InputStream content, String contentType, String characterEncoding) {
RulesRepository repository = getRepo();
System.out.println("set resource content:" + uri);
if (uri.endsWith(".DS_Store")) return;
@@ -344,13 +361,19 @@
String packageName = path[1];
if (path[2].startsWith("._")) {
- this.osxDoubleData.put(uri, IOUtils.toByteArray(content));
+ try {
+ this.osxDoubleData.put(uri, IOUtils.toByteArray(content));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
return;
}
String[] assetName = AssetItem.getAssetNameFromFileName(path[2]);
PackageItem pkg = repository.loadPackage(packageName);
AssetItem asset = pkg.loadAsset(assetName[0]);
asset.updateBinaryContentAttachment(content);
+ //here we could save, or check in, depending on if enough time has passed to justify
+ //a new version. Otherwise we will pollute the version history with lots of trivial versions.
if (shouldCreateNewVersion(asset.getLastModified())) {
asset.checkin("");
}
@@ -360,8 +383,6 @@
throw new UnsupportedOperationException("Unable to save content to this location.");
}
- //here we could save, or check in, depending on if enough time has passed to justify
- //a new version. Otherwise we will pollute the version history with lots of trivial versions.
}
@@ -386,6 +407,7 @@
}
+
}
Added: labs/jbossrules/trunk/drools-jbrms/src/main/java/org/drools/brms/server/files/WebdavServlet.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/java/org/drools/brms/server/files/WebdavServlet.java (rev 0)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/java/org/drools/brms/server/files/WebdavServlet.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -0,0 +1,80 @@
+package org.drools.brms.server.files;
+
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.Constructor;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import net.sf.webdav.WebDavServletBean;
+import net.sf.webdav.WebdavStore;
+
+/**
+ * Taken from the webdav servlet project. Modified to be more useful.
+ * But most of the logic is still in webdav servlet library (which at the time
+ * of writing was included as source as it was easier - needed some fixes).
+ *
+ * @author Michael Neale
+ *
+ */
+public class WebdavServlet extends WebDavServletBean {
+ private static final long serialVersionUID = 5L;
+
+
+ public void init() throws ServletException {
+
+ // Parameters from web.xml
+ String clazzName = WebDAVImpl.class.getName();
+
+
+ File root = new File("");// getFileRoot();
+
+ WebdavStore webdavStore = constructStore(clazzName, root);
+
+ String lazyFolderCreationOnPutValue = getInitParameter("lazyFolderCreationOnPut");
+ boolean lazyFolderCreationOnPut = lazyFolderCreationOnPutValue != null
+ && lazyFolderCreationOnPutValue.equals("1");
+
+ String dftIndexFile = getInitParameter("default-index-file");
+ String insteadOf404 = getInitParameter("instead-of-404");
+
+ int noContentLengthHeader = 0;
+
+ super.init(webdavStore, dftIndexFile, insteadOf404,
+ noContentLengthHeader, lazyFolderCreationOnPut);
+ }
+
+ @Override
+ protected void service(HttpServletRequest req, HttpServletResponse resp)
+ throws ServletException, IOException {
+ String auth = req.getHeader("Authorization");
+ if (!RestAPIServlet.allowUser(auth)) {
+ resp.setHeader("WWW-Authenticate", "BASIC realm=\"users\"");
+ resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
+ }
+ else {
+ super.service(req, resp);
+ }
+ }
+
+
+
+ protected WebdavStore constructStore(String clazzName, File root) {
+ WebdavStore webdavStore;
+ try {
+ Class clazz = WebdavServlet.class.getClassLoader().loadClass(
+ clazzName);
+
+ Constructor ctor = clazz.getConstructor(new Class[] { File.class });
+
+ webdavStore = (WebdavStore) ctor.newInstance(new Object[] { root });
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new RuntimeException("some problem making store component", e);
+ }
+ return webdavStore;
+ }
+
+}
Property changes on: labs/jbossrules/trunk/drools-jbrms/src/main/java/org/drools/brms/server/files/WebdavServlet.java
___________________________________________________________________
Name: svn:eol-style
+ native
Modified: labs/jbossrules/trunk/drools-jbrms/src/main/webapp/WEB-INF/web.xml
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/main/webapp/WEB-INF/web.xml 2008-05-23 02:03:55 UTC (rev 20120)
+++ labs/jbossrules/trunk/drools-jbrms/src/main/webapp/WEB-INF/web.xml 2008-05-23 02:05:18 UTC (rev 20121)
@@ -36,7 +36,7 @@
</servlet>
<servlet>
<servlet-name>WebdavServlet</servlet-name>
- <servlet-class>net.sf.webdav.WebdavServlet</servlet-class>
+ <servlet-class>org.drools.brms.server.files.WebdavServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>RestAPIServlet</servlet-name>
Modified: labs/jbossrules/trunk/drools-jbrms/src/test/java/org/drools/brms/server/files/WebDAVImplTest.java
===================================================================
--- labs/jbossrules/trunk/drools-jbrms/src/test/java/org/drools/brms/server/files/WebDAVImplTest.java 2008-05-23 02:03:55 UTC (rev 20120)
+++ labs/jbossrules/trunk/drools-jbrms/src/test/java/org/drools/brms/server/files/WebDAVImplTest.java 2008-05-23 02:05:18 UTC (rev 20121)
@@ -1,6 +1,7 @@
package org.drools.brms.server.files;
import java.io.ByteArrayInputStream;
+import java.io.File;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
@@ -18,7 +19,7 @@
public class WebDAVImplTest extends TestCase {
public void testPath() {
- WebDAVImpl imp = new WebDAVImpl(null);
+ WebDAVImpl imp = new WebDAVImpl(new File(""));
String[] path = imp.getPath("http://goober/whee/webdav/packages/packagename/resource.drl");
assertEquals("packages", path[0]);
assertEquals("packagename", path[1]);
@@ -33,9 +34,9 @@
//OSX does stupid shit when copying in the same directory
//for instance, it creates the copy as foobar.x copy - totally hosing
//the file extension.
- WebDAVImpl imp = new WebDAVImpl(null);
+ WebDAVImpl imp = new WebDAVImpl(new File(""));
try {
- imp.objectExists("/foo/webdav/packages/foobar/Something.drl copy");
+ imp.objectExists("/foo/webdav/packages/foobar/Something.drl copy 42");
fail("should not be allowed");
} catch (IllegalArgumentException e) {
assertNotNull(e.getMessage());
@@ -44,7 +45,7 @@
}
public void testListRoot() throws Exception {
- WebDAVImpl imp = new WebDAVImpl(null);
+ WebDAVImpl imp = new WebDAVImpl(new File(""));
String[] children = imp.getChildrenNames("foobar/webdav");
assertEquals(1, children.length);
assertEquals("packages", children[0]);
@@ -241,7 +242,18 @@
}
+ public void testResourceLength() throws Exception {
+ WebDAVImpl imp = getImpl();
+ assertEquals(0, imp.getResourceLength("foo/bar/webdav/packages"));
+ imp.createFolder("/foo/webdav/packages/testResourceLengthDAV");
+ imp.createResource("/foo/webdav/packages/testResourceLengthDAV/testResourceLength");
+ assertEquals(0, imp.getResourceLength("/foo/webdav/packages/testResourceLengthDAV/testResourceLength"));
+ imp.setResourceContent("/foo/webdav/packages/testResourceLengthDAV/testResourceLength", IOUtils.toInputStream("some input"), null, null);
+ assertEquals("some input".getBytes().length, imp.getResourceLength("/foo/webdav/packages/testResourceLengthDAV/testResourceLength"));
+ }
+
+
public void testObjectExists() throws Exception {
WebDAVImpl imp = getImpl();
assertFalse(imp.objectExists("foo/webdav/bar"));
@@ -267,6 +279,10 @@
imp.createFolder("foo/webdav/packages/testDavRemoveObjectAsset");
imp.createResource("foo/webdav/packages/testDavRemoveObjectAsset/asset.drl");
+
+ AssetItem as = imp.getRepo().loadPackage("testDavRemoveObjectAsset").loadAsset("asset");
+ long origVer = as.getVersionNumber();
+
assertTrue(imp.objectExists("foo/webdav/packages/testDavRemoveObjectAsset/asset.drl"));
imp.removeObject("foo/webdav/packages/testDavRemoveObjectAsset/asset.drl");
assertFalse(imp.objectExists("foo/webdav/packages/testDavRemoveObjectAsset/asset.drl"));
@@ -275,6 +291,8 @@
imp.createResource("foo/webdav/packages/testDavRemoveObjectAsset/asset.drl");
assertTrue(imp.objectExists("foo/webdav/packages/testDavRemoveObjectAsset/asset.drl"));
+ as = imp.getRepo().loadPackage("testDavRemoveObjectAsset").loadAsset("asset");
+ assertTrue(as.getVersionNumber() > origVer);
imp.createFolder("foo/webdav/packages/testDavRemoveObjectFolder");
assertTrue(imp.objectExists("foo/webdav/packages/testDavRemoveObjectFolder"));
@@ -319,7 +337,7 @@
WebDAVImpl i = new WebDAVImpl();
assertNull(i.getRepo());
try {
- i.begin(null, null);
+ i.begin(null);
} catch (Exception e) {
fail("should not happen");
}
More information about the jboss-svn-commits
mailing list