11.18. Modifying a WebDAV Resource

Problem

You need to modify a WebDAV resource.

Solution

Use the putMethod( ) on WebdavResource, and be sure to lock and unlock the resource before and after modification. The following example demonstrates the use of lockMethod( ) , putMethod( ), and unlockMethod( ) to modify a resource:

               import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.webdav.lib.WebdavResource;

String url = "http://www.discursive.com/jccook/dav/test.html";
Credentials credentials =
    new UsernamePasswordCredentials("davuser", "davpass");

// List resources in top directory
WebdavResource resource = new WebdavResource(url, credentials);

// Lock the Resource for 100 seconds
boolean locked = resource.lockMethod( "tobrien", 100 );

if( locked ) {
    try {
        // Read content as a String
        String resourceData = resource.getMethodDataAsString( );
        
        // Modify a resource
        System.out.println( "*** Modifying Resource");
        resourceData = resourceData.replaceAll( "test", "modified test" );
        resource.putMethod( resourceData );
    } finally {
        // Unlock the resource
        resource.unlockMethod( );
    }
}
        
// Close the resource    
resource.close( );

Discussion

lockMethod( ) accepts an owner and a timeout; the owner is the owner of the lock, and the timeout is the timeout of the lock in number of seconds. When locking a resource, the lockMethod( ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.