*/
public static void uploadFile(File file, String server, SubMonitor monitor)
throws IOException {
try {
if (file == null || !file.exists()) {
throw new CausedIOException("Upload not possible",
new IllegalArgumentException(
"The file that should be uploaded was"
+ " either null or nonexistent"));
}
monitor.beginTask("Uploading file " + file.getName(), 100);
PostMethod post = new PostMethod(server);
// holds the status response after the method was executed
int status = 0;
post.getParams().setBooleanParameter(
HttpMethodParams.USE_EXPECT_CONTINUE, true);
/*
* retry the method 3 times, but not if the request was send
* successfully
*/
post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
monitor.worked(20);
if (monitor.isCanceled())
throw new CancellationException();
try {
// create a multipart request for the file
Part[] parts = { new FilePart(file.getName(), file) };
post.setRequestEntity(new MultipartRequestEntity(parts, post
.getParams()));
HttpClient client = new HttpClient();
/*
* connection has to be established within the timeout,
* otherwise a ConnectTimeoutException is thrown
*/
client.getHttpConnectionManager().getParams()
.setConnectionTimeout(TIMEOUT);
log.info("Trying to upload file " + file.getName() + " to "
+ server + " ...");
monitor.worked(20);
if (monitor.isCanceled())
throw new CancellationException();
// try to upload the file
status = client.executeMethod(post);
monitor.worked(50);
// examine status response
if (status == HttpStatus.SC_OK) {
log.info("Upload successfull for " + file.getName()
+ ".\nServer response: "
+ IOUtils.toString(post.getResponseBodyAsStream()));
return;
}
} catch (ConnectTimeoutException e) {
// couldn't connect within the timeout
throw new CausedIOException("Couldn't connect to host "
+ server, e);
} catch (Exception e) {
throw new CausedIOException(
"An internal error occurred while trying to upload file "
+ file.getName(), e);
} finally {
post.releaseConnection();
}
// upload failed
throw new CausedIOException("Upload failed", new RuntimeException(
"Server response: " + status + " "
+ HttpStatus.getStatusText(status)));
} finally {
monitor.done();
}