From a0788710c12d045ee68672efe8e2265118a66f70 Mon Sep 17 00:00:00 2001 From: pastith Date: Thu, 21 May 2009 13:26:58 +0000 Subject: [PATCH] Make sure that unfinished uploads do not result in unreferenced files in the file system. --- gss/src/gr/ebs/gss/server/ejb/ExternalAPIBean.java | 26 ++++++++++++-------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/gss/src/gr/ebs/gss/server/ejb/ExternalAPIBean.java b/gss/src/gr/ebs/gss/server/ejb/ExternalAPIBean.java index 66e2420..37b1f19 100644 --- a/gss/src/gr/ebs/gss/server/ejb/ExternalAPIBean.java +++ b/gss/src/gr/ebs/gss/server/ejb/ExternalAPIBean.java @@ -2295,7 +2295,7 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote { @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) - public File uploadFile(InputStream stream, Long userId) throws IOException, ObjectNotFoundException{ + public File uploadFile(InputStream stream, Long userId) throws IOException, ObjectNotFoundException { if (userId == null) throw new ObjectNotFoundException("No user specified"); User owner = dao.getEntityById(User.class, userId); @@ -2305,17 +2305,23 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote { if (logger.isDebugEnabled()) start = System.currentTimeMillis(); File result = new File(generateRepositoryFilePath()); - final FileOutputStream output = new FileOutputStream(result); - final byte[] buffer = new byte[UPLOAD_BUFFER_SIZE]; - int n = 0; - - while (-1 != (n = stream.read(buffer))) - output.write(buffer, 0, n); - output.close(); - stream.close(); + try { + final FileOutputStream output = new FileOutputStream(result); + final byte[] buffer = new byte[UPLOAD_BUFFER_SIZE]; + int n = 0; + + while (-1 != (n = stream.read(buffer))) + output.write(buffer, 0, n); + output.close(); + stream.close(); + } catch (IOException e) { + if (!result.delete()) + logger.warn("Could not delete " + result.getPath()); + throw e; + } if (logger.isDebugEnabled()) { end = System.currentTimeMillis(); - logger.debug("UPLOAD: "+(end-start)); + logger.debug("Time to upload: " + (end - start) + " (msec)"); } return result; } -- 1.7.10.4