WebDav Client in Java
The history of Java WebDav client is discussed well in this blog: http://pragmaticchris.blogspot.com/2007/11/java-webdav-clients.html. There is one update to it though: the JackRabbit project has a well-defined WebDav client (extending Commons HTTP Client) available.
To add JackRabbit WebDav client to your Maven project, use this:
<dependency>
<groupId>org.apache.jackrabbit</groupId>
<artifactId>jackrabbit-webdav</artifactId>
<version>1.6.0</version>
</dependency>
I will show one example of using the WebDav client which I had developed to upload content to an WebDav server:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
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.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.jackrabbit.webdav.client.methods.PutMethod;
...
// WebDAV URL:
final String baseUrl = ...;
// Source file to upload:
File f = ...;
try{
HttpClient client = new HttpClient();
Credentials creds = new UsernamePasswordCredentials("username", "password");
client.getState().setCredentials(AuthScope.ANY, creds);
PutMethod method = new PutMethod(baseUrl + "/" + f.getName());
RequestEntity requestEntity = new InputStreamRequestEntity(
new FileInputStream(f));
method.setRequestEntity(requestEntity);
client.executeMethod(method);
System.out.println(method.getStatusCode() + " " + method.getStatusText());
}
catch(HttpException ex){
// Handle Exception
}
catch(IOException ex){
// Handle Exception
}
Good example to upload a file. Could you please share an example to import a file also. I followed Jacakrabbit webdav wiki site and could able to get only the file list. How to get each file downloaded?
Dilip
12 Jun 09 at 9:00 am
I’ve created a new webdav client for Java that is quite a bit easier to use than jackrabbit. Basically, I’ve abstracted all the HttpClient stuff away and just expose a few easy to use methods for common use cases.
It is called sardine and lives up on google code:
http://code.google.com/p/sardine/
Jon Stevens
7 Jan 10 at 6:14 am
How to add progress bar to it for download. Can you put the entire buffer based approach using progress bar.
I used other way, but can’t prevent double calling of uploadFile method..
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLConnection;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.jackrabbit.webdav.client.methods.PutMethod;
import org.cord.client.shared.fileship.constants.FileshipConstants;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.widgets.Display;
public class FileUploadRequestEntity implements RequestEntity {
public String remotePath;
public String relativePath;
private File file = null;
PutMethod putMethod;
public FileUploadRequestEntity(String s_relativePath,String s_RemotePath, String localFileName){
super();
this.file = new File(localFileName);
this.relativePath =s_relativePath;
this.remotePath =s_RemotePath;
}
public String getContentType() {
String mimeType = URLConnection.guessContentTypeFromName(file.getName());
if (mimeType == null) {
mimeType = “application/octet-stream”;
}
return mimeType;
//return “text/plain; charset=UTF-8″;
}
/**
* writeRequest gets executed for every upload..
* means when the HTTP client executes put method, below method actually passes
* the data to server
*/
public void writeRequest( OutputStream out) throws IOException {
try {
uploadFile(out);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
void uploadFile( final OutputStream out) throws IOException, InvocationTargetException, InterruptedException {
final Display display = new Display();// this statement may throw error, since we do not know the activeshell and we need it below
ProgressMonitorDialog dialog = new ProgressMonitorDialog(display.getActiveShell());
final int fileSize = getFileSize();
final MD5 md5 = new MD5(); // for hash
dialog.run(true, true, new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor) {
monitor.beginTask(“Upload status …”, fileSize);// note very large size may return more length .. need to see that
InputStream fsInput;
try {
fsInput = new FileInputStream(file);
int data;
byte[] buffer = new byte[1024];
long kbTransfered = 0;// number of kb transferred in 1 go
while ((data = fsInput.read(buffer)) != -1) {
if(monitor.isCanceled()) {
monitor.done();
return;
}
++kbTransfered;
monitor.subTask(getStatusMessage(kbTransfered));
out.write(buffer, 0, data);
monitor.worked(1);
md5.update(buffer, data);
}
// adding hash value to uploaded file on jackrabbit server
fsInput.close();
out.flush(); /// very important
monitor.subTask(“File uploaded successfully. Generating Hash”);
WebDavEngine engine = WebDavEngine.getInstance();
String s_FileHash = md5.getHashString();
monitor.subTask(“File uploaded successfully. Now updating hash on server”);
//engine.addProperties(relativePath, FileshipConstants.FILE_HASH_Key, s_FileHash);
System.out.println(“File transferred successfully”);
} catch (Exception e) {
e.printStackTrace();
}finally{
monitor.done();
}
}
});
if (display!=null)display.dispose();
}
public long getContentLength() {
return file.length();
}
// Handy methods that have no relation(or not required) for the methods to be implemented while subclassing RequestEntity
/*************************
*/
int getFileSize() {
return (int) (file.length()/1024);// in KB
}
private void sleep(Integer waitTime) {
try {
Thread.sleep(waitTime);
} catch (Throwable t) {
System.out.println(“Wait time interrupted”);
}
}
String getStatusMessage(long kbTransfered){
long bytesTransfered = kbTransfered* 1024;
long totalBytes = getContentLength();
int percentUploaded = 0;
if(totalBytes>0){
percentUploaded = (int) (bytesTransfered * 100/ totalBytes);
}
return “Bytes uploaded: “+ bytesTransfered +” (” +percentUploaded + “%). Total Bytes : ” + totalBytes +
” Remaining: ” +(totalBytes – bytesTransfered) + ” Bytes” ;
}
@Override
public boolean isRepeatable() {
// TODO Auto-generated method stub
return true;
}
// add more …
/*************************
*/
}
Parvez Ahmad Hakim
Srinagar Kashmir India
Parvez Ahmad Hakim
16 Jun 10 at 9:06 pm
Hello, how can we create a filedownload with jackrabbit??
German
22 Jul 10 at 9:49 pm
Hi,
Using the above code I am able to upload Files to WEBDAV server.I need to upload the folders and files . How to upload folders and files under folders.Could you please help.
one more question how to download folders and files from WEBDAV server to local File system.
svr
30 Mar 12 at 12:53 pm