You are viewing a plain text version of this content. The canonical link for it is here.
Posted to slide-dev@jakarta.apache.org by re...@locus.apache.org on 2000/11/22 07:19:11 UTC
cvs commit: jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/util Base64.java DOMUtils.java DOMWriter.java MD5Encoder.java MIME2Java.java WebdavXMLPrinter.java
remm 00/11/21 22:19:11
Added: src/webdav/client/src/org/apache/webdav/ant
CollectionScanner.java ScanException.java
Scanner.java
src/webdav/client/src/org/apache/webdav/ant/taskdefs
Get.java WebdavMatchingTask.java
src/webdav/client/src/org/apache/webdav/cmd Main.java
src/webdav/client/src/org/apache/webdav/lib
Authenticator.java Cookie.java Credentials.java
Header.java HeaderElement.java NameValuePair.java
Property.java RequestOutputStream.java
ResponseInputStream.java State.java
WebdavClient.java WebdavException.java
WebdavStatus.java
src/webdav/client/src/org/apache/webdav/lib/methods
CopyMethod.java DeleteMethod.java GetMethod.java
HeadMethod.java LockMethod.java MkcolMethod.java
MoveMethod.java OptionsMethod.java PostMethod.java
PropFindMethod.java PropMethodBase.java
PropPatchMethod.java PutMethod.java
UnlockMethod.java WebdavMethod.java
WebdavMethodBase.java
src/webdav/client/src/org/apache/webdav/lib/util Base64.java
DOMUtils.java DOMWriter.java MD5Encoder.java
MIME2Java.java WebdavXMLPrinter.java
Log:
- Move the client to to src/webdav/client.
Sorry for all the commit messages ...
Revision Changes Path
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/ant/CollectionScanner.java
Index: CollectionScanner.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.webdav.ant;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;
import org.apache.webdav.lib.Property;
import org.apache.webdav.lib.WebdavClient;
import org.apache.webdav.lib.WebdavException;
import org.apache.webdav.lib.methods.PropFindMethod;
import org.apache.webdav.lib.methods.OptionsMethod;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class CollectionScanner extends Scanner {
private URL baseURL = null;
private WebdavClient client = null;
private static final Vector PROPERTY_NAMES = new Vector();
static {
PROPERTY_NAMES.addElement("DAV:resourcetype");
}
/**
* Scans the base URL for resources that match at least one include
* pattern, and don't match any exclude patterns.
*
* @exception IllegalStateException when baseurl was set incorrecly
* @exception ScanException when a WebDAV or other error occurs
*/
public void scan() {
if (baseURL == null) {
throw new IllegalStateException(
"BaseURL must be set before calling the scan() method");
}
// initialize member variables
filesIncluded = new Vector();
filesExcluded = new Vector();
filesNotIncluded = new Vector();
try {
// check to make sure that DAV is supported...
OptionsMethod options = new OptionsMethod();
options.setPath(baseURL.getFile());
client.startSession(baseURL.getHost(),
(baseURL.getPort() < 0 ? 80 : baseURL.getPort()));
client.executeMethod(options);
if (!options.isAllowed("PROPFIND")) {
throw new ScanException(
"Web server doesn't support PROPFIND; can't find resources");
}
// get a list of all resources from the given URL
PropFindMethod propFind = new PropFindMethod();
propFind.setPath(baseURL.getFile());
propFind.setPropertyNames(PROPERTY_NAMES.elements());
propFind.setType(PropFindMethod.NAMES);
client.executeMethod(propFind);
for (Enumeration e = propFind.getAllResponseURLs();
e.hasMoreElements(); ) {
String href = (String) e.nextElement();
for (Enumeration properties = propFind.getResponseProperties(href);
properties.hasMoreElements(); ) {
Property property = (Property) properties.nextElement();
if (property.getName().endsWith("resourcetype")) {
addResource(href, property.getElement());
}
}
}
} catch (ScanException e) {
throw e;
} catch (WebdavException e) {
throw new ScanException(e.getMessage(), e);
} catch (UnknownHostException e) {
throw new ScanException(e.getMessage(), e);
} catch (IOException e) {
throw new ScanException(e.getMessage(), e);
}
}
protected void addResource(String href, Element resourcetype)
throws ScanException {
boolean isCollection = false;
NodeList tmp = resourcetype.getChildNodes();
for (int i = 0; i < tmp.getLength(); i++ ) {
try {
Element child = (Element) tmp.item(i);
if (child.getTagName().endsWith("collection")) {
isCollection = true;
}
} catch (ClassCastException e) {
}
}
try {
String url = (new URL(getBaseURL(), href)).getFile();
String relativeURL = url.substring(getBaseURL().getFile().length());
if (isCollection) {
if (isIncluded(relativeURL)) {
if (isExcluded(relativeURL)) {
dirsExcluded.addElement(relativeURL);
} else {
dirsIncluded.addElement(relativeURL);
}
} else {
dirsNotIncluded.addElement(relativeURL);
}
} else {
if (isIncluded(relativeURL)) {
if (isExcluded(relativeURL)) {
filesExcluded.addElement(relativeURL);
} else {
filesIncluded.addElement(relativeURL);
}
} else {
filesNotIncluded.addElement(relativeURL);
}
}
} catch (MalformedURLException e) {
throw new ScanException(
"The XML response returned an invalid URL: " + e.getMessage(), e);
}
}
public URL getBaseURL() {
return this.baseURL;
}
public void setBaseURL(URL baseURL) {
this.baseURL = baseURL;
}
public void setWebdavClient(WebdavClient client) {
this.client = client;
}
protected String getSeparator() {
return "/";
}
protected char getSeparatorChar() {
return '/';
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/ant/ScanException.java
Index: ScanException.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.webdav.ant;
import org.apache.tools.ant.BuildException;
/**
* Signals an error condition during the scan of a directory or web
* collection.
*
* @author B.C. Holmes
*/
public class ScanException extends BuildException {
public ScanException() {
super();
}
/**
* Constructs an exception with the given descriptive message.
* @param msg Description of or information about the exception.
*/
public ScanException(String msg) {
super(msg);
}
/**
* Constructs an exception with the given message and exception as
* a root cause.
* @param msg Description of or information about the exception.
* @param cause Throwable that might have cause this one.
*/
public ScanException(String msg, Throwable cause) {
super(msg, cause);
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/ant/Scanner.java
Index: Scanner.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.webdav.ant;
import java.util.StringTokenizer;
import java.util.Vector;
/**
* Class for scanning a directory for files/directories that match a certain
* criteria.
* <p>
* These criteria consist of a set of include and exclude patterns. With these
* patterns, you can select which files you want to have included, and which
* files you want to have excluded.
* <p>
* The idea is simple. A given directory is recursively scanned for all files
* and directories. Each file/directory is matched against a set of include
* and exclude patterns. Only files/directories that match at least one
* pattern of the include pattern list, and don't match a pattern of the
* exclude pattern list will be placed in the list of files/directories found.
* <p>
* When no list of include patterns is supplied, "**" will be used, which
* means that everything will be matched. When no list of exclude patterns is
* supplied, an empty list is used, such that nothing will be excluded.
* <p>
* The pattern matching is done as follows:
* The name to be matched is split up in path segments. A path segment is the
* name of a directory or file, which is bounded by
* <code>File.separator</code> ('/' under UNIX, '\' under Windows).
* E.g. "abc/def/ghi/xyz.java" is split up in the segments "abc", "def", "ghi"
* and "xyz.java".
* The same is done for the pattern against which should be matched.
* <p>
* Then the segments of the name and the pattern will be matched against each
* other. When '**' is used for a path segment in the pattern, then it matches
* zero or more path segments of the name.
* <p>
* There are special case regarding the use of <code>File.separator</code>s at
* the beginningof the pattern and the string to match:<br>
* When a pattern starts with a <code>File.separator</code>, the string
* to match must also start with a <code>File.separator</code>.
* When a pattern does not start with a <code>File.separator</code>, the
* string to match may not start with a <code>File.separator</code>.
* When one of these rules is not obeyed, the string will not
* match.
* <p>
* When a name path segment is matched against a pattern path segment, the
* following special characters can be used:
* '*' matches zero or more characters,
* '?' matches one character.
* <p>
* Examples:
* <p>
* "**\*.class" matches all .class files/dirs in a directory tree.
* <p>
* "test\a??.java" matches all files/dirs which start with an 'a', then two
* more characters and then ".java", in a directory called test.
* <p>
* "**" matches everything in a directory tree.
* <p>
* "**\test\**\XYZ*" matches all files/dirs that start with "XYZ" and where
* there is a parent directory called test (e.g. "abc\test\def\ghi\XYZ123").
* <p>
* Example of usage:
* <pre>
* String[] includes = {"**\\*.class"};
* String[] excludes = {"modules\\*\\**"};
* ds.setIncludes(includes);
* ds.setExcludes(excludes);
* ds.setBasedir(new File("test"));
* ds.scan();
*
* System.out.println("FILES:");
* String[] files = ds.getIncludedFiles();
* for (int i = 0; i < files.length;i++) {
* System.out.println(files[i]);
* }
* </pre>
* This will scan a directory called test for .class files, but excludes all
* .class files in all directories under a directory called "modules"
*
* @author Arnout J. Kuiper <a href="mailto:ajkuiper@wxs.nl">ajkuiper@wxs.nl</a>
*/
public abstract class Scanner {
/**
* Patterns that should be excluded by default.
*
* @see #addDefaultExcludes()
*/
private final static String[] DEFAULTEXCLUDES = {
"**/*~",
"**/#*#",
"**/%*%",
"**/CVS",
"**/CVS/*",
"**/.cvsignore"
};
/**
* The patterns for the files that should be included.
*/
private String[] includes;
/**
* The patterns for the files that should be excluded.
*/
private String[] excludes;
/**
* The files that where found and matched at least one includes, and matched
* no excludes.
*/
protected Vector filesIncluded;
/**
* The files that where found and did not match any includes.
*/
protected Vector filesNotIncluded;
/**
* The files that where found and matched at least one includes, and also
* matched at least one excludes.
*/
protected Vector filesExcluded;
/**
* The directories that where found and matched at least one includes, and
* matched no excludes.
*/
protected Vector dirsIncluded;
/**
* The directories that where found and did not match any includes.
*/
protected Vector dirsNotIncluded;
/**
* The files that where found and matched at least one includes, and also
* matched at least one excludes.
*/
protected Vector dirsExcluded;
/**
* Constructor.
*/
public Scanner() {
}
/**
* Matches a path against a pattern.
*
* @param pattern the (non-null) pattern to match against
* @param str the (non-null) string (path) to match
*
* @return <code>true</code> when the pattern matches against the string.
* <code>false</code> otherwise.
*/
protected static boolean matchPath(String pattern, String str, String separator) {
// When str starts with a separator, pattern has to start with a
// separator.
// When pattern starts with a separator, str has to start with a
// separator.
if (str.startsWith(separator) !=
pattern.startsWith(separator)) {
return false;
}
Vector patDirs = new Vector();
StringTokenizer st = new StringTokenizer(pattern,separator);
while (st.hasMoreTokens()) {
patDirs.addElement(st.nextToken());
}
Vector strDirs = new Vector();
st = new StringTokenizer(str,separator);
while (st.hasMoreTokens()) {
strDirs.addElement(st.nextToken());
}
int patIdxStart = 0;
int patIdxEnd = patDirs.size()-1;
int strIdxStart = 0;
int strIdxEnd = strDirs.size()-1;
// up to first '**'
while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) {
String patDir = (String)patDirs.elementAt(patIdxStart);
if (patDir.equals("**")) {
break;
}
if (!match(patDir,(String)strDirs.elementAt(strIdxStart))) {
return false;
}
patIdxStart++;
strIdxStart++;
}
if (strIdxStart > strIdxEnd) {
// String is exhausted
for (int i = patIdxStart; i <= patIdxEnd; i++) {
if (!patDirs.elementAt(i).equals("**")) {
return false;
}
}
return true;
} else {
if (patIdxStart > patIdxEnd) {
// String not exhausted, but pattern is. Failure.
return false;
}
}
// up to last '**'
while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) {
String patDir = (String)patDirs.elementAt(patIdxEnd);
if (patDir.equals("**")) {
break;
}
if (!match(patDir,(String)strDirs.elementAt(strIdxEnd))) {
return false;
}
patIdxEnd--;
strIdxEnd--;
}
if (strIdxStart > strIdxEnd) {
// String is exhausted
for (int i = patIdxStart; i <= patIdxEnd; i++) {
if (!patDirs.elementAt(i).equals("**")) {
return false;
}
}
return true;
}
while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) {
int patIdxTmp = -1;
for (int i = patIdxStart+1; i <= patIdxEnd; i++) {
if (patDirs.elementAt(i).equals("**")) {
patIdxTmp = i;
break;
}
}
if (patIdxTmp == patIdxStart+1) {
// '**/**' situation, so skip one
patIdxStart++;
continue;
}
// Find the pattern between padIdxStart & padIdxTmp in str between
// strIdxStart & strIdxEnd
int patLength = (patIdxTmp-patIdxStart-1);
int strLength = (strIdxEnd-strIdxStart+1);
int foundIdx = -1;
strLoop:
for (int i = 0; i <= strLength - patLength; i++) {
for (int j = 0; j < patLength; j++) {
String subPat = (String)patDirs.elementAt(patIdxStart+j+1);
String subStr = (String)strDirs.elementAt(strIdxStart+i+j);
if (!match(subPat,subStr)) {
continue strLoop;
}
}
foundIdx = strIdxStart+i;
break;
}
if (foundIdx == -1) {
return false;
}
patIdxStart = patIdxTmp;
strIdxStart = foundIdx+patLength;
}
for (int i = patIdxStart; i <= patIdxEnd; i++) {
if (!patDirs.elementAt(i).equals("**")) {
return false;
}
}
return true;
}
/**
* Matches a string against a pattern. The pattern contains two special
* characters:
* '*' which means zero or more characters,
* '?' which means one and only one character.
*
* @param pattern the (non-null) pattern to match against
* @param str the (non-null) string that must be matched against the
* pattern
*
* @return <code>true</code> when the string matches against the pattern,
* <code>false</code> otherwise.
*/
protected static boolean match(String pattern, String str) {
char[] patArr = pattern.toCharArray();
char[] strArr = str.toCharArray();
int patIdxStart = 0;
int patIdxEnd = patArr.length-1;
int strIdxStart = 0;
int strIdxEnd = strArr.length-1;
char ch;
boolean containsStar = false;
for (int i = 0; i < patArr.length; i++) {
if (patArr[i] == '*') {
containsStar = true;
break;
}
}
if (!containsStar) {
// No '*'s, so we make a shortcut
if (patIdxEnd != strIdxEnd) {
return false; // Pattern and string do not have the same size
}
for (int i = 0; i <= patIdxEnd; i++) {
ch = patArr[i];
if (ch != '?' && ch != strArr[i]) {
return false; // Character mismatch
}
}
return true; // String matches against pattern
}
if (patIdxEnd == 0) {
return true; // Pattern contains only '*', which matches anything
}
// Process characters before first star
while((ch = patArr[patIdxStart]) != '*' && strIdxStart <= strIdxEnd) {
if (ch != '?' && ch != strArr[strIdxStart]) {
return false;
}
patIdxStart++;
strIdxStart++;
}
if (strIdxStart > strIdxEnd) {
// All characters in the string are used. Check if only '*'s are
// left in the pattern. If so, we succeeded. Otherwise failure.
for (int i = patIdxStart; i <= patIdxEnd; i++) {
if (patArr[i] != '*') {
return false;
}
}
return true;
}
// Process characters after last star
while((ch = patArr[patIdxEnd]) != '*' && strIdxStart <= strIdxEnd) {
if (ch != '?' && ch != strArr[strIdxEnd]) {
return false;
}
patIdxEnd--;
strIdxEnd--;
}
if (strIdxStart > strIdxEnd) {
// All characters in the string are used. Check if only '*'s are
// left in the pattern. If so, we succeeded. Otherwise failure.
for (int i = patIdxStart; i <= patIdxEnd; i++) {
if (patArr[i] != '*') {
return false;
}
}
return true;
}
// process pattern between stars. padIdxStart and patIdxEnd point
// always to a '*'.
while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) {
int patIdxTmp = -1;
for (int i = patIdxStart+1; i <= patIdxEnd; i++) {
if (patArr[i] == '*') {
patIdxTmp = i;
break;
}
}
if (patIdxTmp == patIdxStart+1) {
// Two stars next to each other, skip the first one.
patIdxStart++;
continue;
}
// Find the pattern between padIdxStart & padIdxTmp in str between
// strIdxStart & strIdxEnd
int patLength = (patIdxTmp-patIdxStart-1);
int strLength = (strIdxEnd-strIdxStart+1);
int foundIdx = -1;
strLoop:
for (int i = 0; i <= strLength - patLength; i++) {
for (int j = 0; j < patLength; j++) {
ch = patArr[patIdxStart+j+1];
if (ch != '?' && ch != strArr[strIdxStart+i+j]) {
continue strLoop;
}
}
foundIdx = strIdxStart+i;
break;
}
if (foundIdx == -1) {
return false;
}
patIdxStart = patIdxTmp;
strIdxStart = foundIdx+patLength;
}
// All characters in the string are used. Check if only '*'s are left
// in the pattern. If so, we succeeded. Otherwise failure.
for (int i = patIdxStart; i <= patIdxEnd; i++) {
if (patArr[i] != '*') {
return false;
}
}
return true;
}
/**
* Sets the set of include patterns to use. All '/' and '\' characters are
* replaced by <code>File.separatorChar</code>. So the separator used need
* not match <code>File.separatorChar</code>.
* <p>
* When a pattern ends with a '/' or '\', "**" is appended.
*
* @param includes list of include patterns
*/
public void setIncludes(String[] includes) {
if (includes == null) {
this.includes = null;
} else {
this.includes = new String[includes.length];
for (int i = 0; i < includes.length; i++) {
String pattern;
pattern = includes[i].replace('/',getSeparatorChar()).
replace('\\',getSeparatorChar());
if (pattern.endsWith(getSeparator())) {
pattern += "**";
}
this.includes[i] = pattern;
}
}
}
/**
* Sets the set of exclude patterns to use. All '/' and '\' characters are
* replaced by <code>File.separatorChar</code>. So the separator used need
* not match <code>File.separatorChar</code>.
* <p>
* When a pattern ends with a '/' or '\', "**" is appended.
*
* @param excludes list of exclude patterns
*/
public void setExcludes(String[] excludes) {
if (excludes == null) {
this.excludes = null;
} else {
this.excludes = new String[excludes.length];
for (int i = 0; i < excludes.length; i++) {
String pattern;
pattern = excludes[i].replace('/',getSeparatorChar()).
replace('\\',getSeparatorChar());
if (pattern.endsWith(getSeparator())) {
pattern += "**";
}
this.excludes[i] = pattern;
}
}
}
/**
* Scans the base directory for files that match at least one include
* pattern, and don't match any exclude patterns.
*
* @exception IllegalStateException when basedir was set incorrecly
*/
public abstract void scan();
/**
* Tests whether a name matches against at least one include pattern.
*
* @param name the name to match
* @return <code>true</code> when the name matches against at least one
* include pattern, <code>false</code> otherwise.
*/
protected boolean isIncluded(String name) {
for (int i = 0; i < includes.length; i++) {
if (matchPath(includes[i],name,getSeparator())) {
return true;
}
}
return false;
}
/**
* Tests whether a name matches against at least one exclude pattern.
*
* @param name the name to match
* @return <code>true</code> when the name matches against at least one
* exclude pattern, <code>false</code> otherwise.
*/
protected boolean isExcluded(String name) {
for (int i = 0; i < excludes.length; i++) {
if (matchPath(excludes[i],name,getSeparator())) {
return true;
}
}
return false;
}
/**
* Get the names of the files that matched at least one of the include
* patterns, an matched none of the exclude patterns.
* The names are relative to the basedir.
*
* @return the names of the files
*/
public String[] getIncludedFiles() {
int count = filesIncluded.size();
String[] files = new String[count];
for (int i = 0; i < count; i++) {
files[i] = (String)filesIncluded.elementAt(i);
}
return files;
}
/**
* Get the names of the files that matched at none of the include patterns.
* The names are relative to the basedir.
*
* @return the names of the files
*/
public String[] getNotIncludedFiles() {
int count = filesNotIncluded.size();
String[] files = new String[count];
for (int i = 0; i < count; i++) {
files[i] = (String)filesNotIncluded.elementAt(i);
}
return files;
}
/**
* Get the names of the files that matched at least one of the include
* patterns, an matched also at least one of the exclude patterns.
* The names are relative to the basedir.
*
* @return the names of the files
*/
public String[] getExcludedFiles() {
int count = filesExcluded.size();
String[] files = new String[count];
for (int i = 0; i < count; i++) {
files[i] = (String)filesExcluded.elementAt(i);
}
return files;
}
/**
* Get the names of the directories that matched at least one of the include
* patterns, an matched none of the exclude patterns.
* The names are relative to the basedir.
*
* @return the names of the directories
*/
public String[] getIncludedDirectories() {
int count = dirsIncluded.size();
String[] directories = new String[count];
for (int i = 0; i < count; i++) {
directories[i] = (String)dirsIncluded.elementAt(i);
}
return directories;
}
/**
* Get the names of the directories that matched at none of the include
* patterns.
* The names are relative to the basedir.
*
* @return the names of the directories
*/
public String[] getNotIncludedDirectories() {
int count = dirsNotIncluded.size();
String[] directories = new String[count];
for (int i = 0; i < count; i++) {
directories[i] = (String)dirsNotIncluded.elementAt(i);
}
return directories;
}
/**
* Get the names of the directories that matched at least one of the include
* patterns, an matched also at least one of the exclude patterns.
* The names are relative to the basedir.
*
* @return the names of the directories
*/
public String[] getExcludedDirectories() {
int count = dirsExcluded.size();
String[] directories = new String[count];
for (int i = 0; i < count; i++) {
directories[i] = (String)dirsExcluded.elementAt(i);
}
return directories;
}
/**
* Adds the array with default exclusions to the current exclusions set.
*
*/
public void addDefaultExcludes() {
int excludesLength = excludes == null ? 0 : excludes.length;
String[] newExcludes;
newExcludes = new String[excludesLength + DEFAULTEXCLUDES.length];
if (excludesLength > 0) {
System.arraycopy(excludes,0,newExcludes,0,excludesLength);
}
for (int i = 0; i < DEFAULTEXCLUDES.length; i++) {
newExcludes[i+excludesLength] = DEFAULTEXCLUDES[i].replace('/',getSeparatorChar()).replace('\\',getSeparatorChar());
}
excludes = newExcludes;
}
protected abstract String getSeparator();
protected char getSeparatorChar() {
return ((getSeparator().length() > 0) ? getSeparator().charAt(0) : '/');
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/ant/taskdefs/Get.java
Index: Get.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.webdav.ant.taskdefs;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;
import org.apache.tools.ant.BuildException;
import org.apache.webdav.ant.Scanner;
import org.apache.webdav.ant.taskdefs.WebdavMatchingTask;
import org.apache.webdav.lib.Credentials;
import org.apache.webdav.lib.WebdavClient;
import org.apache.webdav.lib.WebdavException;
import org.apache.webdav.lib.methods.GetMethod;
/**
* Get a particular resource or collection of resources from a
* WebDAV-compliant web server. This task differs from the
* basic Get task in Ant because it allows regular expressions
* to be used.
*
* <p> To use this task, first you must it in your Ant build file:
*
* <PRE>
* <taskdef name="davget" classname="org.apache.webdav.ant.taskdefs.Get"/>
* </PRE>
*
* <p> Next, specify a specific target, such as:
*
* <PRE>
*
* <target name="download" depends="init">
* <davget baseurl="http://localhost/dav/" dest="." verbose="true">
* <include name="*.html"/>
* </davget>
* </target>
* <PRE>
*
* @author <a href="mailto:bcholmes@interlog.com">B.C. Holmes</a>
*/
public class Get extends WebdavMatchingTask {
private String baseURL = null; // required
private String dest = null; // required
private String userid = null;
private String password = null;
private boolean verbose = false;
String ignoreErrors=null;
/**
* Does the work.
*
* @exception BuildException Thrown in unrecovrable error.
*/
public void execute() throws BuildException {
try {
// first, is the destination directory valid?
File destDir = new File(dest);
if (!destDir.isDirectory()) {
throw new BuildException(
"Destination " + dest + " is not a valid directory");
}
// next, check the include list
if (includeList.size() == 0) {
throw new BuildException(
"Includes must be specified");
}
if ((this.userid != null && !this.userid.equals("")) &&
(this.password != null && !this.password.equals(""))) {
client.setCredentials(new Credentials(this.userid, this.password));
}
// validity check on the URL
URL url = new URL(baseURL);
client.startSession(url.getHost(),
(url.getPort() < 0 ? 80 : url.getPort()));
Scanner scanner = getScanner(url);
GetMethod getMethod = new GetMethod();
String[] resources = scanner.getIncludedFiles();
log("Downloading " + resources.length + " files from " + url);
for (int i = 0; i < resources.length; i++) {
String resource = resources[i];
String file = resource.replace('/',File.separatorChar);
file = concatenate(dest, file, File.separator);
FileOutputStream output = new FileOutputStream(file);
resource = concatenate(url.getFile(), resource, "/");
if (verbose) {
log("Getting: " + resource + " to " + file);
}
getMethod.setPath(resource);
client.executeMethod(getMethod);
InputStream input = getMethod.getData();
if( input == null ) {
throw new BuildException( "Can't get " + resource + " to " + file);
}
byte[] buffer = new byte[100 * 1024];
int length;
while ((length = input.read(buffer)) >= 0) {
output.write(buffer, 0, length);
}
output.close();
input.close();
getMethod.recycle();
}
client.endSession();
} catch (BuildException e) {
log(e.getMessage());
if( ignoreErrors == null ) {
throw e;
}
} catch (WebdavException e) {
throw new BuildException(e.toString());
} catch (MalformedURLException e) {
throw new BuildException(e.toString());
} catch (IOException e) {
if( ignoreErrors == null )
throw new BuildException(e.toString());
}
}
/**
* Set the base URL.
*
* @param base URL for the request.
*/
public void setBaseurl(String baseURL) {
if (baseURL.endsWith("/")) {
this.baseURL = baseURL;
} else {
this.baseURL = baseURL + "/";
}
}
/**
* Where to copy the source file.
*
* @param dest Path to file.
*/
public void setDest(String dest) {
this.dest = dest.replace('/',File.separatorChar)
.replace('\\',File.separatorChar);
}
/**
* Userid to access the resources
*
* @param userid - HTTP userid
*/
public void setUserid(String userid) {
this.userid = userid;
}
/**
* Password to access the resources
*
* @param password - HTTP password
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Be verbose, if set to "<CODE>true</CODE>".
*
* @param verbose if "true" then be verbose
*/
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
/**
* Don't stop if get fails if set to "<CODE>true</CODE>".
*
* @param ignoreErrors if "true" then be verbose
*/
public void setIgnoreErrors(String ignoreErrors) {
this.ignoreErrors = ignoreErrors;
}
protected String concatenate(String first, String second, String separator) {
if (first.endsWith(separator) && !second.startsWith(separator)) {
return first + second;
} else if (!first.endsWith(separator) && second.startsWith(separator)) {
return first + second;
} else if (!first.endsWith(separator) && !second.startsWith(separator)) {
return first + separator + second;
} else {
return first + second.substring(1);
}
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/ant/taskdefs/WebdavMatchingTask.java
Index: WebdavMatchingTask.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/ant/taskdefs/WebdavMatchingTask.java,v 1.1 2000/11/22 06:19:07 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:07 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.webdav.ant.taskdefs;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.webdav.ant.CollectionScanner;
import org.apache.webdav.ant.ScanException;
import org.apache.webdav.ant.Scanner;
import org.apache.webdav.lib.WebdavClient;
import org.apache.webdav.lib.WebdavException;
public abstract class WebdavMatchingTask extends Task { // ... extends MatchingTask {
// TODO: update for PatternSets, et al
protected WebdavClient client = new WebdavClient();
protected Vector includeList = new Vector();
protected Vector excludeList = new Vector();
protected boolean useDefaultExcludes = true;
/**
* Returns the collection scanner needed to access the resources to get.
*/
protected Scanner getScanner(URL baseURL) throws ScanException {
CollectionScanner scanner = new CollectionScanner();
scanner.setBaseURL(baseURL);
scanner.setIncludes(makeArray(includeList));
scanner.setExcludes(makeArray(excludeList));
scanner.setWebdavClient(client);
if (useDefaultExcludes) {
scanner.addDefaultExcludes();
}
scanner.scan();
return scanner;
}
/**
* provide access to properties from within the inner class
*/
protected String getProperty(String name) {
return project.getProperty(name);
}
/**
* inner class to hold a name on list. "If" and "Unless" attributes
* may be used to invalidate the entry based on the existence of a
* property (typically set thru the use of the Available task).
*/
public class NameEntry {
private boolean valid = true;
private String name;
public String getName() { return valid ? name : null; }
public void setName(String name) { this.name = name; }
public void setIf(String name) {
if (getProperty(name) == null) valid = false;
}
public void setUnless(String name) {
if (getProperty(name) != null) valid = false;
}
}
/**
* add a name entry on the include list
*/
public NameEntry createInclude() {
return addPatternToList(includeList);
}
/**
* add a name entry on the exclude list
*/
public NameEntry createExclude() {
return addPatternToList(excludeList);
}
/**
* Sets the set of include patterns. Patterns may be separated by a comma
* or a space.
*
* @param includes the string containing the include patterns
*/
public void setIncludes(String includes) {
if (includes != null && includes.length() > 0) {
createInclude().setName(includes);
}
}
/**
* Set this to be the items in the base directory that you want to be
* included. You can also specify "*" for the items (ie: items="*")
* and it will include all the items in the base directory.
*
* @param itemString the string containing the files to include.
*/
public void setItems(String itemString) {
log("The items attribute is deprecated. " +
"Please use the includes attribute.",
Project.MSG_WARN);
if (itemString == null || itemString.equals("*")
|| itemString.equals(".")) {
createInclude().setName("**");
} else {
StringTokenizer tok = new StringTokenizer(itemString, ", ");
while (tok.hasMoreTokens()) {
String pattern = tok.nextToken().trim();
if (pattern.length() > 0) {
createInclude().setName(pattern+"/**");
}
}
}
}
/**
* Sets the set of exclude patterns. Patterns may be separated by a comma
* or a space.
*
* @param excludes the string containing the exclude patterns
*/
public void setExcludes(String excludes) {
if (excludes != null && excludes.length() > 0) {
createExclude().setName(excludes);
}
}
/**
* List of filenames and directory names to not include. They should be
* either , or " " (space) separated. The ignored files will be logged.
*
* @param ignoreString the string containing the files to ignore.
*/
public void setIgnore(String ignoreString) {
log("The ignore attribute is deprecated." +
"Please use the excludes attribute.",
Project.MSG_WARN);
if (ignoreString != null && ignoreString.length() > 0) {
Vector tmpExcludes = new Vector();
StringTokenizer tok = new StringTokenizer(ignoreString, ", ", false);
while (tok.hasMoreTokens()) {
createExclude().setName("**/"+tok.nextToken().trim()+"/**");
}
}
}
/**
* Sets whether default exclusions should be used or not.
*
* @param useDefaultExcludes "true"|"on"|"yes" when default exclusions
* should be used, "false"|"off"|"no" when they
* shouldn't be used.
*/
public void setDefaultexcludes(String useDefaultExcludes) {
this.useDefaultExcludes = Project.toBoolean(useDefaultExcludes);
}
/**
* Convert a vector of NameEntry elements into an array of Strings.
*/
private String[] makeArray(Vector list) {
if (list.size() == 0) return null;
Vector tmpNames = new Vector();
for (Enumeration e = list.elements() ; e.hasMoreElements() ;) {
String includes = ((NameEntry)e.nextElement()).getName();
if (includes == null) continue;
StringTokenizer tok = new StringTokenizer(includes, ", ", false);
while (tok.hasMoreTokens()) {
String pattern = tok.nextToken().trim();
if (pattern.length() > 0) {
tmpNames.addElement(pattern);
}
}
}
String result[] = new String[tmpNames.size()];
for (int i = 0; i < tmpNames.size(); i++) {
result[i] = (String)tmpNames.elementAt(i);
}
return result;
}
/**
* add a name entry to the given list
*/
private NameEntry addPatternToList(Vector list) {
NameEntry result = new NameEntry();
list.addElement(result);
return result;
}
/**
* Reads path matching patterns from a file and adds them to the
* includes or excludes list (as appropriate).
*/
private void readPatterns(File patternfile, Vector patternlist) {
try {
// Get a FileReader
BufferedReader patternReader =
new BufferedReader(new FileReader(patternfile));
// Create one NameEntry in the appropriate pattern list for each
// line in the file.
String line = patternReader.readLine();
while (line != null) {
if (line.length() > 0) {
addPatternToList(patternlist).setName(line);
}
line = patternReader.readLine();
}
} catch(IOException ioe) {
log("An error occured while reading from pattern file: "
+ patternfile, Project.MSG_ERR);
}
}
/**
* Sets the name of the file containing the includes patterns.
*
* @param includesfile A string containing the filename to fetch
* the include patterns from.
*/
public void setIncludesfile(String includesfile) {
if (includesfile != null && includesfile.length() > 0) {
File incl = project.resolveFile(includesfile);
if (!incl.exists()) {
log("Includesfile "+includesfile+" not found.",
Project.MSG_ERR);
} else {
readPatterns(incl, includeList);
}
}
}
/**
* Sets the name of the file containing the includes patterns.
*
* @param excludesfile A string containing the filename to fetch
* the include patterns from.
*/
public void setExcludesfile(String excludesfile) {
if (excludesfile != null && excludesfile.length() > 0) {
File excl = project.resolveFile(excludesfile);
if (!excl.exists()) {
log("Excludesfile "+excludesfile+" not found.",
Project.MSG_ERR);
} else {
readPatterns(excl, excludeList);
}
}
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/cmd/Main.java
Index: Main.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/cmd/Main.java,v 1.1 2000/11/22 06:19:08 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:08 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.cmd;
import java.io.*;
import java.util.*;
import java.security.Principal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.net.Socket;
import java.net.UnknownHostException;
import org.apache.webdav.lib.*;
import org.apache.webdav.lib.methods.*;
/**
* Command line WebDAV client.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public class Main {
// --------------------------------------------------------- Public Methods
/**
* Main function.
*/
public static void main(String args[]) {
try {
String host = "127.0.0.1";
int port = 80;
WebdavClient client = new WebdavClient();
// Parsing host and port from command line
if (args.length >= 2) {
host = args[0];
port = Integer.parseInt(args[1]);
}
client.startSession(host, port);
// Set the credentials to use
Credentials credentials = new Credentials("root", "root");
client.setCredentials(credentials);
WebdavMethod method = new OptionsMethod();
method.setPath("/");
client.executeMethod(method);
System.out.println("Response :");
System.out.println("Status code : " + method.getStatusCode());
System.out.println("Status text : " + method.getStatusText());
/* GetMethod method2 = new GetMethod();
method2.setPath("/examples/servlet/HelloWorldExample");
method2.setUseDisk(false);
client.executeMethod(method2);
System.out.println("Response :");
System.out.println("Status code : " + method2.getStatusCode());
System.out.println("Status text : " + method2.getStatusText());
System.out.println("Contents :");
/*
is = method2.getData();
nb = 0;
while (true) {
nb = is.read(buffer);
if (nb == -1)
break;
System.out.println(new String(buffer, 0, nb));
}
is.close();
*/
//System.out.println(method2.getDataAsString());
PropPatchMethod method3 = new PropPatchMethod();
method3.setPath("/test");
method3.addPropertyToSet("password", "foo");
method3.addPropertyToSet("getlastmodified", "foo");
method3.addPropertyToRemove("getetag");
client.executeMethod(method3);
System.out.println("Response :");
System.out.println("Status code : " + method3.getStatusCode());
System.out.println("Status text : " + method3.getStatusText());
} catch (Throwable t) {
t.printStackTrace();
}
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/Authenticator.java
Index: Authenticator.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/Authenticator.java,v 1.1 2000/11/22 06:19:08 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:08 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib;
import java.io.IOException;
import java.util.*;
import org.apache.webdav.lib.util.*;
/**
* Authenticate helper.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public class Authenticator {
// ----------------------------------------------------- Instance Variables
/**
* Base 64 encoder.
*/
protected static Base64 base64 = new Base64();
// ------------------------------------------------------------- Properties
/**
* Generate a response to the given challenge.
*
* @param challenge Challenge
* @param credentials Credentials to use to answser the challenge
* @return String response to the challenge
*/
public static String challengeResponse(String challenge,
Credentials credentials)
throws WebdavException {
if (challenge.startsWith("Basic")) {
return basic(credentials);
} else if (challenge.startsWith("Digest")) {
// FIXME !
}
return null;
}
/**
* Generate a basic response.
*
* @param credentials Credentials to use to answser the challenge
*/
public static String basic(Credentials credentials) {
String authString = credentials.getUserName() + ":"
+ credentials.getPassword();
return "Basic " + new String(base64.encode(authString.getBytes()));
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/Cookie.java
Index: Cookie.java
===================================================================
/*
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib;
import java.io.Serializable;
import java.util.Date;
import java.util.Enumeration;
import java.util.Vector;
/**
* This class represents an http cookie as specified in RFC 2109.
*
*
* @author B.C. Holmes
*/
public class Cookie extends NameValuePair implements Serializable {
//
// member variables
//
protected String m_comment;
protected String m_domain;
protected Date m_expiryDate;
protected String m_path;
protected boolean m_secure;
// FIXME: JServ doesn't appear to explicitly set the version
protected int m_version = 1;
/**
* Create a cookie.
*
* @param name the cookie name
* @param value the cookie value
* @param domain the host this cookie will be sent to
* @param path the path prefix for which this cookie will be sent
* @param maxAge the Date this cookie expires, null if the cookie
* expires at the end of the session
* @param secure if true this cookie will only be over secure connections
* @exception NullPointerException if <var>name</var>, <var>value</var> or
* <var>domain</var> is null
* @since V0.3-1
*/
public Cookie(String domain, String name, String value) {
super(name, value);
if (name == null) throw new NullPointerException("missing name");
if (value == null) throw new NullPointerException("missing value");
if (domain == null) throw new NullPointerException("missing domain");
this.m_domain = domain.toLowerCase();
}
/**
* Returns the comment describing the purpose of this cookie, or
* null if no such comment has been defined.
*
* @see setComment
*/
public String getComment() {
return m_comment;
}
/**
* If a user agent (web browser) presents this cookie to a user, the
* cookie's purpose will be described using this comment.
*
* @see getComment
*/
public void setComment(String comment) {
m_comment = comment;
}
/**
* @return the expiry date of this cookie, or null if none set.
*/
public Date getExpiryDate() {
return m_expiryDate;
}
public void setExpiryDate (Date expiryDate) {
m_expiryDate = expiryDate;
}
/**
* @return true if the cookie should be discarded at the end of the
* session; false otherwise
*/
public boolean isToBeDiscarded() {
return (m_expiryDate != null);
}
/**
* Returns the domain of this cookie.
*
* @see setDomain
*/
public String getDomain() {
return m_domain;
}
/**
* This cookie should be presented only to hosts satisfying this domain
* name pattern. Read RFC 2109 for specific details of the syntax.
* Briefly, a domain name name begins with a dot (".foo.com") and means
* that hosts in that DNS zone ("www.foo.com", but not "a.b.foo.com")
* should see the cookie. By default, cookies are only returned to
* the host which saved them.
*
* @see getDomain
*/
public void setDomain (String domain) {
m_domain = domain.toLowerCase();
}
/**
* Return the path this cookie is associated with.
*/
public String getPath() {
return m_path;
}
/**
* This cookie should be presented only with requests beginning with this URL.
* Read RFC 2109 for a specification of the default behaviour. Basically, URLs
* in the same "directory" as the one which set the cookie, and in subdirectories,
* can all see the cookie unless a different path is set.
*/
public void setPath(String path) {
m_path = path;
}
/**
* Return whether this cookie should only be sent over secure connections.
*/
public boolean getSecure() {
return m_secure;
}
/**
* Indicates to the user agent that the cookie should only be sent
* using a secure protocol (https). This should only be set when
* the cookie's originating server used a secure protocol to set the
* cookie's value.
*
* @see getSecure
*/
public void setSecure (boolean secure) {
m_secure = secure;
}
public int getVersion() {
return m_version;
}
public void setVersion(int version) {
m_version = version;
}
/**
* @return true if this cookie has expired
*/
public boolean isExpired() {
return (m_expiryDate != null && m_expiryDate.getTime() <= System.currentTimeMillis());
}
/**
* Hash up name, path and domain into new hash.
*/
public int hashCode() {
return (super.hashCode() + m_path.hashCode() + m_domain.hashCode());
}
/**
* Two cookies match if the name, path and domain match.
*/
public boolean equals(Object obj) {
if ((obj != null) && (obj instanceof Cookie)) {
Cookie other = (Cookie) obj;
return (this.getName().equals(other.getName()) &&
this.m_path.equals(other.m_path) &&
this.m_domain.equals(other.m_domain));
}
return false;
}
/**
* @return a string suitable for sending in a Cookie header.
*/
public String toExternalForm() {
String string = getName() + "=" + getValue();
if (m_path != null) {
string += "; $Path=" + m_path;
}
string += "; $Domain=" + m_domain;
return string;
}
public static Header createCookieHeader(String domain,
String path, Vector cookies) {
domain = domain.toLowerCase();
StringBuffer value = new StringBuffer("$Version=1");
// FIXME: cookies are supposed to be ordered with "better"
// matches first
for (Enumeration e = cookies.elements(); e.hasMoreElements(); ) {
Cookie cookie = (Cookie) e.nextElement();
if (domain.endsWith(cookie.getDomain()) &&
((cookie.getPath() == null) ||
(path.startsWith(cookie.getPath())))) {
value.append(";");
value.append(cookie.toExternalForm());
}
}
return new Header("cookie", value.toString());
}
public String toString() {
String string = toExternalForm();
if (m_secure) {
string += "; secure";
}
return string;
}
/**
* Parses the Set-Cookie header into an array of Cookies.
*
* <P>The syntax for the Set-Cookie response header is:
*
* <PRE>
* set-cookie = "Set-Cookie:" cookies
* cookies = 1#cookie
* cookie = NAME "=" VALUE * (";" cookie-av)
* NAME = attr
* VALUE = value
* cookie-av = "Comment" "=" value
* | "Domain" "=" value
* | "Max-Age" "=" value
* | "Path" "=" value
* | "Secure"
* | "Version" "=" 1*DIGIT
* </PRE>
*
* @param domain the domain
* @param setCookie the Set-Cookie header received from the server
* @return an array of Cookies as parsed from the Set-Cookie header
* @exception WebdavException if an error occurs during parsing
*/
protected static Cookie[] parse(String domain, Header setCookie)
throws WebdavException {
HeaderElement[] headerElements =
HeaderElement.parse(setCookie.getValue());
Cookie[] cookies = new Cookie[headerElements.length];
int index = 0;
for (int i = 0; i < headerElements.length; i++) {
if (headerElements[i].getValue() == null)
throw new WebdavException(
"Bad Set-Cookie header: " + setCookie.getValue() +
"\nMissing value " + "for cookie '" +
headerElements[i].getName() + "'");
Cookie cookie = new Cookie(domain,
headerElements[i].getName(),
headerElements[i].getValue());
// cycle through the parameters
NameValuePair[] parameters = headerElements[i].getParameters();
boolean discard_set = false, secure_set = false;
for (int j = 0; j < parameters.length; j++) {
String name = parameters[j].getName().toLowerCase();
// check for required value parts
if ( (name.equals("version") || name.equals("max-age") ||
name.equals("domain") || name.equals("path") ||
name.equals("comment")) &&
parameters[j].getValue() == null) {
throw new WebdavException(
"Bad Set-Cookie header: " + setCookie.getValue() +
"\nMissing value for " +
parameters[j].getName() +
" attribute in cookie '" +
headerElements[i].getName() + "'");
}
if (name.equals("version")) {
try {
cookie.setVersion(
Integer.parseInt(parameters[j].getValue()));
} catch (NumberFormatException nfe) {
throw new WebdavException(
"Bad Set-Cookie header: " +
setCookie.getValue() + "\nVersion '" +
parameters[j].getValue() + "' not a number");
}
} else if (name.equals("path")) {
cookie.setPath(parameters[j].getValue());
} else if (name.equals("domain")) {
String d = parameters[j].getValue().toLowerCase();
// add leading dot if not present and if domain is
// not the full host name
if (d.charAt(0) != '.' && !d.equals(domain))
cookie.setDomain("." + d);
else
cookie.setDomain(d);
} else if (name.equals("max-age")) {
int age;
try {
age = Integer.parseInt(parameters[j].getValue());
} catch (NumberFormatException e) {
throw new WebdavException(
"Bad Set-Cookie header: " +
setCookie.getValue() + "\nMax-Age '" +
parameters[j].getValue() + "' not a number");
}
cookie.setExpiryDate(new Date(System.currentTimeMillis() +
age * 1000L));
} else if (name.equals("secure")) {
cookie.setSecure(true);
} else if (name.equals("comment")) {
cookie.setComment(parameters[j].getValue());
}
}
// check version
if (cookie.getVersion() != 1) {
throw new WebdavException(
"Bad Set-Cookie header: " + setCookie.getValue() +
"\nIllegal Version attribute");
}
// security check... we musn't allow the server to give us an
// invalid domain scope
// domain must be either .local or must contain at least two dots
if (!cookie.getDomain().equals("localhost")) {
// must have at least two dots
if ((cookie.getDomain().indexOf('.') ==
cookie.getDomain().lastIndexOf('.'))) {
throw new WebdavException(
"Bad Set-Cookie header: " + setCookie.getValue() +
"\nIllegal domain attribute" + cookie.getDomain());
}
// domain must domain match host
if (!domain.endsWith(cookie.getDomain())){
throw new WebdavException(
"Bad Set-Cookie header: " + setCookie.getValue() +
"\nIllegal domain attribute" + cookie.getDomain());
}
// host minus domain may not contain any dots
if (domain.substring(0,
domain.length() -
cookie.getDomain().length()).indexOf('.') != -1) {
throw new WebdavException(
"Bad Set-Cookie header: " + setCookie.getValue() +
"\nIllegal domain attribute" + cookie.getDomain());
}
}
// looks ok
cookies[index++] = cookie;
}
return cookies;
}
public static void main(String[] args) {
// let's test this class
try {
String headerValue = "custno = 12345; comment=test; version=1," +
" name=John; version=1; max-age=600; secure; domain=.apache.org";
Cookie[] cookies = Cookie.parse("www.apache.org", new Header("set-cookie", headerValue));
for (int i = 0; i < cookies.length; i++) {
System.out.println("name =>" + cookies[i].getName());
System.out.println("value=>" + cookies[i].getValue());
System.out.println("domain =>" + cookies[i].getDomain());
System.out.println("secure =>" + cookies[i].getSecure());
System.out.println("version=>" + cookies[i].getVersion());
System.out.println("comment=>" + cookies[i].getComment());
if (cookies[i].isToBeDiscarded()) {
System.out.println("expires =>" + cookies[i].getExpiryDate());
System.out.println("expired =>" + cookies[i].isExpired());
}
}
} catch (Exception exception) {
System.out.println(exception);
}
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/Credentials.java
Index: Credentials.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/Credentials.java,v 1.1 2000/11/22 06:19:08 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:08 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib;
/**
* Credentials class.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public class Credentials {
// ----------------------------------------------------------- Constructors
/**
* Default constructor.
*/
public Credentials() {
}
/**
* Constructor.
*/
public Credentials(String userName, String password) {
this.userName = userName;
this.password = password;
}
// ----------------------------------------------------- Instance Variables
/**
* UserName.
*/
protected String userName;
/**
* Password.
*/
protected String password;
// ------------------------------------------------------------- Properties
/**
* UserName property setter.
*
* @param userName
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* UserName property getter.
*
* @return String userName
*/
public String getUserName() {
return userName;
}
/**
* Password property setter.
*
* @param password
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Password property getter.
*
* @return String password
*/
public String getPassword() {
return password;
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/Header.java
Index: Header.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/Header.java,v 1.1 2000/11/22 06:19:08 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:08 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib;
import java.io.IOException;
import java.util.*;
import java.security.Principal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* Header class.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public class Header {
// ----------------------------------------------------------- Constructors
/**
* Default constructor.
*/
public Header() {
}
/**
* Constructor.
*/
public Header(String name, String value) {
this.name = name;
this.value = value;
}
// ----------------------------------------------------- Instance Variables
/**
* Name.
*/
protected String name;
/**
* Value.
*/
protected String value;
// ------------------------------------------------------------- Properties
/**
* Name property setter.
*
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* Name property getter.
*
* @return String name
*/
public String getName() {
return name;
}
/**
* Value property setter.
*
* @param value
*/
public void setValue(String value) {
this.value = value;
}
/**
* Value property getter.
*
* @return String value
*/
public String getValue() {
return value;
}
// --------------------------------------------------------- Public Methods
/**
* Get a String representation of the header.
*/
public String toString() {
return (name + ": " + value + "\r\n");
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/HeaderElement.java
Index: HeaderElement.java
===================================================================
/*
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib;
import java.util.BitSet;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.Vector;
/**
* Some HTTP headers (such as the set-cookie header) have values that
* can be decomposed into multiple elements. Such headers must be in the
* following form:
*
* <PRE>
* header = [ element ] *( "," [ element ] )
* element = name [ "=" [ value ] ] *( ";" [ param ] )
* param = name [ "=" [ value ] ]
*
* name = token
* value = ( token | quoted-string )
*
* token = 1*<any char except "=", ",", ";", <"> and
* white space>
* quoted-string = <"> *( text | quoted-char ) <">
* text = any char except <">
* quoted-char = "\" char
* </PRE>
*
* <P> Any amount of white space is allowed between any part of the
* header, element or param and is ignored. A missing value in any
* element or param will be stored as the empty string; if the "="
* is also missing <var>null</var> will be stored instead.
*
* <P> This class represents an individual header element. This
* class also has a <CODE>parse()</CODE> method for parsing a header
* value into an array of elements.
*
* @author <a href="mailto:bcholmes@interlog.com">B.C. Holmes</a>
*/
public class HeaderElement extends NameValuePair {
// ----------------------------------------------------------- Constructors
/**
* Default constructor.
*/
public HeaderElement() {
super();
}
/**
* Constructor.
*/
public HeaderElement(String name, String value) {
super(name, value);
}
/**
* Constructor.
*/
public HeaderElement(String name, String value,
NameValuePair[] parameters) {
super(name, value);
this.parameters = parameters;
}
// -------------------------------------------------------- Class Variables
private static final BitSet SEPARATORS = new BitSet(128);
private static final BitSet TOKEN_CHAR = new BitSet(128);
private static final BitSet UNSAFE_CHAR = new BitSet(128);
static {
// rfc-2068 tspecial
SEPARATORS.set('(');
SEPARATORS.set(')');
SEPARATORS.set('<');
SEPARATORS.set('>');
SEPARATORS.set('@');
SEPARATORS.set(',');
SEPARATORS.set(';');
SEPARATORS.set(':');
SEPARATORS.set('\\');
SEPARATORS.set('"');
SEPARATORS.set('/');
SEPARATORS.set('[');
SEPARATORS.set(']');
SEPARATORS.set('?');
SEPARATORS.set('=');
SEPARATORS.set('{');
SEPARATORS.set('}');
SEPARATORS.set(' ');
SEPARATORS.set('\t');
// rfc-2068 token
for (int ch = 32; ch < 127; ch++) {
TOKEN_CHAR.set(ch);
}
TOKEN_CHAR.xor(SEPARATORS);
// rfc-1738 unsafe characters, including CTL and SP, and excluding
// "#" and "%"
for (int ch = 0; ch < 32; ch++) {
UNSAFE_CHAR.set(ch);
}
UNSAFE_CHAR.set(' ');
UNSAFE_CHAR.set('<');
UNSAFE_CHAR.set('>');
UNSAFE_CHAR.set('"');
UNSAFE_CHAR.set('{');
UNSAFE_CHAR.set('}');
UNSAFE_CHAR.set('|');
UNSAFE_CHAR.set('\\');
UNSAFE_CHAR.set('^');
UNSAFE_CHAR.set('~');
UNSAFE_CHAR.set('[');
UNSAFE_CHAR.set(']');
UNSAFE_CHAR.set('`');
UNSAFE_CHAR.set(127);
}
// ----------------------------------------------------- Instance Variables
/**
* Name.
*/
protected NameValuePair[] parameters = null;
// ------------------------------------------------------------- Properties
public NameValuePair[] getParameters() {
return this.parameters;
}
// --------------------------------------------------------- Public Methods
/**
* This parses the value part of a header. The result is an array of
* HeaderElement objects.
*
* @param headerValue the string representation of the header value
* (as received from the web server).
* @return a Vector containing <var>Header</var> elements.
* @exception WebdavException if the above syntax rules are violated.
*/
public final static HeaderElement[] parse(String headerValue)
throws WebdavException
{
if (headerValue == null)
return null;
Vector elements = new Vector();
StringTokenizer tokenizer =
new StringTokenizer(headerValue.trim(), ",");
while (tokenizer.countTokens() > 0) {
String nextToken = tokenizer.nextToken();
// careful... there may have been a comma in a quoted string
try {
while (HeaderElement.hasOddNumberOfQuotationMarks(
nextToken)) {
nextToken += "," + tokenizer.nextToken();
}
} catch (NoSuchElementException exception) {
throw new WebdavException(
"Bad header format: wrong number of quotation marks");
}
String tmp = nextToken.trim();
if (!tmp.endsWith(";")) {
tmp += ";";
}
char[] header = tmp.toCharArray();
boolean inAString = false;
int startPos = 0;
HeaderElement element = new HeaderElement();
Vector parameters = new Vector();
for (int i = 0 ; i < header.length ; i++) {
if (header[i] == ';' && !inAString) {
NameValuePair pair = parsePair(header, startPos, i);
if (pair == null) {
throw new WebdavException(
"Bad header format: empty name/value pair in" +
nextToken);
// the first name/value pair are handled differently
} else if (startPos == 0) {
element.setName(pair.getName());
element.setValue(pair.getValue());
} else {
parameters.addElement(pair);
}
startPos = i + 1;
} else if (header[i] == '"' &&
!(inAString && i > 0 && header[i-1] == '\\')) {
inAString = !inAString;
}
}
// now let's add all the parameters into the header element
if (parameters.size() > 0) {
NameValuePair[] tmp2 = new NameValuePair[parameters.size()];
tmp2 = (NameValuePair[]) parameters.toArray(tmp2);
element.parameters = tmp2;
parameters.clear();
}
// and save the header element into the list of header elements
elements.addElement(element);
}
HeaderElement[] headerElements = new HeaderElement[elements.size()];
headerElements = (HeaderElement[]) elements.toArray(headerElements);
return headerElements;
}
private final static boolean hasOddNumberOfQuotationMarks(String string) {
boolean odd = false;
int start = -1;
while ((start = string.indexOf('"', start+1)) != -1) {
odd = !odd;
}
return false;
}
private final static NameValuePair parsePair(char[] header, int start, int end)
throws WebdavException {
boolean done = false;
NameValuePair pair = null;
String name = new String(header, start, end - start).trim();
String value = null;
int index = name.indexOf("=");
if (index >= 0) {
if ((index + 1) < name.length()) {
value = name.substring(index+1).trim();
// strip quotation marks
if (value.startsWith("\"") && value.endsWith("\"")) {
value = value.substring(1,value.length()-1);
}
// is there anything left?
if (value.length() == 0) {
value = null;
}
}
name = name.substring(0,index).trim();
}
if (name != null && name.length() > 0) {
pair = new NameValuePair(name, value);
}
return pair;
}
public static void main(String[] args) {
// let's test this class
try {
String headerValue = "name1 = value1; name2; name3=\"value3\" , name4=value4; " +
"name5=value5, name6= ; name7 = value7; name8 = \" name8\"";
HeaderElement[] elements = HeaderElement.parse(headerValue);
for (int i = 0; i < elements.length; i++) {
System.out.println("name =>" + elements[i].getName());
System.out.println("value=>" + elements[i].getValue());
if (elements[i].parameters != null) {
for (int j = 0; j < elements[i].parameters.length; j++) {
System.out.println("parameter name =>" + elements[i].parameters[j].getName());
System.out.println("parameter value=>" + elements[i].parameters[j].getValue());
}
}
}
} catch (Exception exception) {
System.out.println(exception);
}
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/NameValuePair.java
Index: NameValuePair.java
===================================================================
/*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib;
import java.io.Serializable;
/**
* Simple Name Value Pair class.
*
* @author <a href="mailto:bcholmes@interlog.com">B.C. Holmes</a>
*/
public class NameValuePair implements Serializable {
// ----------------------------------------------------------- Constructors
/**
* Default constructor.
*/
public NameValuePair() {
}
/**
* Constructor.
*/
public NameValuePair(String name, String value) {
this.name = name;
this.value = value;
}
// ----------------------------------------------------- Instance Variables
/**
* Name.
*/
protected String name = null;
/**
* Value.
*/
protected String value = null;
// ------------------------------------------------------------- Properties
/**
* Name property setter.
*
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* Name property getter.
*
* @return String name
*/
public String getName() {
return name;
}
/**
* Value property setter.
*
* @param value
*/
public void setValue(String value) {
this.value = value;
}
/**
* Value property getter.
*
* @return String value
*/
public String getValue() {
return value;
}
// --------------------------------------------------------- Public Methods
/**
* Get a String representation of the header.
*/
public String toString() {
return ("name=" + name + ", " + "value=" + value);
}
public boolean equals(Object object) {
if (this == object) {
return true;
} else if (this.getClass().equals(object.getClass())) {
NameValuePair pair = (NameValuePair) object;
return (this.name.equals(pair.name) &&
this.value.equals(pair.value));
} else {
return false;
}
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/Property.java
Index: Property.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/Property.java,v 1.1 2000/11/22 06:19:08 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:08 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib;
import org.w3c.dom.Element;
public interface Property {
public String getName();
public Element getElement();
public String getPropertyAsString();
public int getStatusCode();
public String getOwningURL();
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/RequestOutputStream.java
Index: RequestOutputStream.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/RequestOutputStream.java,v 1.1 2000/11/22 06:19:08 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:08 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib;
import java.io.OutputStream;
import java.io.IOException;
import java.util.Hashtable;
/**
* Socket output stream wrapper.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
* @version $Revision: 1.1 $ $Date: 2000/11/22 06:19:08 $
*/
public class RequestOutputStream
extends OutputStream {
// ----------------------------------------------------------- Constructors
/**
* Construct an output stream associated with the specified headers.
*
* @param stream Wrapped input stream
*/
public RequestOutputStream(OutputStream stream) {
super();
this.stream = stream;
}
// ----------------------------------------------------- Instance Variables
/**
* Has this stream been closed?
*/
protected boolean closed = false;
/**
* The underlying input stream from which we should read data.
*/
protected OutputStream stream = null;
/**
* True if chunking is allowed.
*/
private boolean useChunking = false;
/**
* True if printing a chunk.
*/
private boolean writingChunk = false;
// ------------------------------------------------------------- Properties
/**
* Use chunking flag setter.
*/
public void setUseChunking(boolean useChunking) {
this.useChunking = useChunking;
}
/**
* Use chunking flag getter.
*/
public boolean isUseChunking() {
return useChunking;
}
// --------------------------------------------------------- Public Methods
/**
* Writes a <code>String</code> to the client,
* without a carriage return-line feed (CRLF)
* character at the end.
*
* @param s the <code>String</code to send to the client
* @exception IOException if an input or output exception occurred
*/
public void print(String s) throws IOException {
if (s == null)
s = "null";
int len = s.length();
for (int i = 0; i < len; i++) {
write(s.charAt(i));
}
}
/**
* Writes a carriage return-line feed (CRLF)
* to the client.
*
* @exception IOException if an input or output exception occurred
*/
public void println() throws IOException {
print("\r\n");
}
/**
* Writes a <code>String</code> to the client,
* followed by a carriage return-line feed (CRLF).
*
* @param s the </code>String</code> to write to the client
* @exception IOException if an input or output exception occurred
*/
public void println(String s) throws IOException {
print(s);
println();
}
// -------------------------------------------- ServletOutputStream Methods
/**
* Write the specified byte to our output stream.
*
* @param b The byte to be written
*
* @exception IOException if an input/output error occurs
*/
public void write(int b)
throws IOException {
if (useChunking && !writingChunk) {
writingChunk = true;
print("1\r\n");
stream.write(b);
println();
writingChunk = false;
} else {
stream.write(b);
}
}
/**
* Write the specified byte array.
*/
public void write(byte[] b, int off, int len)
throws IOException {
if (useChunking && !writingChunk) {
writingChunk = true;
print(Integer.toHexString(len) + "\r\n");
stream.write(b, off, len);
println();
writingChunk = false;
} else {
stream.write(b, off, len);
}
}
/**
* Close this output stream, causing any buffered data to be flushed and
* any further output data to throw an IOException.
*/
public void close() throws IOException {
if (useChunking) {
// Write the final chunk.
writingChunk = true;
print("0\r\n\r\n");
writingChunk = false;
}
super.close();
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/ResponseInputStream.java
Index: ResponseInputStream.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/ResponseInputStream.java,v 1.1 2000/11/22 06:19:08 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:08 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib;
import java.io.InputStream;
import java.io.IOException;
import java.util.Hashtable;
/**
* Socket input stream wrapper.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
* @version $Revision: 1.1 $ $Date: 2000/11/22 06:19:08 $
*/
public class ResponseInputStream
extends InputStream {
// ----------------------------------------------------------- Constructors
/**
* Construct a servlet input stream associated with the specified Request.
*
* @param request The associated request
*/
public ResponseInputStream(InputStream stream, Hashtable responseHeaders) {
super();
closed = false;
count = 0;
// Retrieving transfer encoding header
Header transferEncoding =
(Header) responseHeaders.get("transfer-encoding");
if ((transferEncoding != null)
&& (transferEncoding.getValue().indexOf("chunked") != -1))
chunk = true;
// Retrieving content length header
Header contentLength =
(Header) responseHeaders.get("content-length");
if (contentLength != null) {
try {
length = Integer.parseInt(contentLength.getValue());
} catch (NumberFormatException e) {
}
}
this.stream = stream;
}
// ----------------------------------------------------- Instance Variables
/**
* Has this stream been closed?
*/
protected boolean closed = false;
/**
* Use chunking ?
*/
protected boolean chunk = false;
/**
* True if the final chunk was found.
*/
protected boolean endChunk = false;
/**
* Chunk buffer.
*/
protected byte[] chunkBuffer = null;
/**
* Chunk length.
*/
protected int chunkLength = 0;
/**
* Chunk buffer position.
*/
protected int chunkPos = 0;
/**
* The number of bytes which have already been returned by this stream.
*/
protected int count = 0;
/**
* The content length past which we will not read, or -1 if there is
* no defined content length.
*/
protected int length = -1;
/**
* The underlying input stream from which we should read data.
*/
protected InputStream stream = null;
// --------------------------------------------------------- Public Methods
/**
* Close this input stream. No physical level I-O is performed, but
* any further attempt to read from this stream will throw an IOException.
* If a content length has been set but not all of the bytes have yet been
* consumed, the remaining bytes will be swallowed.
*/
public void close()
throws IOException {
/*
// Xerces appears to doubly-close the input stream...
if (closed)
throw new IOException("Stream is already closed");
*/
if (!closed) {
if (chunk) {
while (!endChunk) {
int b = read();
if (b < 0)
break;
}
} else {
if (length > 0) {
while (count < length) {
int b = read();
if (b < 0)
break;
}
}
}
closed = true;
}
}
/**
* Read and return a single byte from this input stream, or -1 if end of
* file has been encountered.
*
* @exception IOException if an input/output error occurs
*/
public int read()
throws IOException {
// Has this stream been closed?
if (closed)
throw new IOException("Stream is closed");
if (endChunk)
return (-1);
if (chunk) {
if ((chunkBuffer == null)
|| (chunkPos == chunkLength)) {
chunkPos = 0;
try {
chunkLength = Integer.parseInt(readLine(), 16);
} catch (NumberFormatException e) {
// Critical error, unable to parse the chunk length
chunkLength = 0;
chunk = false;
close();
return -1;
}
if (chunkLength == 0) {
// TODO : Parse the trailing headers, if any
readLine();
endChunk = true;
return (-1);
// TODO : Should the stream be automatically closed ?
} else {
if ((chunkBuffer == null)
|| (chunkLength > chunkBuffer.length))
chunkBuffer = new byte[chunkLength];
// Now read the whole chunk into the buffer
int nbRead = 0;
int currentRead = 0;
while (nbRead < chunkLength) {
currentRead =
stream.read(chunkBuffer, nbRead,
chunkLength - nbRead);
if (currentRead == -1)
throw new IOException("Unexpected end of stream");
nbRead += currentRead;
}
// Skipping the CRLF
stream.read();
stream.read();
}
}
return (chunkBuffer[chunkPos++]);
} else {
// Have we read the specified content length already?
if ((length >= 0) && (count >= length))
return (-1); // End of file indicator
// Read and count the next byte, then return it
int b = stream.read();
if (b >= 0)
count++;
return (b);
}
}
// -------------------------------------------------------- Private Methods
/**
* Reads the input stream, one line at a time. Reads bytes into an array,
* until it reads a certain number of bytes or reaches a newline character,
* which it reads into the array as well.
*
* @param input Input stream on which the bytes are read
* @return The line that was read, or <code>null</code> if end-of-file
* was encountered
* @exception IOException if an input or output exception has occurred
*/
private String readLine()
throws IOException {
StringBuffer sb = new StringBuffer();
while (true) {
int ch = stream.read();
if (ch < 0) {
if (sb.length() == 0) {
return (null);
} else {
break;
}
} else if (ch == '\r') {
continue;
} else if (ch == '\n') {
break;
}
sb.append((char) ch);
}
return (sb.toString());
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/State.java
Index: State.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/State.java,v 1.1 2000/11/22 06:19:08 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:08 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib;
import java.io.IOException;
import java.util.*;
/**
* Session state.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public class State {
// ----------------------------------------------------- Instance Variables
/**
* Lock tokens.
*/
protected Hashtable lockTokens = new Hashtable();
/**
* Authenticate token.
*/
protected String authenticateToken = null;
/**
* Cookies.
*/
protected Vector cookies = new Vector();
// ------------------------------------------------------------- Properties
/**
* Add a cookie
*/
public void addCookie(Cookie cookie) {
if (cookie != null) {
boolean found = false;
// let's remove the cookie if it's already saved
for (Enumeration e = cookies.elements();
!found && e.hasMoreElements(); ) {
Cookie tmp = (Cookie) e.nextElement();
if (cookie.getDomain().equals(tmp.getDomain()) &&
cookie.getName().equals(tmp.getName())) {
found = true;
cookies.remove(tmp);
}
}
cookies.addElement(cookie);
}
}
/**
* Add a number of cookies
*/
public void addCookies(Cookie[] cookies) {
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
this.addCookie(cookies[i]);
}
}
}
// FIXME: this breaks encapsulation on the cookie vector
public Vector getCookies() {
return cookies;
}
/**
* Add a lock token.
*
* @param uri Uri
* @param value Lock token value
*/
public void addLock(String uri, String value) {
Vector currentLocks = (Vector) lockTokens.get(uri);
if (currentLocks == null)
currentLocks = new Vector();
currentLocks.addElement(value);
lockTokens.put(uri, currentLocks);
}
/**
* Remove a lock.
*
* @param uri Uri
* @param value LockToken value
*/
public void removeLock(String uri, String value) {
Vector currentLocks = (Vector) lockTokens.get(uri);
if (currentLocks == null)
return;
currentLocks.removeElement(value);
}
/**
* Remove locks.
*
* @param uri Uri
*/
public void removeLocks(String uri) {
lockTokens.remove(uri);
}
/**
* Get locks
*
* @param uri Uri
* @return Enumeration of lock tokens
*/
public Enumeration getLocks(String uri) {
Vector result = (Vector) lockTokens.get(uri);
if (result == null)
result = new Vector();
return result.elements();
}
/**
* Authenticate token setter.
*
* @param authenticateToken Authenticate token
*/
public void setAuthenticateToken(String authenticateToken) {
this.authenticateToken = authenticateToken;
}
/**
* Authenticate token accessor.
*
* @return String authenticate token
*/
public String getAuthenticateToken() {
return authenticateToken;
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/WebdavClient.java
Index: WebdavClient.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/WebdavClient.java,v 1.1 2000/11/22 06:19:08 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:08 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.security.Principal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.net.Socket;
import java.net.UnknownHostException;
import org.apache.webdav.lib.methods.WebdavMethod;
/**
* WebDAV client.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public class WebdavClient {
// -------------------------------------------------------------- Constants
/**
* HTTP Date format pattern (RFC 2068, 822, 1123).
*/
public static final String DATE_FORMAT = "EEE, d MMM yyyy kk:mm:ss z";
/**
* User Agent.
*/
public static final Header USER_AGENT =
new Header("user-agent", "org.apache.webdav.lib.WebdavClient");
/**
* Date formatter.
*/
protected static final DateFormat formatter =
new SimpleDateFormat(DATE_FORMAT);
// ----------------------------------------------------- Instance Variables
/**
* Client Socket in use.
*/
protected Socket socket;
/**
* Session state.
*/
protected State state;
/**
* Credentials to use.
*/
protected Credentials credentials;
/**
* Socket input stream.
*/
protected InputStream input;
/**
* Socket output stream.
*/
protected OutputStream output;
/**
* The host name specified when the startSession(host, port) method was
* called.
*/
protected String sessionHost = "";
/**
* port number
*/
protected int sessionPort = -1;
// ------------------------------------------------------------- Properties
/**
* Set the socket to use.
*/
public void setSocket(Socket socket) {
this.socket = socket;
}
/**
* Set the credentials to use.
*/
public void setCredentials(Credentials credentials) {
this.credentials = credentials;
}
// --------------------------------------------------------- Public Methods
/**
* Execute a DAV method.
*
* @param method WebDAV method to execute
*/
public void executeMethod(WebdavMethod method)
throws IOException, WebdavException {
int authRetries = 0;
Hashtable responseHeaders = null;
openConnection();
while ( (authRetries == 0) ||
((method.getStatusCode() == WebdavStatus.SC_UNAUTHORIZED)
&& (authRetries < 3)) ) {
sendRequest(method);
// Parsing response
// Parse status line
parseStatusLine(readLine(input), method);
// Parse headers
responseHeaders = parseHeaders(input);
// Retrieve the authenticate challenge, if any
// (needed in case of a digest challenge, for which the header is
// not constant)
Header authenticateChallenge =
(Header) responseHeaders.get("www-authenticate");
if (authenticateChallenge != null) {
state.setAuthenticateToken(authenticateChallenge.getValue());
}
authRetries++;
}
if (authRetries == 3) {
throw new WebdavException("Unable to authenticate");
}
method.processResponseHeaders(responseHeaders);
// Parse response
ResponseInputStream responseInputStream =
new ResponseInputStream(input, responseHeaders);
method.parseResponse(responseInputStream);
method.setUsed();
responseInputStream.close();
closeConnection();
}
/**
* Start a session.
*/
public void startSession()
throws IOException {
state = new State();
this.sessionHost = "localhost";
this.sessionPort = 80;
}
/**
* Start a session.
*/
public void startSession(String host, int port)
throws UnknownHostException, IOException {
state = new State();
socket = new Socket(host, port);
/*
// we want to separate the notion of "session" and "connection"
// FIXME: Figure out how HTTP/1.1 support works
socket = new Socket(host, port);
input = socket.getInputStream();
output = socket.getOutputStream();
*/
this.sessionHost = host;
this.sessionPort = port;
}
/**
* End a session.
*/
public void endSession()
throws IOException {
state = null;
this.sessionHost = "";
this.sessionPort = -1;
/*
// Close socket
input.close();
output.close();
socket.close();
*/
}
// -------------------------------------------------------- Private Methods
private void openConnection() throws IOException, UnknownHostException {
socket = new Socket(this.sessionHost, this.sessionPort);
input = socket.getInputStream();
output = socket.getOutputStream();
}
private void closeConnection() throws IOException {
// Close socket
input.close();
output.close();
socket.close();
}
/**
* Send a WebDAV request.
*
* @param method WebDAV method to execute
*/
private void sendRequest(WebdavMethod method)
throws IOException, WebdavException {
if (method.hasBeenUsed())
throw new WebdavException("Method has already been used");
if (!method.validate())
throw new WebdavException("Invalid method");
String requestLine = method.generateRequestLine();
method.generateHeaders(sessionHost, state);
Enumeration headersList = method.getHeaders();
// Sending request line
output.write(requestLine.getBytes());
// Sending headers
String query = null;
if (!method.isStreamedQuery()) {
query = method.generateQuery();
if (query == null)
query = new String();
output.write(("Content-Length: "
+ query.length() + "\r\n").getBytes());
} else {
// Chunking
output.write(("Transfer-Encoding: chunked\r\n").getBytes());
}
if (state.getAuthenticateToken() != null) {
String challengeResponse = Authenticator.challengeResponse
(state.getAuthenticateToken(), credentials);
output.write(("Authorization: "
+ challengeResponse + "\r\n").getBytes());
}
// Writing HTTP headers
while (headersList.hasMoreElements()) {
output.write(headersList.nextElement().toString().getBytes());
}
output.write("\r\n".getBytes());
// Writing request body
RequestOutputStream requestOutputStream =
new RequestOutputStream(output);
if (method.isStreamedQuery()) {
requestOutputStream.setUseChunking(true);
method.streamQuery(requestOutputStream);
} else {
requestOutputStream.write(query.getBytes());
}
// Closing wrapped output stream
requestOutputStream.close();
}
/**
* Reads the input stream, one line at a time. Reads bytes into an array,
* until it reads a certain number of bytes or reaches a newline character,
* which it reads into the array as well.
*
* @param input Input stream on which the bytes are read
* @return The line that was read, or <code>null</code> if end-of-file
* was encountered
* @exception IOException if an input or output exception has occurred
*/
private String readLine(InputStream input)
throws IOException {
StringBuffer sb = new StringBuffer();
while (true) {
int ch = input.read();
if (ch < 0) {
if (sb.length() == 0) {
return (null);
} else {
break;
}
} else if (ch == '\r') {
continue;
} else if (ch == '\n') {
break;
}
sb.append((char) ch);
}
return (sb.toString());
}
/**
* Parse status line.
*
* @param statusLine String representing the HTTP status line
* @param method Webdav method
*/
private void parseStatusLine(String statusLine, WebdavMethod method)
throws IOException, WebdavException {
StringTokenizer st = new StringTokenizer(statusLine);
String protocol = null;
try {
protocol = st.nextToken();
} catch (NoSuchElementException e) {
}
if ((protocol == null) ||
(!protocol.equals("HTTP/1.1") && !protocol.equals("HTTP/1.0")))
throw new WebdavException("Incorrect server protocol : "
+ protocol);
int statusCode = -1;
try {
statusCode = Integer.parseInt(st.nextToken());
} catch (Exception e) {
}
if (statusCode == -1)
throw new WebdavException("Status not specified");
method.setStatusCode(statusCode);
String statusText = null;
try {
statusText = st.nextToken();
} catch (NoSuchElementException e) {
}
if (statusText != null)
method.setStatusText(statusText);
}
/**
* Parse headers.
*
* @param input Input stream on which the bytes are read
*/
private Hashtable parseHeaders(InputStream input)
throws IOException, WebdavException {
Hashtable result = new Hashtable();
while (true) {
// Read the next header line
String line = readLine(input);
if ((line == null) || (line.length() < 1))
break;
// Parse the header name and value
int colon = line.indexOf(":");
if (colon < 0)
throw new WebdavException("Incorrect headers");
String name = line.substring(0, colon).trim();
String match = name.toLowerCase();
String value = line.substring(colon + 1).trim();
Header header = new Header(match, value);
result.put(match, header);
}
// should we set cookies?
Header header = (Header) result.get("set-cookie2");
// if the server doesn't support new cookies,
// we'll use the old cookies
if (header == null) {
header = (Header) result.get("set-cookie");
}
if (header != null) {
Cookie[] cookies = Cookie.parse(sessionHost, header);
state.addCookies(cookies);
}
return result;
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/WebdavException.java
Index: WebdavException.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/WebdavException.java,v 1.1 2000/11/22 06:19:08 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:08 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib;
/**
* Webdav exception class.
*/
public class WebdavException
extends Exception {
// ----------------------------------------------------------- Constructors
/**
* Constructor.
*
* @param message Exception message
*/
public WebdavException(String message) {
super(message);
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/WebdavStatus.java
Index: WebdavStatus.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/WebdavStatus.java,v 1.1 2000/11/22 06:19:08 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:08 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Enumeration;
import java.util.NoSuchElementException;
/**
* 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.
*
* @see WebDavRetCode
* @author Marc Eaddy
* @version 1.0, 16 Nov 1997
*/
public class WebdavStatus {
/**
* 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();
/**
* 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);
}
/**
* 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)) {
// DANGER!!! - RECURSIVE!!!
return getStatusText(SC_INTERNAL_SERVER_ERROR);
} else {
return (String) mapStatusCodes.get(intKey);
}
}
/*
* HTTP 1.0 Server status codes; see RFC 1945.
*/
/**
* 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;
/*
* HTTP 1.1 Server status codes; see RFC 2048. When JWS supports HTTP 1.1 we
* will use the appropriate HttpServletRespones status codes.
*/
/**
* 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 HTTP status codes; see <draft-ietf-webdav-protocol-05>.
*/
/**
* 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;
static {
// HTTP 1.0 Server status codes -- see RFC 1945
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");
// HTTP 1.1 Server status codes -- see RFC 2048
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 Server-specific 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");
}
};
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/CopyMethod.java
Index: CopyMethod.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/CopyMethod.java,v 1.1 2000/11/22 06:19:09 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:09 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib.methods;
import java.io.*;
import java.util.*;
import org.apache.webdav.lib.State;
import org.apache.webdav.lib.Header;
import org.apache.webdav.lib.WebdavStatus;
/**
* COPY Method.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public class CopyMethod
extends WebdavMethodBase {
// ----------------------------------------------------------- Constructors
/**
* Method constructor.
*/
public CopyMethod() {
name = "COPY";
}
// ----------------------------------------------------- Instance Variables
/**
* Destination.
*/
private String destination;
/**
* Overwrite.
*/
private boolean overwrite = true;
// ----------------------------------------------------- Instance Variables
/**
* Destination setter.
*
* @param destination New destination value
*/
public void setDestination(String destination) {
this.destination = destination;
}
/**
* Destination getter.
*
* @return String destination value
*/
public String getDestination() {
return destination;
}
/**
* Overwrite setter.
*
* @param overwrite New overwrite value
*/
public void setOverwrite(boolean overwrite) {
this.overwrite = overwrite;
}
/**
* Overwrite getter.
*
* @return boolean Overwrite value
*/
public boolean isOverwrite() {
return overwrite;
}
/**
* Overwrite getter.
*
* @return boolean Overwrite value
*/
public boolean getOverwrite() {
return overwrite;
}
// --------------------------------------------------- WebdavMethod Methods
/**
* Generate additional headers needed by the request.
*
* @param state State token
*/
public void generateHeaders(State state) {
super.generateHeaders(state);
setHeader("Destination", destination);
if (!isOverwrite())
setHeader("Overwrite", "F");
}
/**
* Generate the query body.
*
* @return String query
*/
public String generateQuery() {
return null;
}
/**
* Parse response.
*
* @param is Input stream
*/
public void parseResponse(InputStream is)
throws IOException {
// Parse the 207 error report
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/DeleteMethod.java
Index: DeleteMethod.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/DeleteMethod.java,v 1.1 2000/11/22 06:19:09 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:09 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib.methods;
import java.io.*;
import java.util.*;
import org.apache.webdav.lib.State;
import org.apache.webdav.lib.Header;
import org.apache.webdav.lib.WebdavStatus;
/**
* DELETE Method.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public class DeleteMethod
extends WebdavMethodBase {
// ----------------------------------------------------------- Constructors
/**
* Method constructor.
*/
public DeleteMethod() {
name = "DELETE";
}
// --------------------------------------------------- WebdavMethod Methods
/**
* Generate the query body.
*
* @return String query
*/
public String generateQuery() {
return null;
}
/**
* Parse response.
*
* @param is Input stream
*/
public void parseResponse(InputStream is)
throws IOException {
// We have to parse the multistatus error report if status = 207
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/GetMethod.java
Index: GetMethod.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/GetMethod.java,v 1.1 2000/11/22 06:19:09 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:09 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib.methods;
import java.io.*;
import java.util.*;
import org.apache.webdav.lib.State;
import org.apache.webdav.lib.Header;
import org.apache.webdav.lib.WebdavStatus;
/**
* GET Method.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public class GetMethod
extends WebdavMethodBase {
// -------------------------------------------------------------- Constants
/**
* Temporary directory.
*/
public static final String TEMP_DIR = "temp/";
// ----------------------------------------------------------- Constructors
/**
* Method constructor.
*/
public GetMethod() {
name = "GET";
}
// ----------------------------------------------------- Instance Variables
/**
* By default, the get method will buffer read data to the disk.
*/
private boolean useDisk = true;
/**
* If we're not using the HD, we're using a memory byte buffer.
*/
private byte[] memoryData;
/**
* File which contains the buffered data.
*/
private File fileData;
// ------------------------------------------------------------- Properties
/**
* Use disk setter.
*
* @param useDisk New value of useDisk
*/
public void setUseDisk(boolean useDisk) {
this.useDisk = useDisk;
}
/**
* Use disk getter.
*
* @param boolean useDisk value
*/
public boolean getUseDisk() {
return useDisk;
}
// --------------------------------------------------------- Public Methods
/**
* Get read data.
*/
public InputStream getData()
throws IOException {
if (useDisk) {
return new FileInputStream(fileData);
} else {
if (memoryData == null)
throw new IOException("Data not found");
return new ByteArrayInputStream(memoryData);
}
}
/**
* Get read data as a String.
*/
public String getDataAsString()
throws IOException {
if (useDisk) {
InputStream is = new FileInputStream(fileData);
byte[] buffer = new byte[4096];
ByteArrayOutputStream os = new ByteArrayOutputStream();
int nb = 0;
while (true) {
nb = is.read(buffer);
if (nb == -1)
break;
os.write(buffer, 0, nb);
}
is.close();
return os.toString();
} else {
if (memoryData != null)
return new String(memoryData);
else
return "";
}
}
// --------------------------------------------------- WebdavMethod Methods
/**
* Generate the query body.
*
* @return String query
*/
public String generateQuery() {
return null;
}
/**
* Parse response.
*
* @param is Input stream
*/
public void parseResponse(InputStream is)
throws IOException {
OutputStream out = null;
if (useDisk) {
// Create a temporary file on the HD
File tempDir = new File(TEMP_DIR);
tempDir.mkdirs();
String tempFileName = TEMP_DIR + getPath().hashCode() + ".tmp";
fileData = new File(tempFileName);
out = new FileOutputStream(fileData);
} else {
out = new ByteArrayOutputStream();
}
byte[] buffer = new byte[4096];
int nb = 0;
while (true) {
nb = is.read(buffer);
if (nb == -1)
break;
if (out == null)
throw new IOException("Unable to buffer data");
out.write(buffer, 0, nb);
}
if (!useDisk)
memoryData = ((ByteArrayOutputStream) out).toByteArray();
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/HeadMethod.java
Index: HeadMethod.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/HeadMethod.java,v 1.1 2000/11/22 06:19:09 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:09 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib.methods;
import java.io.*;
import java.util.*;
import org.apache.webdav.lib.State;
import org.apache.webdav.lib.Header;
import org.apache.webdav.lib.WebdavStatus;
/**
* HEAD Method.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public class HeadMethod
extends WebdavMethodBase {
// ----------------------------------------------------------- Constructors
/**
* Method constructor.
*/
public HeadMethod() {
name = "HEAD";
}
// --------------------------------------------------- WebdavMethod Methods
/**
* Generate the query body.
*
* @return String query
*/
public String generateQuery() {
return null;
}
/**
* Parse response.
*
* @param is Input stream
*/
public void parseResponse(InputStream is)
throws IOException {
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/LockMethod.java
Index: LockMethod.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/LockMethod.java,v 1.1 2000/11/22 06:19:09 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:09 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib.methods;
import java.io.*;
import java.util.*;
import org.apache.webdav.lib.State;
import org.apache.webdav.lib.Header;
import org.apache.webdav.lib.WebdavStatus;
/**
* LOCK Method.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public class LockMethod
extends WebdavMethodBase {
// ----------------------------------------------------------- Constructors
/**
* Method constructor.
*/
public LockMethod() {
name = "LOCK";
}
// --------------------------------------------------- WebdavMethod Methods
/**
* Generate the query body.
*
* @return String query
*/
public String generateQuery() {
return null;
}
/**
* Parse response.
*
* @param is Input stream
*/
public void parseResponse(InputStream is)
throws IOException {
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/MkcolMethod.java
Index: MkcolMethod.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/MkcolMethod.java,v 1.1 2000/11/22 06:19:09 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:09 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib.methods;
import java.io.InputStream;
import java.io.IOException;
/**
* The MKCOL method is used to create a new collection. All DAV compliant
* resources must support the MKCOL method. Collections are merely
* the HTTP name for structures like directories or folders (and, in
* fact, often map directly to a folder or directory on the web server.
*
* <p> This implementation of a MKCOL client method does not support a
* a request body, and the newly created web collection should therefore
* have no members.
*
* <p> MKCOL creates a new collection resource at the location specified by
* the Request-URI. If the resource identified by the Request-URI already
* exists on the server then the MKCOL will fail. During MKCOL processing,
* a server will make the Request-URI a member of the URI's parent collection
* (unless the Request-URI is "/"). If no parent collection exists, the method
* will fail. Thus, for example, if a request to create collection
* <code>/a/b/c/d/</code> is made, and neither <code>/a/b/</code> nor
* <code>/a/b/c/</code> exists, the request will fail.
*
* <p> MKCOL is not idempotent (that is to say, each MKCOL request should
* be handled by the web server, and the results of a MKCOL request should
* not be cached).
*
* <h3>Example Request</h3>
* <pre>
* MKCOL /webdisc/xfiles/ HTTP/1.1
* Host: www.server.org
* </pre>
*
* <h3>Example Response</h3>
* <pre>
* HTTP/1.1 201 Created
* </pre>
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public class MkcolMethod
extends WebdavMethodBase {
// ----------------------------------------------------------- Constructors
/**
* Method constructor.
*/
public MkcolMethod() {
name = "MKCOL";
}
// --------------------------------------------------- WebdavMethod Methods
/**
* Parse the response body. The MKCOL method does not receive a response
* body.
*
* @param is Input stream
*/
public void parseResponse(InputStream is)
throws IOException {
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/MoveMethod.java
Index: MoveMethod.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/MoveMethod.java,v 1.1 2000/11/22 06:19:09 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:09 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib.methods;
import java.io.*;
import java.util.*;
import org.apache.webdav.lib.State;
import org.apache.webdav.lib.Header;
import org.apache.webdav.lib.WebdavStatus;
/**
* MOVE Method.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public class MoveMethod
extends WebdavMethodBase {
// ----------------------------------------------------------- Constructors
/**
* Method constructor.
*/
public MoveMethod() {
name = "MOVE";
}
// ----------------------------------------------------- Instance Variables
/**
* Destination.
*/
private String destination;
/**
* Overwrite.
*/
private boolean overwrite = true;
// ------------------------------------------------------------- Properties
/**
* Destination setter.
*
* @param destination New destination value
*/
public void setDestination(String destination) {
this.destination = destination;
}
/**
* Destination getter.
*
* @return String destination value
*/
public String getDestination() {
return destination;
}
/**
* Overwrite setter.
*
* @param overwrite New overwrite value
*/
public void setOverwrite(boolean overwrite) {
this.overwrite = overwrite;
}
/**
* Overwrite getter.
*
* @return boolean Overwrite value
*/
public boolean isOverwrite() {
return overwrite;
}
/**
* Overwrite getter.
*
* @return boolean Overwrite value
*/
public boolean getOverwrite() {
return overwrite;
}
// --------------------------------------------------- WebdavMethod Methods
/**
* Generate additional headers needed by the request.
*
* @param state State token
*/
public void generateHeaders(State state) {
super.generateHeaders(state);
setHeader("Destination", destination);
if (!isOverwrite())
setHeader("Overwrite", "F");
}
/**
* Generate the query body.
*
* @return String query
*/
public String generateQuery() {
return null;
}
/**
* Parse response.
*
* @param is Input stream
*/
public void parseResponse(InputStream is)
throws IOException {
// Parse the 207 error report
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/OptionsMethod.java
Index: OptionsMethod.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/OptionsMethod.java,v 1.1 2000/11/22 06:19:09 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:09 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib.methods;
import java.io.*;
import java.util.*;
import org.apache.webdav.lib.State;
import org.apache.webdav.lib.Header;
import org.apache.webdav.lib.WebdavStatus;
/**
* OPTIONS Method.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public class OptionsMethod
extends WebdavMethodBase {
// -------------------------------------------------------------- Constants
/**
* DAV level 1. Mandatory.
*/
public static final String DAV_LEVEL1 = "1";
/**
* DAV level 2.
*/
public static final String DAV_LEVEL2 = "2";
/**
* Advanced collections.
*/
public static final String ADVANCED_COLLECTIONS = "3";
/**
* Delta V.
*/
public static final String DELTAV = "4";
/**
* ACL.
*/
public static final String ACL = "5";
/**
* DASL.
*/
public static final String DASL = "6";
// ----------------------------------------------------------- Constructors
/**
* Method constructor.
*/
public OptionsMethod() {
name = "OPTIONS";
}
// ----------------------------------------------------- Instance Variables
/**
* DAV Capabilities.
*/
private Vector davCapabilities = new Vector();
/**
* Methods allowed.
*/
private Vector methodsAllowed = new Vector();
// --------------------------------------------------------- Public Methods
/**
* Is the specified method allowed ?
*/
public boolean isAllowed(String method) {
return methodsAllowed.contains(method);
}
/**
* Get a list of allowed methods.
*/
public Enumeration getAllowedMethods() {
return methodsAllowed.elements();
}
/**
* Is DAV capability supported ?
*/
public boolean isSupported(String capability) {
return davCapabilities.contains(capability);
}
/**
* Get a list of supported DAV capabilities.
*/
public Enumeration getDavCapabilities() {
return davCapabilities.elements();
}
// --------------------------------------------------- WebdavMethod Methods
/**
* Generate the query body.
*
* @return String query
*/
public String generateQuery() {
return null;
}
/**
* Parse response.
*
* @param is Input stream
*/
public void parseResponse(InputStream is)
throws IOException {
}
/**
* Process response headers. The contract of this method is that it only
* parses the response headers.
*
* @param headers Headers list
*/
public void processResponseHeaders(Hashtable headers) {
Header davHeader = (Header) headers.get("dav");
if (davHeader != null) {
String davHeaderValue = davHeader.getValue();
StringTokenizer tokenizer =
new StringTokenizer(davHeaderValue, ",");
while (tokenizer.hasMoreElements()) {
String davCapability = tokenizer.nextToken().trim();
davCapabilities.addElement(davCapability);
}
}
Header allowHeader = (Header) headers.get("allow");
if (allowHeader != null) {
String allowHeaderValue = allowHeader.getValue();
StringTokenizer tokenizer =
new StringTokenizer(allowHeaderValue, ",");
while (tokenizer.hasMoreElements()) {
String methodAllowed =
tokenizer.nextToken().trim().toUpperCase();
methodsAllowed.addElement(methodAllowed);
}
}
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/PostMethod.java
Index: PostMethod.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/PostMethod.java,v 1.1 2000/11/22 06:19:09 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:09 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib.methods;
import java.io.*;
import java.util.*;
import org.apache.webdav.lib.State;
import org.apache.webdav.lib.Header;
import org.apache.webdav.lib.WebdavStatus;
/**
* POST Method.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public class PostMethod
extends WebdavMethodBase {
// ----------------------------------------------------------- Constructors
/**
* Method constructor.
*/
public PostMethod() {
name = "POST";
}
// --------------------------------------------------- WebdavMethod Methods
/**
* Generate the query body.
*
* @return String query
*/
public String generateQuery() {
return null;
}
/**
* Parse response.
*
* @param is Input stream
*/
public void parseResponse(InputStream is)
throws IOException {
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/PropFindMethod.java
Index: PropFindMethod.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/PropFindMethod.java,v 1.1 2000/11/22 06:19:09 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:09 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib.methods;
import java.io.InputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import org.apache.webdav.lib.State;
import org.apache.webdav.lib.Header;
import org.apache.webdav.lib.Property;
import org.apache.webdav.lib.WebdavStatus;
import org.apache.webdav.lib.util.DOMUtils;
import org.apache.webdav.lib.util.DOMWriter;
import org.apache.webdav.lib.util.WebdavXMLPrinter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* This class implements the WebDAV PROPFIND Method.
*
* <P> The PROPFIND method retrieves properties defined on the resource
* identified by the Request-URI, if the resource does not have any internal
* members, or on the resource identified by the Request-URI and potentially
* its member resources, if the resource is a collection that has internal
* member URIs.
*
* <P> A typical request looks like this:
*
* <PRE>
*
* PROPFIND /file HTTP/1.1
* Host: www.foo.bar
* Content-type: text/xml; charset="utf-8"
* Content-Length: xxxx
*
* <?xml version="1.0" encoding="utf-8" ?>
* <D:propfind xmlns:D="DAV:">
* <D:prop xmlns:R="http://www.foo.bar/boxschema/">
* <R:bigbox/>
* <R:author/>
* <R:DingALing/>
* <R:Random/>
* </D:prop>
* </D:propfind>
* </PRE>
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public class PropFindMethod
extends PropMethodBase {
// -------------------------------------------------------------- Constants
/**
* Request of named properties.
*/
public static final int BY_NAME = 0;
/**
* Request of all properties name and value.
*/
public static final int ALL = 1;
/**
* Request of all properties name.
*/
public static final int NAMES = 2;
/**
* Request with depth infinity.
*/
public static final int DEPTH_INFINITY = -1;
/**
* Request with depth 0.
*/
public static final int DEPTH_0 = 0;
/**
* Request with depth 1.
*/
public static final int DEPTH_1 = 1;
// ----------------------------------------------------------- Constructors
/**
* Method constructor.
*/
public PropFindMethod() {
name = "PROPFIND";
}
// ----------------------------------------------------- Instance Variables
/**
* Type of the Propfind.
*/
private int type = ALL;
/**
* Property name list.
*/
private Enumeration propertyNames;
/**
* Depth.
*/
private int depth = DEPTH_INFINITY;
/**
* Hashtable of response nodes
*/
private Hashtable responseHashtable = null;
// ------------------------------------------------------------- Properties
/**
* Type setter.
*
* @param type New type value
*/
public void setType(int type) {
this.type = type;
}
/**
* Type getter.
*
* @return int type value
*/
public int getType() {
return type;
}
/**
* Depth setter.
*
* @param depth New depth value
*/
public void setDepth(int depth) {
this.depth = depth;
}
/**
* Depth getter.
*
* @return int depth value
*/
public int getDepth() {
return depth;
}
/**
* Property names setter.
*
* @param propertyNames List of the property names
*/
public void setPropertyNames(Enumeration propertyNames) {
this.propertyNames = propertyNames;
}
/**
* The namespace abbreviation that prefixes DAV tags
*/
private String prefix = null;
// --------------------------------------------------- WebdavMethod Methods
public void recycle() {
super.recycle();
prefix = null;
responseHashtable = null;
}
/**
* Generate additional headers needed by the request.
*
* @param host the host
* @param state State token
*/
public void generateHeaders(String host, State state) {
super.generateHeaders(host, state);
switch (depth) {
case DEPTH_0:
setHeader("Depth", "0");
break;
case DEPTH_1:
setHeader("Depth", "1");
break;
case DEPTH_INFINITY:
setHeader("Depth", "infinity");
break;
}
}
/**
* Generate the query body.
*
* @return String query
*/
public String generateQuery() {
WebdavXMLPrinter printer = new WebdavXMLPrinter();
printer.writeElement("D", "DAV", "propfind", WebdavXMLPrinter.OPENING);
switch (type) {
case ALL:
printer.writeElement("D", "allprop", WebdavXMLPrinter.NO_CONTENT);
break;
case NAMES:
printer.writeElement("D", "propname",
WebdavXMLPrinter.NO_CONTENT);
break;
case BY_NAME:
printer.writeElement("D", "prop", WebdavXMLPrinter.OPENING);
while (propertyNames.hasMoreElements()) {
String propertyName = (String) propertyNames.nextElement();
printer.writeElement(null, propertyName,
WebdavXMLPrinter.NO_CONTENT);
}
printer.writeElement("D", "prop", WebdavXMLPrinter.CLOSING);
break;
}
printer.writeElement("D", "DAV", "propfind", WebdavXMLPrinter.CLOSING);
return printer.toString();
}
public Enumeration getAllResponseURLs() {
return getResponseHashtable().keys();
}
protected Hashtable getResponseHashtable() {
if (responseHashtable == null) {
initResponseHashtable();
}
return responseHashtable;
}
protected synchronized void initResponseHashtable() {
if (responseHashtable == null) {
responseHashtable = new Hashtable();
Element multistatus = getResponseDocument().getDocumentElement();
NodeList hrefList = multistatus.getElementsByTagName(
getPrefix() + "href");
if (hrefList != null) {
for (int i = 0; i < hrefList.getLength(); i++) {
try {
Element child = (Element) hrefList.item(i);
String href = DOMUtils.getTextValue(child);
Element response = (Element) child.getParentNode();
responseHashtable.put(href, response);
} catch (ClassCastException e) {
}
}
}
}
}
public Enumeration getResponseProperties(String urlPath) {
Vector vector = new Vector();
try {
Element response = (Element) getResponseHashtable().get(urlPath);
if (response != null) {
NodeList list = response.getElementsByTagName(
getPrefix() + "prop");
for (int i = 0; i < list.getLength(); i++) {
try {
Element prop = (Element) list.item(i);
NodeList subList = prop.getChildNodes();
for (int j = 0; j < subList.getLength(); j++) {
try {
vector.add(new PropertyImpl(
getPrefix(), (Element) subList.item(j)));
} catch (ClassCastException e) {
}
}
} catch (ClassCastException e) {
}
}
}
} catch (ClassCastException e) {
}
return vector.elements();
}
protected String getPrefix() {
if (prefix == null) {
prefix = DOMUtils.findDavPrefix(getResponseDocument());
}
return prefix;
}
// --------------------------------------------------- Property Inner Class
class PropertyImpl implements Property {
PropertyImpl(String prefix, Element element) {
this.element = element;
this.prefix = prefix;
}
private String prefix;
private Element element;
public String getName() {
return element.getTagName();
}
public Element getElement() {
return element;
}
public String getPropertyAsString() {
return DOMUtils.getTextValue(element);
}
public int getStatusCode() {
int status = -1;
try {
Element propstat = (Element) element.getParentNode().getParentNode();
NodeList statusList = propstat.getElementsByTagName(prefix + "status");
if (statusList != null && statusList.getLength() != 1) {
// ????
} else {
try {
Element child = (Element) statusList.item(0);
status = DOMUtils.parseStatus(DOMUtils.getTextValue(child));
} catch (ClassCastException e) {
}
}
} catch (ClassCastException e) {
}
return status;
}
public String getOwningURL() {
return null;
}
public String toString () {
StringWriter tmp = new StringWriter();
DOMWriter domWriter = new DOMWriter(tmp, true);
domWriter.print(element);
return tmp.getBuffer().toString();
}
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/PropMethodBase.java
Index: PropMethodBase.java
===================================================================
/*
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib.methods;
import java.io.InputStream;
import java.io.IOException;
import java.util.Enumeration;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.webdav.lib.WebdavStatus;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class PropMethodBase
extends WebdavMethodBase {
// ----------------------------------------------------- Instance Variables
/**
* Response document
*/
private Document responseDocument = null;
// ------------------------------------------------------------- Properties
/**
* Response document getter.
*
* @return Document response document
*/
public Document getResponseDocument() {
return this.responseDocument;
}
// --------------------------------------------------- WebdavMethod Methods
/**
* Parse response.
*
* @param input Input stream
*/
public void parseResponse(InputStream input)
throws IOException {
// Parse the 207 response.
if (getStatusCode() == WebdavStatus.SC_MULTI_STATUS) {
try {
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
responseDocument = builder.parse(new InputSource(input));
} catch (ParserConfigurationException e) {
// throw new IllegalArgumentException("XML Parser Configuration error", e);
} catch (SAXException e) {
throw new IllegalArgumentException(
"XML parsing error; input is not valid XML: " +
e.getMessage());
}
}
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/PropPatchMethod.java
Index: PropPatchMethod.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/PropPatchMethod.java,v 1.1 2000/11/22 06:19:09 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:09 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib.methods;
import java.io.*;
import java.util.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.webdav.lib.State;
import org.apache.webdav.lib.Header;
import org.apache.webdav.lib.WebdavStatus;
import org.apache.webdav.lib.util.WebdavXMLPrinter;
/**
* PROPPATCH Method.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public class PropPatchMethod
extends PropMethodBase {
// ----------------------------------------------------------- Constructors
/**
* Method constructor.
*/
public PropPatchMethod() {
name = "PROPPATCH";
}
// ----------------------------------------------------- Instance Variables
/**
* Hashtable of the properties to set.
*/
protected Hashtable toSet = new Hashtable();
/**
* Hashtable of the properties to remove.
*/
protected Hashtable toRemove = new Hashtable();
// --------------------------------------------------------- Public Methods
/**
* Add a new property to set.
*
* @param name Property name
* @param value Property value
*/
public void addPropertyToSet(String name, String value) {
Property propertyToSet = new Property();
if (name != null) {
propertyToSet.name = name;
if (value != null)
propertyToSet.value = value;
else
propertyToSet.value = "";
toSet.put(name, propertyToSet);
}
}
/**
* Add a new property to set.
*
* @param name Property name
* @param value Property value
* @param namespace Namespace abbreviation
* @param namespaceInfo Namespace information
*/
public void addPropertyToSet(String name, String value, String namespace,
String namespaceInfo) {
Property propertyToSet = new Property();
if (name != null) {
propertyToSet.name = name;
if (value != null)
propertyToSet.value = value;
else
propertyToSet.value = "";
propertyToSet.namespace = namespace;
propertyToSet.namespaceInfo = namespaceInfo;
toSet.put(namespace + ":" + name, propertyToSet);
}
}
/**
* Add property to remove.
*
* @param name Property name
*/
public void addPropertyToRemove(String name) {
Property propertyToRemove = new Property();
if (name != null) {
propertyToRemove.name = name;
toRemove.put(name, propertyToRemove);
}
}
/**
* Add property to remove.
*
* @param name Property name
* @param namespace Namespace abbreviation
* @param namespaceInfo Namespace information
*/
public void addPropertyToRemove(String name, String namespace,
String namespaceInfo) {
Property propertyToRemove = new Property();
if (name != null) {
propertyToRemove.name = name;
propertyToRemove.namespace = namespace;
propertyToRemove.namespaceInfo = namespaceInfo;
toRemove.put(name, propertyToRemove);
}
}
// --------------------------------------------------- WebdavMethod Methods
/**
* Generate the query body.
*
* @return String query
*/
public String generateQuery() {
WebdavXMLPrinter printer = new WebdavXMLPrinter();
printer.writeElement("D", "DAV", "propertyupdate",
WebdavXMLPrinter.OPENING);
if (toSet.size() > 0) {
printer.writeElement("D", null, "set",
WebdavXMLPrinter.OPENING);
Enumeration toSetList = toSet.elements();
while (toSetList.hasMoreElements()) {
Property current = (Property) toSetList.nextElement();
printer.writeElement("D", null, "prop",
WebdavXMLPrinter.OPENING);
printer.writeProperty(current.namespace, current.namespaceInfo,
current.name, current.value);
printer.writeElement("D", null, "prop",
WebdavXMLPrinter.CLOSING);
}
printer.writeElement("D", null, "set",
WebdavXMLPrinter.CLOSING);
}
if (toRemove.size() > 0) {
printer.writeElement("D", null, "remove",
WebdavXMLPrinter.OPENING);
Enumeration toRemoveList = toRemove.elements();
while (toRemoveList.hasMoreElements()) {
Property current = (Property) toRemoveList.nextElement();
printer.writeElement("D", null, "prop",
WebdavXMLPrinter.OPENING);
printer.writeElement(current.namespace, current.namespaceInfo,
current.name,
WebdavXMLPrinter.NO_CONTENT);
printer.writeElement("D", null, "prop",
WebdavXMLPrinter.CLOSING);
}
printer.writeElement("D", null, "remove",
WebdavXMLPrinter.CLOSING);
}
printer.writeElement("D", "DAV", "propertyupdate",
WebdavXMLPrinter.CLOSING);
return printer.toString();
}
// --------------------------------------------------- Property Inner Class
private class Property {
public String name = "";
public String namespace;
public String namespaceInfo;
public String value;
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/PutMethod.java
Index: PutMethod.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/PutMethod.java,v 1.1 2000/11/22 06:19:09 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:09 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib.methods;
import java.io.*;
import java.util.*;
import org.apache.webdav.lib.State;
import org.apache.webdav.lib.Header;
import org.apache.webdav.lib.WebdavStatus;
/**
* PUT Method.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public class PutMethod
extends WebdavMethodBase {
// ----------------------------------------------------------- Constructors
/**
* Method constructor.
*/
public PutMethod() {
name = "PUT";
}
// ------------------------------------------------------- Instance Methods
/**
* For now, the data to be sent is loaded into memory. That will break if
* uploading of large files is attempted. I'll fix that eventually and use
* streams, but I need chunking on output to work (it does), AND chunking
* on input to work on the server side (it doesn't - Catalina doesn't
* handle that yet).
*/
private byte[] data = null;
/**
* Input stream to the data.
*/
private InputStream is = null;
// --------------------------------------------------------- Public Methods
/**
* Send the contents of a file.
*/
public void sendData(File file)
throws IOException {
sendData(new FileInputStream(file));
setHeader("Content-Length", new Long(file.length()).toString());
}
/**
* Send the contents of a byte array.
*/
public void sendData(byte[] data) {
this.data = data;
}
/**
* Send the contents of a string.
*/
public void sendData(String data) {
sendData(data.getBytes());
}
/**
* Send the contents of an input stream.
*/
public void sendData(InputStream is)
throws IOException {
/*
byte[] buffer = new byte[4096];
ByteArrayOutputStream os = new ByteArrayOutputStream();
int nb = 0;
while (true) {
nb = is.read(buffer);
if (nb == -1)
break;
os.write(buffer, 0, nb);
}
data = os.toByteArray();
*/
this.is = is;
}
// --------------------------------------------------- WebdavMethod Methods
/**
* Is the query body submitted through an InputStream of with a String.
* If an InputStream is available, it's used.
*
* @return boolean True if the content is avalable in an InputStream
*/
public boolean isStreamedQuery() {
return (is != null);
}
/**
* Recycle the method object, so that it can be reused again. Any attempt
* to reuse an object without recycling it will throw a WebdavException.
*/
public void recycle() {
super.recycle();
data = null;
if (is != null) {
try {
is.close();
} catch (IOException e) {
// Ignore
}
}
is = null;
}
/**
* Generate the query body.
*
* @return String query
*/
public String generateQuery() {
if (data == null)
return "";
else
return new String(data);
}
/**
* Stream the body of the query. This function should be used to send large
* request bodies.
*/
public void streamQuery(OutputStream out)
throws IOException {
byte[] buffer = new byte[4096];
int nb = 0;
while (true) {
nb = is.read(buffer);
if (nb == -1)
break;
out.write(buffer, 0, nb);
}
}
/**
* Parse response.
*
* @param is Input stream
*/
public void parseResponse(InputStream is)
throws IOException {
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/UnlockMethod.java
Index: UnlockMethod.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/UnlockMethod.java,v 1.1 2000/11/22 06:19:09 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:09 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib.methods;
import java.io.*;
import java.util.*;
import org.apache.webdav.lib.State;
import org.apache.webdav.lib.Header;
import org.apache.webdav.lib.WebdavStatus;
/**
* UNLOCK Method.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public class UnlockMethod
extends WebdavMethodBase {
// ----------------------------------------------------------- Constructors
/**
* Method constructor.
*/
public UnlockMethod() {
name = "UNLOCK";
}
// --------------------------------------------------- WebdavMethod Methods
/**
* Generate the query body.
*
* @return String query
*/
public String generateQuery() {
return null;
}
/**
* Parse response.
*
* @param is Input stream
*/
public void parseResponse(InputStream is)
throws IOException {
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/WebdavMethod.java
Index: WebdavMethod.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/WebdavMethod.java,v 1.1 2000/11/22 06:19:09 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:09 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib.methods;
import java.io.*;
import java.util.*;
import org.apache.webdav.lib.State;
import org.apache.webdav.lib.Header;
/**
* WebDAV method.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public interface WebdavMethod {
// -------------------------------------------------------------- Constants
/**
* Protocol version.
*/
public static final String PROTOCOL = "HTTP/1.1";
// ------------------------------------------------------------- Properties
/**
* Debug property setter.
*
* @param int Debug
*/
public void setDebug(int debug);
/**
* Set the method as used.
*/
public void setUsed();
/**
* Status code property setter.
*
* @param int Status code
*/
public void setStatusCode(int statusCode);
/**
* Status code property getter.
*
* @return int Status code
*/
public int getStatusCode();
/**
* Status text property setter.
*
* @param statusText Status text
*/
public void setStatusText(String statusText);
/**
* Status text property getter.
*
* @return String status text
*/
public String getStatusText();
/**
* Path property setter.
*
* @param path Absolute path
*/
public void setPath(String path);
/**
* Path property getter.
*
* @return String path
*/
public String getPath();
/**
* Set header.
*
* @param headerName Header name
* @param headerValue Header value
*/
public void setHeader(String headerName, String headerValue);
/**
* Get header.
*
* @param headerName Header name
* @return String header value (null if the header doesn't exist)
*/
public Header getHeader(String headerName);
/**
* Remove header.
*
* @param headerName Header name
*/
public void removeHeader(String headerName);
/**
* Checks if this method's instance has already been used, and has not been
* recycled.
*
* @return boolean True if the method's instance has already been used
*/
public boolean hasBeenUsed();
// ------------------------------------------------------ Interface Methods
/**
* Ensures the correctness of the request according to criterions which are
* method dependent.
*
* @return boolean True if the method is valid
*/
public boolean validate();
/**
* Recycle the method object, so that it can be reused again. Any attempt
* to reuse an object without recycling it will throw a WebdavException.
*/
public void recycle();
/**
* Get headers.
*
* @return Enumeration
*/
public Enumeration getHeaders();
/**
* Generate additional headers needed by the request.
*
* @param state State token
*/
public void generateHeaders(String host, State state);
/**
* Is the query body submitted through an InputStream of with a String.
* If an InputStream is available, it's used.
*
* @return boolean True if the content is avalable in an InputStream
*/
public boolean isStreamedQuery();
/**
* Generate the query.
*
* @return String query
*/
public String generateQuery();
/**
* Stream the body of the query. This function should be used to send large
* request bodies.
*/
public void streamQuery(OutputStream out)
throws IOException ;
/**
* Process response headers. The contract of this method is that it only
* parses the response headers.
*
* @param headers Headers list
*/
public void processResponseHeaders(Hashtable headers);
/**
* Parse response.
*
* @param is Input stream
*/
public void parseResponse(InputStream is)
throws IOException;
/**
* Generate the HTTP request line.
*
* @return String request line
*/
public String generateRequestLine();
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/WebdavMethodBase.java
Index: WebdavMethodBase.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/methods/WebdavMethodBase.java,v 1.1 2000/11/22 06:19:09 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:09 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib.methods;
import java.io.*;
import java.util.*;
import org.apache.webdav.lib.State;
import org.apache.webdav.lib.Cookie;
import org.apache.webdav.lib.Header;
import org.apache.webdav.lib.WebdavClient;
import org.apache.webdav.lib.WebdavStatus;
/**
* WebDAV method abstract implementation.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public abstract class WebdavMethodBase
implements WebdavMethod {
// ----------------------------------------------------- Instance Variables
/**
* True if this method has already been executed.
*/
private boolean used = false;
/**
* Debug.
*/
protected int debug = 0;
/**
* Status code.
*/
protected int statusCode = WebdavStatus.SC_OK;
/**
* Status text.
*/
protected String statusText = "OK";
/**
* Server path.
*/
protected String path = "/";
/**
* Method name.
*/
protected String name;
/**
* Headers.
*/
protected Hashtable headers = new Hashtable();
/**
* Global state.
*/
protected State state;
// ----------------------------------------------------------- Constructors
/**
* Method constructor.
*/
public WebdavMethodBase() {
}
// ------------------------------------------------------------- Properties
/**
* Debug property setter.
*
* @param int Debug
*/
public void setDebug(int debug) {
this.debug = debug;
}
/**
* Status code property setter.
*
* @param int Status code
*/
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
/**
* Status code property getter.
*
* @return int Status code
*/
public int getStatusCode() {
return statusCode;
}
/**
* Status text property setter.
*
* @param statusText Status text
*/
public void setStatusText(String statusText) {
this.statusText = statusText;
}
/**
* Status text property getter.
*
* @return String status text
*/
public String getStatusText() {
return statusText;
}
/**
* Path property setter.
*
* @param path Absolute path
*/
public void setPath(String path) {
this.path = path;
}
/**
* Path property getter.
*
* @return String path
*/
public String getPath() {
return path;
}
/**
* Set header.
*
* @param headerName Header name
* @param headerValue Header value
*/
public void setHeader(String headerName, String headerValue) {
headers.put(headerName.toLowerCase(),
new Header(headerName, headerValue));
}
/**
* Get header.
*
* @param headerName Header name
* @return String header value (null if the header doesn't exist)
*/
public Header getHeader(String headerName) {
return (Header) headers.get(headerName.toLowerCase());
}
/**
* Remove header.
*
* @param headerName Header name
*/
public void removeHeader(String headerName) {
headers.remove(headerName.toLowerCase());
}
/**
* Checks if this method's instance has already been used, and has not been
* recycled.
*
* @return boolean True if the method's instance has already been used
*/
public final boolean hasBeenUsed() {
return (used);
}
// --------------------------------------------------- WebdavMethod Methods
/**
* Set the method as used.
*/
public void setUsed() {
used = true;
}
/**
* Ensures the correctness of the request according to criterions which are
* method dependent.
*
* @return boolean True if the method is valid
*/
public boolean validate() {
// By default, the request is valid.
return (true);
}
/**
* Recycle the method object, so that it can be reused again. Any attempt
* to reuse an object without recycling it will throw a WebdavException.
*/
public void recycle() {
path = "/";
statusCode = WebdavStatus.SC_OK;
statusText = "OK";
headers.clear();
state = null;
used = false;
}
/**
* Get headers.
*
* @return Enumeration
*/
public Enumeration getHeaders() {
return headers.elements();
}
/**
* Generate additional headers needed by the request.
*
* @param state State token
* @deprecated this method is deprecated in favour of the
* <CODE>generateHeaders(String, State)</CODE> method.
*/
public void generateHeaders(State state) {
}
/**
* Generate additional headers needed by the request.
*
* @param host the host
* @param state State token
*/
public void generateHeaders(String host, State state) {
// Default implementation adds the lock token headers if necessary
this.state = state;
generateHeaders(state);
// good practice to provide a user-agent indicator
if (!headers.containsKey("user-agent")) {
headers.put("user-agent", WebdavClient.USER_AGENT);
}
if (!headers.containsKey("host")) {
headers.put("host", new Header("host", host));
}
// add the cookies
if (!headers.containsKey("cookie")) {
Vector cookies = state.getCookies();
headers.put("cookie",
Cookie.createCookieHeader(host, getPath(), cookies));
}
}
/**
* Is the query body submitted through an InputStream of with a String.
* If an InputStream is available, it's used.
*
* @return boolean True if the content is avalable in an InputStream
*/
public boolean isStreamedQuery() {
// By default, the query is NOT streamed.
return false;
}
/**
* Generate the query body.
*
* @return String query
*/
public String generateQuery() {
return "";
}
/**
* Stream the body of the query. This function should be used to send large
* request bodies.
*/
public void streamQuery(OutputStream out)
throws IOException {
}
/**
* Process response headers. The contract of this method is that it only
* parses the response headers.
*
* @param headers Headers list
*/
public void processResponseHeaders(Hashtable headers) {
// We replace the request headers with the response headers
this.headers = headers;
if (debug > 0) {
Enumeration list = headers.elements();
while (list.hasMoreElements()) {
Header current = (Header) list.nextElement();
System.out.println(current.getName() + ": " +
current.getValue());
}
}
}
/**
* Parse response.
*
* @param is Input stream
*/
public abstract void parseResponse(InputStream is)
throws IOException;
/**
* Generate the HTTP request line.
*
* @return String request line
*/
public final String generateRequestLine() {
return (name + " " + path + " " + PROTOCOL + "\r\n");
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/util/Base64.java
Index: Base64.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/util/Base64.java,v 1.1 2000/11/22 06:19:10 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:10 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib.util;
/**
* This class provides encode/decode for RFC 2045 Base64 as
* defined by RFC 2045, N. Freed and N. Borenstein.
* RFC 2045: Multipurpose Internet Mail Extensions (MIME)
* Part One: Format of Internet Message Bodies. Reference
* 1996 Available at: http://www.ietf.org/rfc/rfc2045.txt
* This class is used by XML Schema binary format validation
*
* @author Jeffrey Rodriguez
* @version $Revision: 1.1 $ $Date: 2000/11/22 06:19:10 $
*/
public final class Base64 {
static private final int BASELENGTH = 255;
static private final int LOOKUPLENGTH = 63;
static private final int TWENTYFOURBITGROUP = 24;
static private final int EIGHTBIT = 8;
static private final int SIXTEENBIT = 16;
static private final int SIXBIT = 6;
static private final int FOURBYTE = 4;
static private final byte PAD = ( byte ) '=';
static private byte [] base64Alphabet = new byte[BASELENGTH];
static private byte [] lookUpBase64Alphabet = new byte[LOOKUPLENGTH];
static {
for (int i = 0; i<BASELENGTH; i++ ) {
base64Alphabet[i] = -1;
}
for ( int i = 'Z'; i >= 'A'; i-- ) {
base64Alphabet[i] = (byte) (i-'A');
}
for ( int i = 'z'; i>= 'a'; i--) {
base64Alphabet[i] = (byte) ( i-'a' + 26);
}
for ( int i = '9'; i >= '0'; i--) {
base64Alphabet[i] = (byte) (i-'0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i<=25; i++ )
lookUpBase64Alphabet[i] = (byte) ('A'+i );
for (int i = 26, j = 0; i<=51; i++, j++ )
lookUpBase64Alphabet[i] = (byte) ('a'+ j );
for (int i = 52, j = 0; i<=61; i++, j++ )
lookUpBase64Alphabet[i] = (byte) ('0' + j );
}
static boolean isBase64( byte octect ) {
//shall we ignore white space? JEFF??
return(octect == PAD || base64Alphabet[octect] != -1 );
}
static boolean isArrayByteBase64( byte[] arrayOctect ) {
int length = arrayOctect.length;
if ( length == 0 )
return false;
for ( int i=0; i < length; i++ ) {
if ( Base64.isBase64( arrayOctect[i] ) == false)
return false;
}
return true;
}
/**
* Encodes hex octects into Base64
*
* @param binaryData Array containing binaryData
* @return Encoded Base64 array
*/
public byte[] encode( byte[] binaryData ) {
int lengthDataBits = binaryData.length*EIGHTBIT;
int fewerThan24bits = lengthDataBits%TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits/TWENTYFOURBITGROUP;
byte encodedData[] = null;
if ( fewerThan24bits != 0 ) //data not divisible by 24 bit
encodedData = new byte[ (numberTriplets + 1 )*4 ];
else // 16 or 8 bit
encodedData = new byte[ numberTriplets*4 ];
byte k=0, l=0, b1=0,b2=0,b3=0;
int encodedIndex = 0;
int dataIndex = 0;
int i = 0;
for ( i = 0; i<numberTriplets; i++ ) {
dataIndex = i*3;
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
b3 = binaryData[dataIndex + 2];
l = (byte)(b2 & 0x0f);
k = (byte)(b1 & 0x03);
encodedIndex = i*4;
encodedData[encodedIndex] = lookUpBase64Alphabet[ b1 >>2 ];
encodedData[encodedIndex+1] = lookUpBase64Alphabet[(b2 >>4 ) |
( k<<4 )];
encodedData[encodedIndex+2] = lookUpBase64Alphabet[ (l <<2 ) |
( b3>>6)];
encodedData[encodedIndex+3] = lookUpBase64Alphabet[ b3 & 0x3f ];
}
// form integral number of 6-bit groups
dataIndex = i*3;
encodedIndex = i*4;
if (fewerThan24bits == EIGHTBIT ) {
b1 = binaryData[dataIndex];
k = (byte) ( b1 &0x03 );
encodedData[encodedIndex] = lookUpBase64Alphabet[ b1 >>2 ];
encodedData[encodedIndex + 1] = lookUpBase64Alphabet[ k<<4 ];
encodedData[encodedIndex + 2] = PAD;
encodedData[encodedIndex + 3] = PAD;
} else if ( fewerThan24bits == SIXTEENBIT ) {
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex +1 ];
l = ( byte ) ( b2 &0x0f );
k = ( byte ) ( b1 &0x03 );
encodedData[encodedIndex] = lookUpBase64Alphabet[ b1 >>2 ];
encodedData[encodedIndex + 1] = lookUpBase64Alphabet[ (b2 >>4 )
| ( k<<4 )];
encodedData[encodedIndex + 2] = lookUpBase64Alphabet[ l<<2 ];
encodedData[encodedIndex + 3] = PAD;
}
return encodedData;
}
/**
* Decodes Base64 data into octects
*
* @param binaryData Byte array containing Base64 data
* @return Array containind decoded data.
*/
public byte[] decode( byte[] base64Data ) {
int numberQuadruple = base64Data.length/FOURBYTE;
byte decodedData[] = null;
byte b1=0,b2=0,b3=0, b4=0, marker0=0, marker1=0;
// Throw away anything not in base64Data
// Adjust size
int encodedIndex = 0;
int dataIndex = 0;
decodedData = new byte[ numberQuadruple*3 + 1 ];
for (int i = 0; i<numberQuadruple; i++ ) {
dataIndex = i*4;
marker0 = base64Data[dataIndex +2];
marker1 = base64Data[dataIndex +3];
b1 = base64Alphabet[base64Data[dataIndex]];
b2 = base64Alphabet[base64Data[dataIndex +1]];
if ( marker0 != PAD && marker1 != PAD ) { //No PAD e.g 3cQl
b3 = base64Alphabet[ marker0 ];
b4 = base64Alphabet[ marker1 ];
decodedData[encodedIndex] = (byte)( b1 <<2 | b2>>4 ) ;
decodedData[encodedIndex+1] = (byte)(((b2 & 0xf)<<4 ) |(
(b3>>2) & 0xf) );
decodedData[encodedIndex+2] = (byte)( b3<<6 | b4 );
} else if ( marker0 == PAD ) { //Two PAD e.g. 3c[Pad][Pad]
decodedData[encodedIndex] = (byte)( b1 <<2 | b2>>4 ) ;
decodedData[encodedIndex+1] = (byte)((b2 & 0xf)<<4 );
decodedData[encodedIndex+2] = (byte) 0;
} else if ( marker1 == PAD ) { //One PAD e.g. 3cQ[Pad]
b3 = base64Alphabet[ marker0 ];
decodedData[encodedIndex] = (byte)( b1 <<2 | b2>>4 );
decodedData[encodedIndex+1] = (byte)(((b2 & 0xf)<<4 ) |(
(b3>>2) & 0xf) );
decodedData[encodedIndex+2] = (byte)( b3<<6);
}
encodedIndex += 3;
}
return decodedData;
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/util/DOMUtils.java
Index: DOMUtils.java
===================================================================
/*
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib.util;
import java.lang.reflect.Method;
import java.io.InputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.StringTokenizer;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
/** This class provides some basic utility methods for working with
* XML Document objects.
*/
public class DOMUtils {
protected static Class[] getElementsByNSParameterTypes =
{ String.class, String.class };
public static boolean isDOM2Compliant(Document document) {
boolean isDOM2 = false;
try {
Class documentClass = document.getClass();
Method method = documentClass.getMethod(
"getElementsByTagNameNS",
getElementsByNSParameterTypes );
// can method ever be null?
if (method != null) {
isDOM2 = true;
}
} catch (NoSuchMethodException e) {
}
return isDOM2;
}
/**
* Determine the namespace prefix being used for DAV.
* Generally, DAV responses say something like:
*
* <PRE>
* <D:multistatus xmlns:D="DAV:">
* </PRE>
*
* <P> In this case, the "D:" is the prefix for DAV.
*/
public static String findDavPrefix(Document document) {
Element multistatus = document.getDocumentElement();
NamedNodeMap list = multistatus.getAttributes();
String prefix = "DAV:";
for (int i = 0; i < list.getLength(); i++) {
try {
Attr attr = (Attr) list.item(i);
if (attr.getName() != null &&
attr.getName().startsWith("xmlns") &&
attr.getValue().equals("DAV:")) {
int indx = attr.getName().indexOf(":");
if ((indx >= 0) && (indx < attr.getName().length())) {
prefix = attr.getName().substring(indx + 1) + ":";
} else {
prefix = "";
}
}
} catch (ClassCastException e) {
}
}
return prefix;
}
/**
* Scan all immediate children of a node, and append all
* text nodes into a string. Consider the following example
*
* <PRE>
* <customer>Joe Schmoe</customer>
* </PRE>
*
* <P> In this case, calling this method on the
* <CODE>customer</CODE> element returns "Joe Schmoe".
*/
public static String getTextValue(Element element) {
// I *thought* that I should be able to use element.getNodeValue()...
String text = "";
NodeList textList = element.getChildNodes();
for (int i = 0; i < textList.getLength(); i++) {
try {
text += ((Text) textList.item(i)).getData();
} catch (ClassCastException e) {
// we don't care about non-Text nodes
}
}
return text;
}
/**
* Get the status code out of the normal status response.
*
* <P> Each <code>DAV:propstat</code> node contains a
* status line, such as:
*
* <PRE>
* <DAV:status>HTTP/1.1 200 OK</DAV:status>
* </PRE>
*
* <P> In this case, calling this method on the
* text string returns 200.
*/
public static int parseStatus(String statusString) {
int status = -1;
if (statusString != null) {
StringTokenizer tokenizer = new StringTokenizer(statusString);
if (tokenizer.countTokens() >= 2) {
Object dummy = tokenizer.nextElement();
String statusCode = tokenizer.nextElement().toString();
try {
status = Integer.parseInt(statusCode);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(
"Status code is not numeric");
}
} else {
throw new IllegalArgumentException(
"There aren't enough words in the input argument");
}
}
return status;
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/util/DOMWriter.java
Index: DOMWriter.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/util/DOMWriter.java,v 1.1 2000/11/22 06:19:11 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:11 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib.util;
import java.io.*;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
/**
* A sample DOM writer. This sample program illustrates how to
* traverse a DOM tree in order to print a document that is parsed.
*/
public class DOMWriter {
//
// Data
//
/** Default Encoding */
private static String
PRINTWRITER_ENCODING = "UTF8";
private static String MIME2JAVA_ENCODINGS[] =
{ "Default", "UTF-8", "US-ASCII", "ISO-8859-1", "ISO-8859-2", "ISO-8859-3", "ISO-8859-4",
"ISO-8859-5", "ISO-8859-6", "ISO-8859-7", "ISO-8859-8", "ISO-8859-9", "ISO-2022-JP",
"SHIFT_JIS", "EUC-JP","GB2312", "BIG5", "EUC-KR", "ISO-2022-KR", "KOI8-R", "EBCDIC-CP-US",
"EBCDIC-CP-CA", "EBCDIC-CP-NL", "EBCDIC-CP-DK", "EBCDIC-CP-NO", "EBCDIC-CP-FI", "EBCDIC-CP-SE",
"EBCDIC-CP-IT", "EBCDIC-CP-ES", "EBCDIC-CP-GB", "EBCDIC-CP-FR", "EBCDIC-CP-AR1",
"EBCDIC-CP-HE", "EBCDIC-CP-CH", "EBCDIC-CP-ROECE","EBCDIC-CP-YU",
"EBCDIC-CP-IS", "EBCDIC-CP-AR2", "UTF-16"
};
/** Print writer. */
protected PrintWriter out;
/** Canonical output. */
protected boolean canonical;
public DOMWriter(String encoding, boolean canonical)
throws UnsupportedEncodingException {
out = new PrintWriter(new OutputStreamWriter(System.out, encoding));
this.canonical = canonical;
} // <init>(String,boolean)
//
// Constructors
//
/** Default constructor. */
public DOMWriter(boolean canonical) throws UnsupportedEncodingException {
this( getWriterEncoding(), canonical);
}
public DOMWriter(Writer writer, boolean canonical) {
out = new PrintWriter(writer);
this.canonical = canonical;
}
public static String getWriterEncoding( ) {
return (PRINTWRITER_ENCODING);
}// getWriterEncoding
public static void setWriterEncoding( String encoding ) {
if( encoding.equalsIgnoreCase( "DEFAULT" ) )
PRINTWRITER_ENCODING = "UTF8";
else if( encoding.equalsIgnoreCase( "UTF-16" ) )
PRINTWRITER_ENCODING = "Unicode";
else
PRINTWRITER_ENCODING = MIME2Java.convert( encoding );
}// setWriterEncoding
public static boolean isValidJavaEncoding( String encoding ) {
for ( int i = 0; i < MIME2JAVA_ENCODINGS.length; i++ )
if ( encoding.equals( MIME2JAVA_ENCODINGS[i] ) )
return (true);
return (false);
}// isValidJavaEncoding
/** Prints the specified node, recursively. */
public void print(Node node) {
// is there anything to do?
if ( node == null ) {
return;
}
int type = node.getNodeType();
switch ( type ) {
// print document
case Node.DOCUMENT_NODE: {
if ( !canonical ) {
String Encoding = this.getWriterEncoding();
if( Encoding.equalsIgnoreCase( "DEFAULT" ) )
Encoding = "UTF-8";
else if( Encoding.equalsIgnoreCase( "Unicode" ) )
Encoding = "UTF-16";
else
Encoding = MIME2Java.reverse( Encoding );
out.println("<?xml version=\"1.0\" encoding=\""+
Encoding + "\"?>");
}
print(((Document)node).getDocumentElement());
out.flush();
break;
}
// print element with attributes
case Node.ELEMENT_NODE: {
out.print('<');
out.print(node.getNodeName());
Attr attrs[] = sortAttributes(node.getAttributes());
for ( int i = 0; i < attrs.length; i++ ) {
Attr attr = attrs[i];
out.print(' ');
out.print(attr.getNodeName());
out.print("=\"");
out.print(normalize(attr.getNodeValue()));
out.print('"');
}
out.print('>');
NodeList children = node.getChildNodes();
if ( children != null ) {
int len = children.getLength();
for ( int i = 0; i < len; i++ ) {
print(children.item(i));
}
}
break;
}
// handle entity reference nodes
case Node.ENTITY_REFERENCE_NODE: {
if ( canonical ) {
NodeList children = node.getChildNodes();
if ( children != null ) {
int len = children.getLength();
for ( int i = 0; i < len; i++ ) {
print(children.item(i));
}
}
} else {
out.print('&');
out.print(node.getNodeName());
out.print(';');
}
break;
}
// print cdata sections
case Node.CDATA_SECTION_NODE: {
if ( canonical ) {
out.print(normalize(node.getNodeValue()));
} else {
out.print("<![CDATA[");
out.print(node.getNodeValue());
out.print("]]>");
}
break;
}
// print text
case Node.TEXT_NODE: {
out.print(normalize(node.getNodeValue()));
break;
}
// print processing instruction
case Node.PROCESSING_INSTRUCTION_NODE: {
out.print("<?");
out.print(node.getNodeName());
String data = node.getNodeValue();
if ( data != null && data.length() > 0 ) {
out.print(' ');
out.print(data);
}
out.print("?>");
break;
}
}
if ( type == Node.ELEMENT_NODE ) {
out.print("</");
out.print(node.getNodeName());
out.print('>');
}
out.flush();
} // print(Node)
/** Returns a sorted list of attributes. */
protected Attr[] sortAttributes(NamedNodeMap attrs) {
int len = (attrs != null) ? attrs.getLength() : 0;
Attr array[] = new Attr[len];
for ( int i = 0; i < len; i++ ) {
array[i] = (Attr)attrs.item(i);
}
for ( int i = 0; i < len - 1; i++ ) {
String name = array[i].getNodeName();
int index = i;
for ( int j = i + 1; j < len; j++ ) {
String curName = array[j].getNodeName();
if ( curName.compareTo(name) < 0 ) {
name = curName;
index = j;
}
}
if ( index != i ) {
Attr temp = array[i];
array[i] = array[index];
array[index] = temp;
}
}
return (array);
} // sortAttributes(NamedNodeMap):Attr[]
/** Normalizes the given string. */
protected String normalize(String s) {
StringBuffer str = new StringBuffer();
int len = (s != null) ? s.length() : 0;
for ( int i = 0; i < len; i++ ) {
char ch = s.charAt(i);
switch ( ch ) {
case '<': {
str.append("<");
break;
}
case '>': {
str.append(">");
break;
}
case '&': {
str.append("&");
break;
}
case '"': {
str.append(""");
break;
}
case '\r':
case '\n': {
if ( canonical ) {
str.append("&#");
str.append(Integer.toString(ch));
str.append(';');
break;
}
// else, default append char
}
default: {
str.append(ch);
}
}
}
return (str.toString());
} // normalize(String):String
private static void printValidJavaEncoding() {
System.err.println( " ENCODINGS:" );
System.err.print( " " );
for( int i = 0;
i < MIME2JAVA_ENCODINGS.length; i++) {
System.err.print( MIME2JAVA_ENCODINGS[i] + " " );
if( (i % 7 ) == 0 ){
System.err.println();
System.err.print( " " );
}
}
} // printJavaEncoding()
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/util/MD5Encoder.java
Index: MD5Encoder.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/util/MD5Encoder.java,v 1.1 2000/11/22 06:19:11 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:11 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib.util;
/**
* 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: 2000/11/22 06:19:11 $
*/
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);
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/util/MIME2Java.java
Index: MIME2Java.java
===================================================================
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.webdav.lib.util;
import java.util.*;
/**
* MIME2Java is a convenience class which handles conversions between MIME charset names
* and Java encoding names.
* <p>The supported XML encodings are the intersection of XML-supported code sets and those
* supported in JDK 1.1.
* <p>MIME charset names are used on <var>xmlEncoding</var> parameters to methods such
* as <code>TXDocument#setEncoding</code> and <code>DTD#setEncoding</code>.
* <p>Java encoding names are used on <var>encoding</var> parameters to
* methods such as <code>TXDocument#printWithFormat</code> and <code>DTD#printExternal</code>.
* <P>
* <TABLE BORDER="0" WIDTH="100%">
* <TR>
* <TD WIDTH="33%">
* <P ALIGN="CENTER"><B>Common Name</B>
* </TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER"><B>Use this name in XML files</B>
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER"><B>Name Type</B>
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER"><B>Xerces converts to this Java Encoder Name</B>
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">8 bit Unicode</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">UTF-8
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">IANA
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">UTF8
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">ISO Latin 1</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ISO-8859-1
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">MIME
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">ISO-8859-1
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">ISO Latin 2</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ISO-8859-2
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">MIME
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">ISO-8859-2
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">ISO Latin 3</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ISO-8859-3
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">MIME
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">ISO-8859-3
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">ISO Latin 4</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ISO-8859-4
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">MIME
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">ISO-8859-4
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">ISO Latin Cyrillic</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ISO-8859-5
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">MIME
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">ISO-8859-5
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">ISO Latin Arabic</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ISO-8859-6
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">MIME
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">ISO-8859-6
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">ISO Latin Greek</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ISO-8859-7
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">MIME
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">ISO-8859-7
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">ISO Latin Hebrew</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ISO-8859-8
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">MIME
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">ISO-8859-8
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">ISO Latin 5</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ISO-8859-9
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">MIME
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">ISO-8859-9
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">EBCDIC: US</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ebcdic-cp-us
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">IANA
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">cp037
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">EBCDIC: Canada</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ebcdic-cp-ca
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">IANA
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">cp037
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">EBCDIC: Netherlands</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ebcdic-cp-nl
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">IANA
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">cp037
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">EBCDIC: Denmark</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ebcdic-cp-dk
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">IANA
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">cp277
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">EBCDIC: Norway</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ebcdic-cp-no
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">IANA
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">cp277
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">EBCDIC: Finland</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ebcdic-cp-fi
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">IANA
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">cp278
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">EBCDIC: Sweden</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ebcdic-cp-se
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">IANA
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">cp278
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">EBCDIC: Italy</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ebcdic-cp-it
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">IANA
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">cp280
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">EBCDIC: Spain, Latin America</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ebcdic-cp-es
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">IANA
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">cp284
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">EBCDIC: Great Britain</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ebcdic-cp-gb
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">IANA
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">cp285
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">EBCDIC: France</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ebcdic-cp-fr
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">IANA
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">cp297
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">EBCDIC: Arabic</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ebcdic-cp-ar1
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">IANA
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">cp420
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">EBCDIC: Hebrew</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ebcdic-cp-he
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">IANA
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">cp424
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">EBCDIC: Switzerland</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ebcdic-cp-ch
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">IANA
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">cp500
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">EBCDIC: Roece</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ebcdic-cp-roece
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">IANA
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">cp870
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">EBCDIC: Yogoslavia</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ebcdic-cp-yu
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">IANA
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">cp870
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">EBCDIC: Iceland</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ebcdic-cp-is
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">IANA
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">cp871
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">EBCDIC: Urdu</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">ebcdic-cp-ar2
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">IANA
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">cp918
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">Chinese for PRC, mixed 1/2 byte</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">gb2312
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">MIME
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">GB2312
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">Extended Unix Code, packed for Japanese</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">euc-jp
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">MIME
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">eucjis
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">Japanese: iso-2022-jp</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">iso-2020-jp
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">MIME
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">JIS
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">Japanese: Shift JIS</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">Shift_JIS
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">MIME
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">SJIS
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">Chinese: Big5</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">Big5
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">MIME
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">Big5
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">Extended Unix Code, packed for Korean</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">euc-kr
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">MIME
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">iso2022kr
* </TD>
* </TR>
* <TR>
* <TD WIDTH="33%">Cyrillic</TD>
* <TD WIDTH="15%">
* <P ALIGN="CENTER">koi8-r
* </TD>
* <TD WIDTH="12%">
* <P ALIGN="CENTER">MIME
* </TD>
* <TD WIDTH="31%">
* <P ALIGN="CENTER">koi8-r
* </TD>
* </TR>
* </TABLE>
*
* @version
* @author TAMURA Kent <kent@trl.ibm.co.jp>
*/
public class MIME2Java {
static private Hashtable s_enchash;
static private Hashtable s_revhash;
static {
s_enchash = new Hashtable();
// <preferred MIME name>, <Java encoding name>
s_enchash.put("UTF-8", "UTF8");
s_enchash.put("US-ASCII", "8859_1"); // ?
s_enchash.put("ISO-8859-1", "8859_1");
s_enchash.put("ISO-8859-2", "8859_2");
s_enchash.put("ISO-8859-3", "8859_3");
s_enchash.put("ISO-8859-4", "8859_4");
s_enchash.put("ISO-8859-5", "8859_5");
s_enchash.put("ISO-8859-6", "8859_6");
s_enchash.put("ISO-8859-7", "8859_7");
s_enchash.put("ISO-8859-8", "8859_8");
s_enchash.put("ISO-8859-9", "8859_9");
s_enchash.put("ISO-2022-JP", "JIS");
s_enchash.put("SHIFT_JIS", "SJIS");
s_enchash.put("EUC-JP", "EUCJIS");
s_enchash.put("GB2312", "GB2312");
s_enchash.put("BIG5", "Big5");
s_enchash.put("EUC-KR", "KSC5601");
s_enchash.put("ISO-2022-KR", "ISO2022KR");
s_enchash.put("KOI8-R", "KOI8_R");
s_enchash.put("EBCDIC-CP-US", "CP037");
s_enchash.put("EBCDIC-CP-CA", "CP037");
s_enchash.put("EBCDIC-CP-NL", "CP037");
s_enchash.put("EBCDIC-CP-DK", "CP277");
s_enchash.put("EBCDIC-CP-NO", "CP277");
s_enchash.put("EBCDIC-CP-FI", "CP278");
s_enchash.put("EBCDIC-CP-SE", "CP278");
s_enchash.put("EBCDIC-CP-IT", "CP280");
s_enchash.put("EBCDIC-CP-ES", "CP284");
s_enchash.put("EBCDIC-CP-GB", "CP285");
s_enchash.put("EBCDIC-CP-FR", "CP297");
s_enchash.put("EBCDIC-CP-AR1", "CP420");
s_enchash.put("EBCDIC-CP-HE", "CP424");
s_enchash.put("EBCDIC-CP-CH", "CP500");
s_enchash.put("EBCDIC-CP-ROECE", "CP870");
s_enchash.put("EBCDIC-CP-YU", "CP870");
s_enchash.put("EBCDIC-CP-IS", "CP871");
s_enchash.put("EBCDIC-CP-AR2", "CP918");
// j:CNS11643 -> EUC-TW?
// ISO-2022-CN? ISO-2022-CN-EXT?
s_revhash = new Hashtable();
// <Java encoding name>, <preferred MIME name>
s_revhash.put("UTF8", "UTF-8");
//s_revhash.put("8859_1", "US-ASCII"); // ?
s_revhash.put("8859_1", "ISO-8859-1");
s_revhash.put("8859_2", "ISO-8859-2");
s_revhash.put("8859_3", "ISO-8859-3");
s_revhash.put("8859_4", "ISO-8859-4");
s_revhash.put("8859_5", "ISO-8859-5");
s_revhash.put("8859_6", "ISO-8859-6");
s_revhash.put("8859_7", "ISO-8859-7");
s_revhash.put("8859_8", "ISO-8859-8");
s_revhash.put("8859_9", "ISO-8859-9");
s_revhash.put("JIS", "ISO-2022-JP");
s_revhash.put("SJIS", "Shift_JIS");
s_revhash.put("EUCJIS", "EUC-JP");
s_revhash.put("GB2312", "GB2312");
s_revhash.put("BIG5", "Big5");
s_revhash.put("KSC5601", "EUC-KR");
s_revhash.put("ISO2022KR", "ISO-2022-KR");
s_revhash.put("KOI8_R", "KOI8-R");
s_revhash.put("CP037", "EBCDIC-CP-US");
s_revhash.put("CP037", "EBCDIC-CP-CA");
s_revhash.put("CP037", "EBCDIC-CP-NL");
s_revhash.put("CP277", "EBCDIC-CP-DK");
s_revhash.put("CP277", "EBCDIC-CP-NO");
s_revhash.put("CP278", "EBCDIC-CP-FI");
s_revhash.put("CP278", "EBCDIC-CP-SE");
s_revhash.put("CP280", "EBCDIC-CP-IT");
s_revhash.put("CP284", "EBCDIC-CP-ES");
s_revhash.put("CP285", "EBCDIC-CP-GB");
s_revhash.put("CP297", "EBCDIC-CP-FR");
s_revhash.put("CP420", "EBCDIC-CP-AR1");
s_revhash.put("CP424", "EBCDIC-CP-HE");
s_revhash.put("CP500", "EBCDIC-CP-CH");
s_revhash.put("CP870", "EBCDIC-CP-ROECE");
s_revhash.put("CP870", "EBCDIC-CP-YU");
s_revhash.put("CP871", "EBCDIC-CP-IS");
s_revhash.put("CP918", "EBCDIC-CP-AR2");
}
private MIME2Java() {
}
/**
* Convert a MIME charset name, also known as an XML encoding name, to a Java encoding name.
* @param mimeCharsetName Case insensitive MIME charset name: <code>UTF-8, US-ASCII, ISO-8859-1,
* ISO-8859-2, ISO-8859-3, ISO-8859-4, ISO-8859-5, ISO-8859-6,
* ISO-8859-7, ISO-8859-8, ISO-8859-9, ISO-2022-JP, Shift_JIS,
* EUC-JP, GB2312, Big5, EUC-KR, ISO-2022-KR, KOI8-R,
* EBCDIC-CP-US, EBCDIC-CP-CA, EBCDIC-CP-NL, EBCDIC-CP-DK,
* EBCDIC-CP-NO, EBCDIC-CP-FI, EBCDIC-CP-SE, EBCDIC-CP-IT,
* EBCDIC-CP-ES, EBCDIC-CP-GB, EBCDIC-CP-FR, EBCDIC-CP-AR1,
* EBCDIC-CP-HE, EBCDIC-CP-CH, EBCDIC-CP-ROECE, EBCDIC-CP-YU,
* EBCDIC-CP-IS and EBCDIC-CP-AR2</code>.
* @return Java encoding name, or <var>null</var> if <var>mimeCharsetName</var>
* is unknown.
* @see #reverse
*/
public static String convert(String mimeCharsetName) {
return (String)s_enchash.get(mimeCharsetName.toUpperCase());
}
/**
* Convert a Java encoding name to MIME charset name.
* Available values of <i>encoding</i> are "UTF8", "8859_1", "8859_2", "8859_3", "8859_4",
* "8859_5", "8859_6", "8859_7", "8859_8", "8859_9", "JIS", "SJIS", "EUCJIS",
* "GB2312", "BIG5", "KSC5601", "ISO2022KR", "KOI8_R", "CP037", "CP277", "CP278",
* "CP280", "CP284", "CP285", "CP297", "CP420", "CP424", "CP500", "CP870", "CP871" and "CP918".
* @param encoding Case insensitive Java encoding name: <code>UTF8, 8859_1, 8859_2, 8859_3,
* 8859_4, 8859_5, 8859_6, 8859_7, 8859_8, 8859_9, JIS, SJIS, EUCJIS,
* GB2312, BIG5, KSC5601, ISO2022KR, KOI8_R, CP037, CP277, CP278,
* CP280, CP284, CP285, CP297, CP420, CP424, CP500, CP870, CP871
* and CP918</code>.
* @return MIME charset name, or <var>null</var> if <var>encoding</var> is unknown.
* @see #convert
*/
public static String reverse(String encoding) {
return (String)s_revhash.get(encoding.toUpperCase());
}
}
1.1 jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/util/WebdavXMLPrinter.java
Index: WebdavXMLPrinter.java
===================================================================
/*
* $Header: /home/cvs/jakarta-slide/src/webdav/client/src/org/apache/webdav/lib/util/WebdavXMLPrinter.java,v 1.1 2000/11/22 06:19:11 remm Exp $
* $Revision: 1.1 $
* $Date: 2000/11/22 06:19:11 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.webdav.lib.util;
/**
* WebdavXMLPrinter helper class.
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
*/
public class WebdavXMLPrinter {
// -------------------------------------------------------------- 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;
// ----------------------------------------------------------- Constructors
/**
* Constructor.
*/
public WebdavXMLPrinter() {
buffer = new StringBuffer();
}
// ----------------------------------------------------- Instance Variables
/**
* Buffer.
*/
protected StringBuffer buffer;
// --------------------------------------------------------- Public Methods
/**
* 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 XML Header.
*/
public void writeXMLHeader() {
buffer.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n");
}
// --------------------------------------------------------- Object Methods
/**
* Retrieve generated XML.
*
* @return String containing the generated XML
*/
public String toString() {
return buffer.toString();
}
}