KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ibm > webdav > Resource


1 package com.ibm.webdav;
2
3 /*
4  * (C) Copyright IBM Corp. 2000 All rights reserved.
5  *
6  * The program is provided "AS IS" without any warranty express or
7  * implied, including the warranty of non-infringement and the implied
8  * warranties of merchantibility and fitness for a particular purpose.
9  * IBM will not be liable for any damages suffered by you as a result
10  * of using the Program. In no event will IBM be liable for any
11  * special, indirect or consequential damages or lost profits even if
12  * IBM has been advised of the possibility of their occurrence. IBM
13  * will not be liable for any third party claims against you.
14  *
15  * Portions Copyright (C) Simulacra Media Ltd, 2004.
16  */

17 import java.io.*;
18 import java.net.*;
19 import java.util.*;
20
21 import javax.xml.parsers.*;
22
23 import org.w3c.dom.*;
24
25 import com.ibm.webdav.impl.*;
26
27 /** A Resource implements a client proxy of the Resource interface locally where
28  * possible, and by delegating the methods that must be implemented by the server
29  * to another proxy stub as specified by the protocol given
30  * in the resource URL. This allows WebDAV client applications to communicate
31  * with a server through multiple RPC protocols, including no protocol at all for
32  * local access.
33  * @see com.ibm.webdav.CollectionP
34  * @see com.ibm.webdav.Precondition#addStateTokenCondition
35  * @author Jim Amsden <jamsden@us.ibm.com>
36  */

37 public class Resource implements Serializable {
38
39    /** The version of XML used by WebDAV
40     */

41    public static String JavaDoc XMLVersion = "1.0";
42    public static String JavaDoc DAV4JVersion = "2.0.10";
43
44     /** The default charset encoding for XML documents and for storing
45      * text/* MIME types on the server
46      */

47     public static String JavaDoc defaultXMLEncoding = "UTF-8";
48     public static String JavaDoc defaultCharEncoding = "UTF-8";
49
50     static {
51         try {
52             // (for now, always use UTF-8, explore using the platform default later)
53
/*OutputStreamWriter temp = new OutputStreamWriter(System.out);
54              String charEncoding = temp.getEncoding();
55              if (charEncoding.startsWith("ISO")) {
56              charEncoding = charEncoding.substring(3);
57              }
58              String XMLEncoding = MIME2Java.reverse(charEncoding);
59              if (XMLEncoding != null) {
60              defaultCharEncoding = charEncoding;
61              defaultXMLEncoding = XMLEncoding;
62              } else {
63              System.err.println("Java encoding "+charEncoding+" is not supported");
64              }*/

65             URL.setURLStreamHandlerFactory(new com.ibm.webdav.protocol.URLStreamHandlerFactory());
66         } catch (Error JavaDoc exc) {
67         }
68     }
69
70     //------------------------------------------------------------------------------------
71

72     protected URL url = null; // the resource URL, key, or identifier
73
protected TargetSelector targetSelector; // identifier for revision selector
74

75     // contexts for communicating HTTP and WebDAV headers (method contol couples)
76
protected ResourceContext context = new ResourceContext();
77     protected IRResource impl = null; // the implementation to delegate to
78

79     // cache the contents to avoid unnecessary trips to the server
80
protected byte[] cachedContents = null;
81 /** The default constructor. Should be rarely used.
82  */

83 public Resource() {
84     this.url = null;
85 }
86 /** A copy constructor. This copies by reference so the resources share the
87  * same URL and contexts. TODO: probably should clone.
88  * @param resource the resource to copy
89  * @exception com.ibm.webdav.WebDAVException
90  */

91 public Resource(Resource resource) throws WebDAVException {
92     this.url = resource.url;
93     this.context = resource.context;
94     this.targetSelector = resource.targetSelector;
95     this.impl = ResourceFactory.createResource(url, null);
96 }
97 /** Construct a Resource with the given URL. This is the constructor most clients
98  * will use to construct and access Resources using WebDAV. The resource having
99  * the url may not exist as this constructor does not access the resource from
100  * the server. Use exists() or attmept to get the contents of the resource to
101  * see if it exists. Other constructors are provided using parameters for the
102  * various parts of the URL. See java.net.URLConnection for details. A ResourceFactory
103  * may also be used to construct instances of a Resource.
104  *
105  * @param url the URL of the resource.
106  * @exception com.ibm.webdav.WebDAVException
107  * @see URLConnection
108  * @see com.ibm.webdav.ResourceFactory
109  */

110 public Resource(String JavaDoc url) throws WebDAVException {
111    try {
112       initialize(new URL(url), null);
113    } catch (java.io.IOException JavaDoc exc) {
114       throw new WebDAVException(WebDAVStatus.SC_BAD_REQUEST, "Bad URL");
115    }
116 }
117 /** Construct a Resource with the given URL. The resource having
118  * the url may not exist as this constructor does not access the resource from
119  * the server. Use exists() or attmept to get the contents of the resource to
120  * see if it exists. Other constructors are provided using parameters for the
121  * various parts of the URL. See java.net.URLConnection for details. A ResourceFactory
122  * may also be used to construct instances of a Resource.
123  *
124  * @param url the URL of the resource.
125  * @param targetSelector the revision target selector for this Collection
126  * @exception java.io.IOException
127  * @see URLConnection
128  * @see com.ibm.webdav.ResourceFactory
129  */

130 public Resource(String JavaDoc url, TargetSelector targetSelector) throws WebDAVException {
131    try {
132       initialize(new URL(url), targetSelector);
133    } catch (java.io.IOException JavaDoc exc) {
134       throw new WebDAVException(WebDAVStatus.SC_BAD_REQUEST, "Bad URL");
135    }
136 }
137 /** Create a Resource from the given URL components.
138  * @param protocol the protocol to use, http:, rmi:, or iiop:
139  * @param host the name or IP addres of the server host. Using the client host name,
140  * or 'localhost' without a port uses local access with no RPC or server required.
141  * @param port the TCP port to use. HTTP uses 80 by default.
142  * @param file the resource URL relative to the server including any query string, etc.
143  * @exception WebDAVException
144  * @see URLConnection
145  * @see com.ibm.webdav.ResourceFactory
146  */

147 public Resource(String JavaDoc protocol, String JavaDoc host, int port, String JavaDoc file) throws WebDAVException {
148    try {
149       initialize(new URL(protocol, host, port, file), null);
150    } catch (java.io.IOException JavaDoc exc) {
151       throw new WebDAVException(WebDAVStatus.SC_BAD_REQUEST, "Bad URL");
152    }
153 }
154 /** Create a Resource from the given URL components. This constructor uses the default
155  * HTTP port.
156  * @param protocol the protocol to use, http:, rmi:, or iiop:
157  * @param host the name or IP addres of the server host. Using the client host name,
158  * or 'localhost' without a port uses local access with no RPC or server required.
159  * @param file the resource URL relative to the server including any query string, etc.
160  * @exception com.ibm.webdav.WebDAVException
161  * @see URLConnection
162  * @see com.ibm.webdav.ResourceFactory
163  */

164 public Resource(String JavaDoc protocol, String JavaDoc host, String JavaDoc file) throws WebDAVException {
165    try {
166       initialize(new URL(protocol, host, file), null);
167    } catch (java.io.IOException JavaDoc exc) {
168       throw new WebDAVException(WebDAVStatus.SC_BAD_REQUEST, "Bad URL");
169    }
170 }
171 /** Construct a Resource with the given URL. The resource having
172  * the url may not exist as this constructor does not access the resource from
173  * the server. Use exists() or attmept to get the contents of the resource to
174  * see if it exists. Other constructors are provided using parameters for the
175  * various parts of the URL. See java.net.URLConnection for details. A ResourceFactory
176  * may also be used to construct instances of a Resource.
177  *
178  * @param url the URL of the resource.
179  * @exception java.io.IOException
180  * @see URLConnection
181  * @see com.ibm.webdav.ResourceFactory
182  */

183 public Resource(URL url) throws WebDAVException {
184    try {
185       initialize(url, null);
186    } catch (java.io.IOException JavaDoc exc) {
187       throw new WebDAVException(WebDAVStatus.SC_BAD_REQUEST, "Bad URL");
188    }
189 }
190 /** Construct a Resource with the given URL. The resource having
191  * the url may not exist as this constructor does not access the resource from
192  * the server. Use exists() or attmept to get the contents of the resource to
193  * see if it exists. Other constructors are provided using parameters for the
194  * various parts of the URL. See java.net.URLConnection for details. A ResourceFactory
195  * may also be used to construct instances of a Resource.
196  *
197  * @param url the URL of the resource.
198  * @param targetSelector the revision target selector for this Collection
199  * @exception java.io.IOException
200  * @see URLConnection
201  * @see com.ibm.webdav.ResourceFactory
202  */

203 public Resource(URL url, TargetSelector targetSelector) throws WebDAVException {
204    try {
205       initialize(url, targetSelector);
206    } catch (java.io.IOException JavaDoc exc) {
207       throw new WebDAVException(WebDAVStatus.SC_BAD_REQUEST, "Bad URL");
208    }
209 }
210 /** Construct a Resource with the given URL specification in the given context. The resource having
211  * the url may not exist as this constructor does not access the resource from
212  * the server. Use exists() or attmept to get the contents of the resource to
213  * see if it exists. Other constructors are provided using parameters for the
214  * various parts of the URL. See java.net.URLConnection for details. A ResourceFactory
215  * may also be used to construct instances of a Resource.
216  *
217  * @param context a URL giving the context in which the spec is evaluated
218  * @param spec a URL whose missing parts are provided by the context
219  * @exception com.ibm.webdav.WebDAVException
220  * @see URLConnection
221  * @see com.ibm.webdav.ResourceFactory
222  */

223 public Resource(URL context, String JavaDoc spec) throws WebDAVException {
224    try {
225       initialize(new URL(context, spec), null);
226    } catch (java.io.IOException JavaDoc exc) {
227       throw new WebDAVException(WebDAVStatus.SC_BAD_REQUEST, "Bad URL");
228    }
229 }
230 /**
231  * Add a label to this revision of a versioned resource. The
232  * versioned resource must not already have the label on any
233  * revision, and the label cannot be the same as any revision
234  * id. The label must be removed from one revision before it
235  * can be added to a different revision. The operation will
236  * fail if the resource is not a versioned resource.
237  * <p>
238  * Labels are used to provide meaningful names that distinguish
239  * revisions of versioned resources. They can be used in the revision
240  * selection rule of the workspace to specify what revision should
241  * be used in that workspace. A specific label may be used to override
242  * the workspace to access revisions.
243  * <p>
244  * A revision does not need to be checked out to add a label.
245  *
246  * @param label the label to add to the labels used to identify
247  * this revision
248  * @exception com.ibm.webdav.WebDAVException
249  */

250 public void addLabel(String JavaDoc label) throws WebDAVException {
251 }
252 /** Add properties to a resource.
253  *
254  * @param names an array of property names
255  * @param value an array of property values
256  * @exception com.ibm.webdav.WebDAVException
257  */

258 public MultiStatus addProperties( PropertyName[] names, Element[] values) throws WebDAVException {
259         // create a propertyupdate document to set the values
260
Document document = null;
261         try {
262         document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
263     } catch(Exception JavaDoc e) {
264           throw new WebDAVException(WebDAVStatus.SC_PROCESSING,"Parsing problem");
265         }
266         //document.setVersion(Resource.XMLVersion);
267
//document.setEncoding(Resource.defaultXMLEncoding);
268

269     Element propertyUpdate = document.createElementNS("DAV:","D:propertyupdate");
270     propertyUpdate.setAttribute("xmlns:D", "DAV:");
271     document.appendChild(propertyUpdate);
272     Element set = document.createElementNS("DAV:","D:set");
273     propertyUpdate.appendChild(set);
274     Element prop = document.createElementNS("DAV:","D:prop");
275     set.appendChild(prop);
276     for (int i = 0; i < names.length; i++) {
277         prop.appendChild((Element) values[i]);
278     }
279     return setProperties(document);
280 }
281 /** Add a property to a resource
282  *
283  * @param name the property name
284  * @param value the property value
285  * @exception com.ibm.webdav.WebDAVException
286  */

287 public void addProperty( PropertyName name, Element value) throws WebDAVException {
288     PropertyName[] names = new PropertyName[1];
289     names[0] = name;
290     Element[] values = new Element[1];
291     values[0] = value;
292     MultiStatus result = addProperties(names, values);
293
294     // raise any necessary exceptions
295
if (result.getResponses().hasMoreElements()) {
296         Response response = (Response) result.getResponses().nextElement();
297         if (response instanceof MethodResponse) {
298             int status = ((MethodResponse) response).getStatus();
299             if (status != WebDAVStatus.SC_OK) {
300                 throw new WebDAVException(status, WebDAVStatus.getStatusMessage(status));
301             }
302         } else {
303             PropertyValue propertyValue = (PropertyValue) ((PropertyResponse) response).getPropertiesByPropName().elements().nextElement();
304             if ((propertyValue.status != WebDAVStatus.SC_OK) && (propertyValue.status != WebDAVStatus.SC_FAILED_DEPENDENCY)) {
305                 throw new WebDAVException(propertyValue.status, WebDAVStatus.getStatusMessage(propertyValue.status));
306             }
307         }
308     }
309 }
310 /**
311  * Cancel the checkout of this working resource, delete the
312  * working resource, and remove any predecessor/successor
313  * relationships created by checkout or merge. An exception
314  * is raised if the resource is not currently checked out.
315  *
316  * @exception com.ibm.webdav.WebDAVException
317  */

318 public void cancelCheckOut() throws WebDAVException {
319 }
320 /**
321  * Checkin a resource creating a new immutable revision and
322  * releasing the revision so other user agents may subsequently
323  * check it out.
324  *
325  * @exception com.ibm.webdav.WebDAVException
326  */

327 public void checkin() throws WebDAVException {
328 }
329 /**
330  * Checkin a resource releasing it so other user agents may check
331  * it out. If overwrite is false, create a new revision and set
332  * the predecessor and successor relationships. If overwrite is
333  * true, the revision is updated in place and the previous contents
334  * are lost. Effectively, no new revision is created, and the revision
335  * id now refers to the updated revision. Overwrite will fail if the
336  * revision being overwritten is not mutable.
337  * <p>
338  * If makeCurrentTarget is true, this revision becomes the default target
339  * for the versioned resource. Otherwise the current target is unchanged.
340  *
341  * @param activity the activity associted with the changes made in this revision
342  * @param makeCurrentTarget true means the new revision becomes the
343  * target for the versioned resource. Otherwise the target is unchanged.
344  * @param overwrite ture means overwrite the existing revision,
345  * false means create a new revision.
346  * @exception com.ibm.webdav.WebDAVException
347  */

348 public void checkin(Activity activity, boolean makeCurrentTarget, boolean overwrite) throws WebDAVException {
349 }
350 /**
351  * Checkin a resource releasing it so other user agents may check
352  * it out. If overwrite is false, create a new revision and set
353  * the predecessor and successor relationships. If overwrite is
354  * true, the revision is updated in place and the previous contents
355  * are lost. Effectively, no new revision is created, and the revision
356  * id now refers to the updated revision. Overwrite will fail if the
357  * revision being overwritten is not mutable.
358  * <p>
359  * If makeCurrentTarget is true, this revision becomes the default target
360  * for the versioned resource. Otherwise the current target is unchanged.
361  *
362  * @param makeCurrentTarget true means the new revision becomes the
363  * target for the versioned resource. Otherwise the target is unchanged.
364  * @param overwrite ture means overwrite the existing revision,
365  * false means create a new revision.
366  * @exception com.ibm.webdav.WebDAVException
367  */

368 public void checkin(boolean makeCurrentTarget, boolean overwrite) throws WebDAVException {
369 }
370 /**
371  * Check out a resource in order to create a new working resource.
372  * A resource is checked out in the context of the workspace, and
373  * can only be checked out once in a given activity. The workspace
374  * to use can be set in the request context. Checkout control
375  * on versioned may be managed by locking the versioned resource or a
376  * revision before checking out a revision.
377  * <p>
378  * CheckOut fails is the resource is not a versioned resource, is
379  * currently checked out in the current activity, or the versioned
380  * <p>
381  * resource or revision is locked by another user. CheckOut also
382  * fails if the current activity or workspace is locked. If the
383  * versioned resource or revision is locked, the request context
384  * must include a precondition containing the lock token.
385  * <p>
386  * If workspace is null, the server will return a workspace that
387  * can be subsequently used to access the checked out working
388  * resource.
389  *
390  * @return the TargetSelector for this working resource
391  * @exception com.ibm.webdav.WebDAVException
392  */

393 public TargetSelector checkOut() throws WebDAVException {
394     return checkOut(null);
395 }
396 /**
397  * Check out a resource in order to create a new working resource.
398  * A resource is checked out in the context of the workspace, and
399  * can only be checked out once in a given activity. The workspace
400  * to use can be set in the request context. Checkout control
401  * on versioned may be managed by locking the versioned resource or a
402  * revision before checking out a revision.
403  * <p>
404  * CheckOut fails is the resource is not a versioned resource, is
405  * currently checked out in the current activity, or the versioned
406  * <p>
407  * resource or revision is locked by another user. CheckOut also
408  * fails if the current activity or workspace is locked. If the
409  * versioned resource or revision is locked, the request context
410  * must include a precondition containing the lock token.
411  * <p>
412  * If workspace is null, the server will return a workspace that
413  * can be subsequently used to access the checked out working
414  * resource.
415  *
416  * @param workspace the Workspace in which the revision is checked out.
417  * @return the TargetSelector for this working resource
418  * @exception com.ibm.webdav.WebDAVException
419  */

420 public TargetSelector checkOut(Workspace workspace) throws WebDAVException {
421     return null;
422 }
423 /**
424  * Create a new revision of this resource, but keep it checked
425  * out. If overwrite is false, create a new revision and set
426  * the predecessor and successor relationships. If overwrite is
427  * true, the revision is updated in place and the previous contents
428  * are lost. Effectively, no new revision is created, and the revision
429  * id now refers to the updated revision. Overwrite will fail if the
430  * revision being overwritten is not mutable.
431  * <p>
432  * If makeCurrentTarget is true, this revision becomes the default target
433  * for the versioned resource. Otherwise the current target is unchanged.
434  *
435  * @param makeCurrentTarget true means the new revision becomes the
436  * target for the versioned resource. Otherwise the target is unchanged.
437  * @param overwrite ture means overwrite the existing revision,
438  * false means create a new revision.
439  * @exception com.ibm.webdav.WebDAVException
440  */

441 public void checkPoint(boolean makeCurrentTarget, boolean overwrite) throws WebDAVException {
442 }
443 /** This method must be called after the client has completed writing to the contents
444  * output stream that was obtained from <code>getContentsOutputStream()</code>.
445  * @exception com.ibm.webdav.WebDAVException
446  */

447 public void closeContentsOutputStream() throws WebDAVException {
448     this.closeContentsOutputStream(null);
449 }
450 /** Copy this resource to the destination URL. The destination resource must not already exist.
451  * Partial results are possible, check the returned status for details.
452  *
453  * @param destinationURL the destination
454  *
455  * @return the status of the copy operation for each resource copied
456  * @exception com.ibm.webdav.WebDAVException
457  */

458 public MultiStatus copy(String JavaDoc destinationURL) throws WebDAVException {
459     return copy(destinationURL, true, null);
460 }
461 /** Copy this resource to the destination URL.
462  * Partial results are possible, check the returned status for details.
463  *
464  * @param destinationURL the destination
465  * @param overwrite true implies overrite the destination if it exists
466  * @param propertiesToCopy a collection of properties that must be copied or
467  * the method will fail. propertiesToCopy may have one of the following values:
468  * <ul>
469  * <li>null - ignore properties that cannot be copied</li>
470  * <li>empty collection - all properties must be copied or the method will fail</li>
471  * <li>a collection of URIs - a list of the properties that must be copied
472  * or the method will fail</li>
473  * </ul>
474  *
475  * @return the status of the copy operation for each resource copied
476  * @exception com.ibm.webdav.WebDAVException
477  */

478 public MultiStatus copy(String JavaDoc destinationURL, boolean overwrite, Vector propertiesToCopy) throws WebDAVException {
479     flushCaches();
480     return impl.copy(context, destinationURL, overwrite, propertiesToCopy);
481 }
482 /** Delete this resouce from the server. The actual effect of the delete operation is
483  * determined by the underlying repository manager. The visible effect to WebDAV
484  * is that the resource is no longer available.
485  *
486  * @return a MultiStatus containing the status of the delete method on each
487  * effected resource.
488  * @exception com.ibm.webdav.WebDAVException
489  */

490 public MultiStatus delete() throws WebDAVException {
491     flushCaches();
492     return impl.delete(context);
493 }
494 /**
495  * Return an XML document describing the differences between two
496  * revisions, both contents and properties.
497  *
498  * @return an XML document describing the differences between
499  * the given resource and this resource
500  * @exception com.ibm.webdav.WebDAVException
501  */

502 public Document differencesWith(Resource resource) throws WebDAVException {
503     return null;
504 }
505 /** Two Resources are equal if they have the same URL. In this case, port
506  * number -1 and port number 80 are considered the same port for equality
507  * purposes.
508  * @return true if the resources have URLs indicating the same server resource.
509  * @exception com.ibm.webdav.WebDAVException
510  */

511 public boolean equals(Resource resource) throws WebDAVException {
512     URL resourceURL = resource.getURL();
513
514     int thisPort = url.getPort() == -1 ? 80 : url.getPort();
515     int resourcePort = resourceURL.getPort() == -1 ? 80 : resourceURL.getPort();
516     return url.getProtocol().equals(resourceURL.getProtocol()) && thisPort == resourcePort && url.getFile().equals(resourceURL.getFile());
517 }
518 /** See if the contents of this resource exists. A resource exists
519  * if it has contents or state maintained by a server.
520  *
521  * @return true if the contents exists, false otherwise
522  * @exception com.ibm.webdav.WebDAVException
523  */

524 public boolean exists() throws WebDAVException {
525     boolean exists = true;
526     InputStream is = null;
527     try {
528         is = getContentsInputStream();
529     } catch (WebDAVException exc) {
530                 if (exc.getStatusCode() == WebDAVStatus.SC_NOT_FOUND) {
531             exists = false;
532         }
533     }
534
535         return exists;
536 }
537 /** Flush any caches so that subsequent methods obtain fresh data from the server.
538  * @exception com.ibm.webdav.WebDAVException
539  */

540 public void flushCaches() throws WebDAVException {
541     cachedContents = null;
542 }
543 /** Get the active lock on this resource owned by the given principal if any.
544  * NOTE: this method cannot be reliably implemented based on version 10 of
545  * the WebDAV spec as an activelock element in a lockdiscovery does not contain
546  * the authorization credentials of the owner of the lock. For now, this method
547  * relies on an additional principal element in the activelock that contains
548  * the required id. This is an IBM EXTENSTION. When WebDAV ACLs are introduced,
549  * the principal will likely be added to the activelock element.
550  *
551  * @param principal the authorization id of the requesting principal
552  *
553  * @return the active lock owned by that principal or null if the resource is
554  * not locked by that principal.
555  * @exception com.ibm.webdav.WebDAVException
556  */

557 public ActiveLock getActiveLockFor(String JavaDoc principal) throws WebDAVException {
558     Enumeration locks = getLocks().elements();
559     ActiveLock ownedLock = null;
560     while (ownedLock == null && locks.hasMoreElements()) {
561         ActiveLock lock = (ActiveLock) locks.nextElement();
562         if (lock.getPrincipal().equals(principal)) {
563             ownedLock = lock;
564         }
565     }
566     return ownedLock;
567 }
568 /**
569  * Get the activity this revision was created in. Returns null
570  * for un-versioned resources or revisions that weren't
571  * updated in an activity.
572  *
573  * @return the Activity used to create this revision if any
574  * @exception com.ibm.webdav.WebDAVException
575  */

576 public Activity getActivity() throws WebDAVException {
577     return null;
578 }
579 /** Get the contents of this resource. This method does not decode text contents. The
580  * caller should convert the result to a String using a character set based on the
581  * contentType.
582  *
583  * @return the contents as a byte array
584  * @exception com.ibm.webdav.WebDAVException
585  */

586 public byte[] getContents() throws WebDAVException {
587     try {
588         if (cachedContents == null) {
589             InputStream is = getContentsInputStream();
590             int length = (int) getResponseContext().contentLength();
591             if (length != -1) {
592                 int rcvd = 0;
593                 int size = 0;
594                 cachedContents = new byte[length];
595                 do {
596                     size += rcvd;
597                     rcvd = is.read(cachedContents, size, length - size);
598                 } while (size < length && rcvd != -1);
599                 if (rcvd == -1)
600
601                     // premature EOF
602
cachedContents = resizeArray(cachedContents, size);
603             } else {
604                 cachedContents = new byte[0];
605                 int inc = 8192;
606                 int off = cachedContents.length;
607                 int rcvd = 0;
608                 do {
609                     off += rcvd;
610                     cachedContents = resizeArray(cachedContents, off + inc);
611                     rcvd = is.read(cachedContents, off, inc);
612                 } while (rcvd != -1);
613                 cachedContents = resizeArray(cachedContents, off);
614             }
615             is.close();
616         }
617     } catch (WebDAVException exc) {
618         throw exc;
619     } catch (java.io.IOException JavaDoc exc) {
620         throw new WebDAVException(WebDAVStatus.SC_INTERNAL_SERVER_ERROR, "IO Error");
621     }
622     return cachedContents;
623 }
624 /** Get an InputStream for accessing the contents of this resource. This method may provide
625  * more efficient access for resources that have large contents. Clients may want to create
626  * a Reader to perform appropriate character conversions on this stream.
627  *
628  * @return an InputStream on the contents
629  * @exception com.ibm.webdav.WebDAVException
630  */

631 public InputStream getContentsInputStream() throws WebDAVException {
632     InputStream is = null;
633     if (cachedContents != null) {
634         is = new ByteArrayInputStream(cachedContents);
635     } else {
636         is = impl.getContentsInputStream(context);
637     }
638         return is;
639 }
640 /** Get an OutputStream for setting the contents of this resource. This method may provide
641  * more efficient access for resources that have large contents. Remember to call
642  * closeContentsOutputStream() when all the data has been written.
643  *
644  * @return an OutputStream to set the contents
645  * @exception com.ibm.webdav.WebDAVException
646  */

647 public OutputStream getContentsOutputStream() throws WebDAVException {
648     flushCaches();
649     return impl.getContentsOutputStream(context);
650 }
651 /**
652  * Return all the labels on this revision, not including its revision id.
653  *
654  * @return an Enumeration of revision labels that identify this revision
655  * @exception com.ibm.webdav.WebDAVException
656  */

657 public Enumeration getLabels() throws WebDAVException {
658     return null;
659 }
660 /** Get the locks that exist on this resource.
661  *
662  * @return a Vector of ActiveLock objects
663  * @exception com.ibm.webdav.WebDAVException
664  */

665 public Vector getLocks() throws WebDAVException {
666     PropertyValue p = getProperty( PropertyName.createPropertyNameQuietly("DAV:lockdiscovery") );
667     Element lockdiscovery = null;
668     if (p != null) {
669         lockdiscovery = p.value;
670     }
671     Vector allLocks = new Vector();
672     if (lockdiscovery != null) {
673         NodeList activeLocks = ((Element) lockdiscovery).getElementsByTagNameNS("DAV:", "activelock");
674         Element activeLock = null;
675         for (int i = 0; i < activeLocks.getLength(); i++) {
676             activeLock = (Element) activeLocks.item(i);
677             allLocks.addElement(new ActiveLock(activeLock));
678         }
679     }
680     return allLocks;
681 }
682 /**
683  * Return a list of activities on different lines of descent
684  * for this revision that are candidates for merging. Returns
685  * null if the resource is not a versioned resource.
686  *
687  * @return an Enumeration of Activities that specify revisions
688  * on different lines of descent.
689  * @exception com.ibm.webdav.WebDAVException
690  */

691 public Enumeration getMergeCandidates() throws WebDAVException {
692     return null;
693 }
694 /**
695  * Get the predecessors of this revision that were established
696  * by merging changes from another activity. The list may be empty.
697  *
698  * @return an Enumeration of Resources that are the merge
699  * predecessors of this revision.
700  * @exception com.ibm.webdav.WebDAVException
701  */

702 public Enumeration getMergePredecessors() throws WebDAVException {
703     return null;
704 }
705
706 /** This method can be used for obtaining meta-information about this resource without
707  * actually reading the resource contents. This meta-information is maintained by the server
708  * in addition to the resource properties.</p>
709  * <p>
710  * After this call, the resource context has been updated and
711  * <code>getStatusCode()</code>, <code>getStatusMessage()</code>, and <code>getResponseContext()</code>
712  * as well as all the ResourceContext methods return updated values based on the current
713  * state of the resource.</p>
714  * <p>This methods corresponds to the HTTP HEAD method.</p>
715  *
716  * @exception com.ibm.webdav.WebDAVException
717  */

718 public void getMetaInformation() throws WebDAVException {
719     if (cachedContents != null) {
720         return; // already have them
721
}
722     impl.getMetaInformation(context);
723 }
724 /**
725  * A resource may have a number of mutable properties. These are
726  * properties that may change even when the resource is checked in.
727  * Changes to these properties does not require a new revision.
728  *
729  * @return an Enumeration of the mutable properties of this resource
730  * @exception com.ibm.webdav.WebDAVException
731  */

732 public Enumeration getMutableProperties() throws WebDAVException {
733     return null;
734 }
735
736 /**
737  * Get the options for this resource. Versioning options
738  * are established by the server and include:
739  * <ul>
740  * <li>Mutable/immutable revisions</li>
741  * <li>Supports multiple activities </li>
742  * <li>Is automatically versioned</li>
743  * </ul>
744  *
745  * @return an XML Element containing the options for
746  * this resource
747  * @exception com.ibm.webdav.WebDAVException
748  */

749 public Element getOptions() throws WebDAVException {
750     return null;
751 }
752
753 /** Get the collection containing this resource.
754  *
755  * @return the parent collection
756  * @exception com.ibm.webdav.WebDAVException
757  */

758 public Collection getParentCollection() throws WebDAVException {
759     String JavaDoc parentURL = getURL().toString();
760
761     int delimiterPosition = 0;
762     if (parentURL.endsWith("/")) {
763         delimiterPosition = parentURL.substring(0, parentURL.length() - 1).lastIndexOf("/");
764     } else {
765         delimiterPosition = parentURL.lastIndexOf("/");
766     }
767     parentURL = parentURL.substring(0, delimiterPosition + 1);
768     Collection parent = null;
769     try {
770         parent = new Collection(parentURL);
771     } catch (WebDAVException exc) {
772         throw exc;
773     }
774     return parent;
775 }
776 /**
777  * Get the predecessor of this revision. That is, get the
778  * revision from which this revision was checked out.
779  * Returns null if the Resource has no predecessor.
780  *
781  * @return the predecessor of this revision or null if the revision
782  * has no successor.
783  * @exception com.ibm.webdav.WebDAVException
784  */

785 public Resource getPredecessor() throws WebDAVException {
786     return null;
787 }
788
789 /** Get all the properties of this resource.
790  *
791  * @return a MultiStatus of PropertyResponses. It should contain only one
792  * response element.
793  * @see com.ibm.webdav.MultiStatus
794  * @see com.ibm.webdav.PropertyResponse
795  * @exception com.ibm.webdav.WebDAVException
796  */

797 public MultiStatus getProperties() throws WebDAVException {
798     return impl.getProperties(context);
799 }
800 /** Get the named properties of this resource.
801  *
802  * @param names an arrary of property names to retrieve
803  *
804  * @return a MultiStatus of PropertyResponses
805  * @exception com.ibm.webdav.WebDAVException
806  * @see com.ibm.webdav.PropertyResponse
807  */

808 public MultiStatus getProperties( PropertyName names[]) throws WebDAVException {
809     return impl.getProperties(context, names);
810 }
811 /** Get the value of the given property for this resource.
812  *
813  * @param name the name of the property to retrieve
814  *
815  * @return PropertyValue or null if the resource does not have the requested property
816  * @exception com.ibm.webdav.WebDAVException
817  */

818 public PropertyValue getProperty( PropertyName name) throws WebDAVException {
819     PropertyName[] names = new PropertyName[1];
820     names[0] = name;
821     Enumeration responses = getProperties(names).getResponses();
822     PropertyResponse response = (PropertyResponse) responses.nextElement();
823     Dictionary properties = response.getPropertiesByPropName();
824     return (PropertyValue) properties.get(name);
825 }
826 /** Get the names of all properties for this resource. The result is similar to
827  * getProperties(), but the properties have no values.
828  *
829  * @return a MultiStatus of PropertyResponses
830  * (PropertyValue.value is always null, PropertyValue.status contains the status)
831  * @exception com.ibm.webdav.WebDAVException
832  * @see com.ibm.webdav.PropertyResponse
833  */

834 public MultiStatus getPropertyNames() throws WebDAVException {
835     return impl.getPropertyNames(context);
836 }
837 /** Get the request context for this resource. The context contains information
838  * used by methods on a resource when the method is called.
839  *
840  * @return the ResourceContext providing information that controls
841  * method execution.
842  * @exception com.ibm.webdav.WebDAVException
843  */

844 public HTTPHeaders getRequestContext() throws WebDAVException {
845     return context.getRequestContext();
846 }
847 /** Get the response context for this resource. The context contains information
848  * returned from invocations of methods on a resource.
849  *
850  * @return the ResourceContext providing information that
851  * is returned by method execution.
852  * @exception com.ibm.webdav.WebDAVException
853  */

854 public HTTPHeaders getResponseContext() throws WebDAVException {
855     return context.getResponseContext();
856 }
857 public ResourceContext getContext() {
858   return context;
859 }
860
861 /**
862  * Get the revision history for a versioned resource. The revision
863  * history lists the revisions of a resource and their predecessors
864  * and successors. The format of the document is given in section
865  * Revision History. The document will not contain any revisions
866  * if the resource is not versioned.
867  *
868  * @return an XML document containing the revision history of the
869  * associated versioned resource.
870  * @exception com.ibm.webdav.WebDAVException
871  */

872 public Document getRevisionHistory() throws WebDAVException {
873     return null;
874 }
875
876 /**
877  * Get the system-assigned revision id for this revision. This
878  * revision name cannot be changed, and cannot be reused if
879  * this revision is deleted. Returns NULL if the resource is
880  * not versioned.
881  * <p>
882  * The revision id must be unique for the revision across all
883  * time. Servers may choose to use an opaque identifier consisting
884  * of a time stamp similar to UUIDs for lock tokens.
885  *
886  * @return the revision id of this revision of a versioned resource
887  * @exception com.ibm.webdav.WebDAVException
888  */

889 public String JavaDoc getRevisionId() throws WebDAVException {
890     return null;
891 }
892
893 /** Get the status code corresponding to the last method execution.
894  *
895  * @return the status code as defined by HTTP/1.1 and the WebDAV extensions.
896  * @exception com.ibm.webdav.WebDAVException
897  */

898 public int getStatusCode() throws WebDAVException {
899     return context.getStatusCode().getStatusCode();
900 }
901 /** Get the status message corresponding to the last method execution.
902  *
903  * @return the status message as defined by HTTP/1.1 and the WebDAV extensions.
904  * @exception com.ibm.webdav.WebDAVException
905  */

906 public String JavaDoc getStatusMessage() throws WebDAVException {
907     return context.getStatusCode().getStatusMessage();
908 }
909 /**
910  * Get the immediate successors of this revision. That is, get the revisions
911  * that were created by checking out this revision.
912  * The list may be empty.
913  *
914  * @return an Enumeration of Resources that are
915  * successors of this revision.
916  * @exception com.ibm.webdav.WebDAVException
917  */

918 public Enumeration getSuccessors() throws WebDAVException {
919     return null;
920 }
921
922 /** Get the TargetSelector that identifies this resource revision.
923  *
924  * @return the TargetSelector for this revision
925  * @exception com.ibm.webdav.WebDAVException
926  */

927 public TargetSelector getTargetSelector() throws WebDAVException {
928     return targetSelector;
929 }
930 /** Get the name that identifies this resource.
931  *
932  * @return the URL for this resource
933  * @exception com.ibm.webdav.WebDAVException
934  */

935 public URL getURL() throws WebDAVException {
936     return url;
937 }
938 /**
939  * Get the system-assigned working resource id for this revision.
940  * Returns NULL if the resource is not versioned or is not checked out.
941  * <p>
942  * The working resource id must be unique for all working resources
943  * of this revision. Servers may choose to use an opaque identifier consisting
944  * of a time stamp similar to UUIDs for lock tokens.
945  *
946  * @return the working resource id of this working resource of a revision of
947  * a versioned resource
948  * @exception com.ibm.webdav.WebDAVException
949  */

950 public String JavaDoc getWorkingResourceId() throws WebDAVException {
951     return null;
952 }
953
954 /**
955  * Get the current working resources of this revision. Returns an
956  * empty Enumeration if this revision has no current working resources.
957  * Returns null if this resource is not a revision.
958  *
959  * @return An Enumeration of current working resources of this VersionedResource
960  * @exception com.ibm.webdav.WebDAVException
961  */

962 public Enumeration getWorkingResources() throws WebDAVException {
963     return null;
964 }
965 /** Initialize this collection instance. Make sure the URL ends in a '/'.
966 */

967 protected void initialize(URL url, TargetSelector targetSelector) throws WebDAVException {
968     try {
969         this.url = url;
970         this.targetSelector = targetSelector;
971         impl = ResourceFactory.createResource(url, targetSelector);
972                 
973     } catch (Exception JavaDoc exc) {
974         throw new WebDAVException(WebDAVStatus.SC_BAD_REQUEST, "Malformed URL");
975     }
976 }
977 /**
978  * A resource can be automatically versioned on each method
979  * that updates its state (content or properties). Non-versioning
980  * aware clients use automatic versioning to support updates. If
981  * a resource is not automatically versioned, attempts to update
982  * the revision without explicitly checking it out first will fail.
983  *
984  * @return true if this resource is automatically versioned,
985  * false if not.
986  * @exception com.ibm.webdav.WebDAVException
987  */

988 public boolean isAutomaticallyVersioned() throws WebDAVException {
989     return false;
990 }
991
992 /**
993  * Return true if this revision is checked out in the given activity.
994  * The activity may be null to see if the revision was checked out
995  * without using an activity.
996  *
997  * @param activity the Activity to check for
998  * @return boolean return true if this revision is checked out in the
999  * given activity
1000 * @exception com.ibm.webdav.WebDAVException
1001 */

1002public boolean isCheckedOut(Activity activity) throws WebDAVException {
1003    return false;
1004}
1005/** Returns true if this Resource is a collection. Returns false otherwise.
1006 *
1007 * @return true if this Resource is a collection.
1008 * @exception com.ibm.webdav.WebDAVException
1009 */

1010public boolean isCollection() throws WebDAVException {
1011    boolean isCollection = false;
1012    PropertyValue pv = getProperty(PropertyName.pnResourcetype);
1013    if (pv != null) {
1014        Element resourcetype = (Element) pv.value;
1015        if (resourcetype.getElementsByTagNameNS("DAV:", "collection") != null) {
1016            isCollection = true;
1017        }
1018    }
1019    return isCollection;
1020}
1021/**
1022 * Return true if any revision of this versioned resource is
1023 * labeled with the given label
1024 *
1025 * @param label the label to check
1026 * @return true if this revision is labeled with the given label
1027 * @exception com.ibm.webdav.WebDAVException
1028 */

1029public boolean isLabeledWith(String JavaDoc label) throws WebDAVException {
1030    return false;
1031}
1032/** See if this resource is locked.
1033 *
1034 * @return true if this resource is locked, false otherwise.
1035 * @exception com.ibm.webdav.WebDAVException
1036 */

1037public boolean isLocked() throws WebDAVException {
1038    // see if there are any active locks
1039
return !getLocks().isEmpty();
1040}
1041/** Is this resource locked by the current authorized user? That is, does the
1042 * current user have sufficient locking access to modify this resource. The
1043 * method, like all methods that do modify the resource, must have a precondition
1044 * set in the context containing the lock token of the resource owned by this
1045 * user. The user is set in the request context using the authorization method.
1046 * @return true if this resource is locked by the principal in the context
1047 * sufficient to modify the resource.
1048 * @exception com.ibm.webdav.WebDAVException
1049 * @see com.ibm.webdav.ResourceContext#authorization
1050 */

1051public boolean isLockedByMe() throws WebDAVException {
1052    String JavaDoc principal = getRequestContext().getAuthorizationId();
1053    Precondition precondition = getRequestContext().precondition();
1054    if (precondition == null) {
1055        return false; // it is not locked by me.
1056
//raise(new WebDAVException(WebDAVStatus.SC_BAD_REQUEST, "Missing If header containing lock token"));
1057
}
1058
1059    // get the locks on this resource
1060
Enumeration locks = getLocks().elements();
1061    boolean isLockedByMe = false;
1062    // look for a matching lock
1063
while (locks.hasMoreElements()) {
1064        ActiveLock activeLock = (ActiveLock) locks.nextElement();
1065        Condition condition = new Condition(getURL().getFile());
1066        ConditionTerm term = new ConditionTerm();
1067        StateToken stateToken = new StateToken(activeLock.getLockToken());
1068        term.addConditionFactor(stateToken);
1069        condition.addConditionTerm(term);
1070        if (precondition.matches(condition) && activeLock.getPrincipal().equals(principal) && activeLock.getLockType().equals(ActiveLock.writeLock)) {
1071            isLockedByMe = true;
1072            break;
1073        }
1074    }
1075    return isLockedByMe;
1076}
1077/**
1078 * Return true if this revision is mutable. That is, it was checked
1079 * in as a mutable revision. Mutable revisions may be checked in
1080 * overwriting the contents of the revision with the contents of
1081 * the checked out working resource. This allows users to make
1082 * pdates that do not require a new revision.
1083 * <p>
1084 * An immutable revision can never be made mutable, but a new revision
1085 * can be. A mutable revision can be made immutable by checking it out
1086 * in place and checking it back is as immutable.
1087 *
1088 * @return an XML document describing the differences between
1089 * the given resource and this resource
1090 * @exception com.ibm.webdav.WebDAVException
1091 */

1092public boolean isMutable() throws WebDAVException {
1093    return false;
1094}
1095/**
1096 * Return true if this resource is a versioned resource. A versioned
1097 * resource has multiple revisions and a revision history.
1098 *
1099 * @return true if this resource is a versioned resource, false otherwise
1100 * @exception com.ibm.webdav.WebDAVException
1101 */

1102boolean isVersioned() throws WebDAVException {
1103    return false;
1104}
1105/** Exclusively write Lock this resource for all time.
1106 *
1107 * @return detailed information about the lock status of this resource. A MultiStatus
1108 * containing lockdiscovery properties.
1109 * An ActiveLock may be constructed by accessing the lockdiscovery element(s) of the
1110 * returned MultiStatus in order to obtain information about the lock.
1111 *
1112 * @return a MultiStatus containing a lockdiscovery property indicating
1113 * the results of the lock operation.
1114 * @exception com.ibm.webdav.WebDAVException
1115 */

1116public MultiStatus lock(Document document) throws WebDAVException {
1117    String JavaDoc sPrefix = "D";
1118        String JavaDoc userName = System.getProperties().getProperty("user.name");
1119    Element owner = document.createElementNS("DAV:","D:owner");
1120    owner.setAttribute("xmlns:D", "DAV:");
1121    owner.appendChild(document.createTextNode(userName));
1122    return lock(ActiveLock.exclusive, ActiveLock.writeLock, -1, owner);
1123}
1124/** Lock this resource based on the given parameters. This allows control of
1125 * the lock scope (exclusive or shared) the lock type (write), owner information, etc.
1126 *
1127 * @param scope the scope of the lock, exclusive or shared
1128 * @param type the type of the lock, currently only write
1129 * @param timeout the number of seconds before the lock times out or
1130 * -1 for infinite timeout.
1131 * @param owner an XML element containing useful information that can be
1132 * used to identify the owner of the lock. An href to a home page, an
1133 * email address, phone number, etc. Can be null if no owner information
1134 * is provided.
1135 *
1136 * @return a MultiStatus containing a lockdiscovery property indicating
1137 * the results of the lock operation.
1138 * @exception com.ibm.webdav.WebDAVException
1139*/

1140public MultiStatus lock(String JavaDoc scope, String JavaDoc type, int timeout, Element owner) throws WebDAVException {
1141    // remove any lock tokens in the context so we don't try to
1142
// do a refresh by mistake.
1143
getRequestContext().precondition((String JavaDoc) null);
1144    return impl.lock(context, scope, type, timeout, owner);
1145}
1146/** Move this resource to the destination URL.
1147 * The destination resource must not already exist.
1148 * Partial results are possible, check the returned status for details
1149 *
1150 * @param destinationURL the destination
1151 *
1152 * @return the status of the move operation for each resource moved
1153 * @exception com.ibm.webdav.WebDAVException
1154 */

1155public MultiStatus move(String JavaDoc destinationURL) throws WebDAVException {
1156    return move(destinationURL, true, null);
1157}
1158/** Move this resource to the destination URL.
1159 * Partial results are possible, check the returned status for details
1160 *
1161 * @param destinationURL the destination
1162 * @param overwrite true implies overrite the destination if it exists
1163 * @param propertiesToMove a collection of properties that must be moved or
1164 * the method will fail. propertiesToMove may have one of the following values:
1165 * <ul>
1166 * <li>null - ignore properties that cannot be moved</li>
1167 * <li>empty collection - all properties must be moved or the method will fail</li>
1168 * <li>a collection of URIs - a list of the properties that must be moved
1169 * or the method will fail</li>
1170 * </ul>
1171 *
1172 * @return the status of the move operation for each resource moved
1173 * @exception com.ibm.webdav.WebDAVException
1174 */

1175public MultiStatus move(String JavaDoc destinationURL, boolean overwrite, Vector propertiesToMove) throws WebDAVException {
1176    flushCaches();
1177    return impl.move(context, destinationURL, overwrite, propertiesToMove);
1178}
1179/** This method treats this resource as a method or service, and sends its parameter to
1180 * this resource where it is handled in a resource-specific way. For example,
1181 * sending data from an HTML form to a URL representing a Servlet or CGI script that processes
1182 * the form data to produce some result.
1183 *
1184 * @param args a string representing the arguments to the method represented by this URL. The
1185 * arguments are in the form ?parameterName1=value1&amp;parameterName2=value2... as specified
1186 * for URL queries.
1187 *
1188 * @return the results of sending the arguments to the URL
1189 * @exception com.ibm.webdav.WebDAVException
1190 */

1191public byte[] performWith(String JavaDoc args) throws WebDAVException {
1192    flushCaches(); // can't cache the results of a POST
1193
return impl.performWith(context, args);
1194}
1195/** Refresh the lock on this resource by resetting the lock timeout.
1196 * The context must contain the proper authorization for the requesting
1197 * principal.
1198 *
1199 * @param lockToken the lock token identifying the lock.
1200 * @param timeout the new timeout in seconds. -1 means infinite timeout.
1201 *
1202 * @return updated information about the lock status of this resource
1203 * @exception com.ibm.webdav.WebDAVException
1204 */

1205public MultiStatus refreshLock(String JavaDoc lockToken, int timeout) throws WebDAVException {
1206    return impl.refreshLock(context, lockToken, timeout);
1207}
1208/**
1209 * Remove a label from a revision. An exception is raised
1210 * if the revision does not have this label.
1211 * <p>
1212 * A revision does not need to be checked out to add a label.
1213 *
1214 * @param label the label to add to the labels used to identify
1215 * this revision
1216 * @exception com.ibm.webdav.WebDAVException
1217 */

1218public void removeLabel(String JavaDoc label) throws WebDAVException {
1219}
1220/** Remove properties from a resource.
1221 *
1222 * @param names an array of property names
1223 * @exception com.ibm.webdav.WebDAVException
1224 */

1225public MultiStatus removeProperties( PropertyName[] names) throws WebDAVException {
1226    String JavaDoc sPrefix = "D";
1227        Document document = null;
1228
1229        try {
1230          document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
1231    } catch(Exception JavaDoc e) {
1232          throw new WebDAVException(WebDAVStatus.SC_PROCESSING,e.getMessage());
1233        }
1234        //document.setVersion(Resource.XMLVersion);
1235
//document.setEncoding(Resource.defaultXMLEncoding);
1236

1237    Element propertyUpdate = document.createElementNS("DAV:","D:propertyupdate");
1238
1239    propertyUpdate.setAttribute("xmlns:D", "DAV:");
1240    document.appendChild(propertyUpdate);
1241    Element remove = document.createElementNS("DAV:","D:remove");
1242
1243    propertyUpdate.appendChild(remove);
1244    Element prop = document.createElementNS("DAV:","D:prop");
1245
1246    remove.appendChild(prop);
1247    for (int i = 0; i < names.length; i++) {
1248        // we don't care about the property value, only its name. But sending the whole
1249
// value element would work too because it still has the property name.
1250
PropertyName name = names[i];
1251        String JavaDoc prefix = "E";
1252        if (name.ns.equals("DAV:")) {
1253            prefix = "D";
1254        }
1255        Element newel = (Element) document.createElementNS(name.ns,prefix + ":" + name.local );
1256                
1257        if (prefix.equals("E")) {
1258            newel.setAttribute( "xmlns:E", name.ns );
1259        }
1260        prop.appendChild( newel );
1261    }
1262    return setProperties(document);
1263}
1264/** Remove a property from a resource.
1265 *
1266 * @param name the property name
1267 * @exception com.ibm.webdav.WebDAVException
1268 */

1269public void removeProperty( PropertyName name) throws WebDAVException {
1270    PropertyName[] names = new PropertyName[1];
1271    names[0] = name;
1272    MultiStatus result = removeProperties(names);
1273    setStatusCode(WebDAVStatus.SC_OK);
1274    if (result.getResponses().hasMoreElements()) {
1275        Response response = (Response) result.getResponses().nextElement();
1276        // raise any necessary exceptions
1277
if (response instanceof MethodResponse) {
1278            int status = ((MethodResponse) response).getStatus();
1279            if (status != WebDAVStatus.SC_OK) {
1280                throw new WebDAVException(status, WebDAVStatus.getStatusMessage(status));
1281            }
1282        } else {
1283            PropertyValue propertyValue = (PropertyValue) ((PropertyResponse) response).getPropertiesByPropName().elements().nextElement();
1284            if ((propertyValue.status != WebDAVStatus.SC_OK) && (propertyValue.status != WebDAVStatus.SC_FAILED_DEPENDENCY)) {
1285                throw new WebDAVException(propertyValue.status, WebDAVStatus.getStatusMessage(propertyValue.status));
1286            }
1287        }
1288    }
1289}
1290/** A utility to resize a byte array and copy its current contents.
1291 * @param src the source array
1292 * @param new_size the new size to make the array
1293 * @param the newly sized array (may be smaller than src)
1294 */

1295private final static byte[] resizeArray(byte[] src, int new_size) {
1296    byte tmp[] = new byte[new_size];
1297    System.arraycopy(src, 0, tmp, 0, (src.length < new_size ? src.length : new_size));
1298    return tmp;
1299}
1300/** Set the contents of this resource. This may create a new resource on the server,
1301 * or update the contents of an existing resource. Sufficient authorization is required
1302 * and administered by the target web server. For text/* MIME types, the caller should
1303 * be sure to convert Strings to byte codes using an acceptable charset, and to set
1304 * that charset in the request context so the server knows how to decode the byte
1305 * stream.
1306 * <p><B>deprecated</B>: Use the setContents method that takes content type as a parameter.
1307 *
1308 * @param value the new contents for the resource
1309 * @exception com.ibm.webdav.WebDAVException
1310 */

1311public void setContents(byte[] value) throws WebDAVException {
1312    setContents( value, "text/plain" );
1313}
1314/** Set the contents of this resource. This may create a new resource on the server,
1315 * or update the contents of an existing resource. Sufficient authorization is required
1316 * and administered by the target web server. For text/* MIME types, the caller should
1317 * be sure to convert Strings to byte codes using an acceptable charset, and to set
1318 * that charset in the request context so the server knows how to decode the byte
1319 * stream.
1320 *
1321 * @param value the new contents for the resource
1322 * @param mimetype the mimetype of the new contents
1323 * @exception com.ibm.webdav.WebDAVException
1324 */

1325public void setContents(byte[] value, String JavaDoc mimetype) throws WebDAVException {
1326    context.getRequestContext().contentType(mimetype);
1327    OutputStream os = getContentsOutputStream();
1328    try {
1329        os.write(value, 0, value.length);
1330    } catch (WebDAVException exc) {
1331        throw exc;
1332    } catch (java.io.IOException JavaDoc exc) {
1333        throw new WebDAVException(WebDAVStatus.SC_INTERNAL_SERVER_ERROR, "IO Error");
1334    }
1335    closeContentsOutputStream();
1336}
1337/** Set properties of a resource.
1338 *
1339 * @param names an array of property names
1340 * @param values an array of property value
1341 * @return a MultiStatus indicating the result of the update
1342 * @exception com.ibm.webdav.WebDAVException
1343 */

1344public MultiStatus setProperties( PropertyName[] names, Element[] values) throws WebDAVException {
1345
1346        Document document = null;
1347
1348        try {
1349          document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
1350    } catch(Exception JavaDoc e) {
1351          throw new WebDAVException(WebDAVStatus.SC_PROCESSING,e.getMessage());
1352        }
1353        //document.setVersion(Resource.XMLVersion);
1354
//document.setEncoding(Resource.defaultXMLEncoding);
1355

1356    Element propertyUpdate = document.createElementNS("DAV:","D:propertyupdate");
1357
1358    propertyUpdate.setAttribute("xmlns:D", "DAV:");
1359    document.appendChild(propertyUpdate);
1360    Element set = document.createElementNS("DAV:","D:set");
1361
1362    propertyUpdate.appendChild(set);
1363    Element prop = document.createElementNS("DAV:","D:prop");
1364
1365    set.appendChild(prop);
1366    for (int i = 0; i < names.length; i++) {
1367        prop.appendChild((Element) values[i]);
1368    }
1369    return setProperties(document);
1370}
1371/** Edit the properties of a resource. The updates must refer to a Document containing a WebDAV
1372 * DAV:propertyupdates element as the document root.
1373 *
1374 * @param updates an XML Document containing DAV:propertyupdate elements
1375 * describing the edits to be made
1376 * @return a MultiStatus indicating the status of the updates
1377 * @exception com.ibm.webdav.WebDAVException
1378 */

1379public MultiStatus setProperties(Document updates) throws WebDAVException {
1380    return impl.setProperties(context, updates);
1381}
1382/** Set a property of a resource to a value.
1383 *
1384 * @param name the property name
1385 * @param value the property value
1386 * @exception com.ibm.webdav.WebDAVException
1387 */

1388public void setProperty( PropertyName name, Element value) throws WebDAVException {
1389    PropertyName[] names = new PropertyName[1];
1390    names[0] = name;
1391    Element[] values = new Element[1];
1392    values[0] = value;
1393    int responseCode = 0;
1394
1395    MultiStatus result = setProperties(names, values);
1396    setStatusCode(WebDAVStatus.SC_OK);
1397    if (result.getResponses().hasMoreElements()) {
1398        Response response = (Response) result.getResponses().nextElement();
1399        // raise any necessary exceptions
1400
if (response instanceof MethodResponse) {
1401            responseCode = ((MethodResponse) response).getStatus();
1402            if (responseCode != WebDAVStatus.SC_OK) {
1403                throw new WebDAVException(getStatusCode(), getStatusMessage());
1404            }
1405        } else {
1406            PropertyValue propertyValue = (PropertyValue) ((PropertyResponse) response).getPropertiesByPropName().elements().nextElement();
1407            responseCode = propertyValue.status;
1408            if ((responseCode != WebDAVStatus.SC_OK) && (responseCode != WebDAVStatus.SC_FAILED_DEPENDENCY)) {
1409                throw new WebDAVException(propertyValue.status, getStatusMessage());
1410            }
1411        }
1412    }
1413}
1414/** Set the request context for this resource. The context contains information
1415 * used by methods on a resource. This method is provided
1416 * for implementation reasons and would generally not be used by client
1417 * applications.
1418 *
1419 * @value the ResourceContext providing information that controls
1420 * method execution.
1421 * @exception com.ibm.webdav.WebDAVException
1422 */

1423public void setRequestContext(HTTPHeaders value) throws WebDAVException {
1424    context.setRequestContext(value);
1425}
1426/** Set the response context for this resource. The context contains information
1427 * returned from methods on a resource. This method is provided
1428 * for implementation reasons and would generally not be used by client
1429 * applications.
1430 *
1431 * @value the ResourceContext providing information resulting from
1432 * method execution.
1433 * @exception com.ibm.webdav.WebDAVException
1434 */

1435public void setResponseContext(HTTPHeaders value) throws WebDAVException {
1436    context.setResponseContext(value);
1437}
1438/** Set the status code corresponding to the last method execution.
1439 *
1440 * @value the status code as defined by HTTP/1.1 and the WebDAV extensions.
1441 * @exception com.ibm.webdav.WebDAVException
1442 */

1443public void setStatusCode(int value) throws WebDAVException {
1444    context.getStatusCode().setStatusCode(value);
1445}
1446/** Get a String representation of this resource.
1447 *
1448 * @return the URL of this Resource
1449 */

1450public String JavaDoc toString() {
1451    String JavaDoc value = null;
1452    try {
1453        value = getURL().toString();
1454    } catch (Exception JavaDoc exc) {
1455    }
1456    return value;
1457}
1458/** Unlock the lock identified by the lockToken on this resource. The request context
1459 * must contain the proper authorization.
1460 *
1461 * @param lockToken the lock token obtained from the ActiveLock of a previous <code>lock() </code>
1462 * or <code>getLocks()</code>.
1463 *
1464 * @return a MultiStatus containing any responses on resources that could not
1465 * be unlocked.
1466 * @exception com.ibm.webdav.WebDAVException
1467 */

1468public MultiStatus unlock(String JavaDoc lockToken) throws WebDAVException {
1469    return impl.unlock(context, lockToken);
1470}
1471/**
1472 * @param sContentType
1473 */

1474public void closeContentsOutputStream(String JavaDoc sContentType) throws WebDAVException {
1475    if(sContentType == null) {
1476        impl.closeContentsOutputStream(context);
1477    } else {
1478        impl.closeContentsOutputStream(context,sContentType);
1479    }
1480    
1481}
1482}
1483
Popular Tags