]> git.argeo.org Git - gpl/argeo-slc.git/blob - runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/core/attachment/FileAttachmentsStorage.java
Attachments management
[gpl/argeo-slc.git] / runtime / org.argeo.slc.support.simple / src / main / java / org / argeo / slc / core / attachment / FileAttachmentsStorage.java
1 package org.argeo.slc.core.attachment;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.OutputStream;
9
10 import org.apache.commons.io.IOUtils;
11 import org.argeo.slc.SlcException;
12
13 public class FileAttachmentsStorage implements AttachmentsStorage {
14 private File attachmentsDirectory = new File(System
15 .getProperty("java.io.tmpdir")
16 + File.separator + "slcAttachments");
17
18 public void retrieveAttachment(Attachment attachment,
19 OutputStream outputStream) {
20 File file = getFile(attachment);
21 InputStream in = null;
22 try {
23 byte[] buffer = new byte[1024 * 1024];
24 in = new FileInputStream(file);
25 while (in.read(buffer) >= 0) {
26 outputStream.write(buffer);
27 }
28 } catch (IOException e) {
29 throw new SlcException("Cannot write attachment " + attachment
30 + " to " + file, e);
31 } finally {
32 IOUtils.closeQuietly(in);
33 }
34 }
35
36 public void storeAttachment(Attachment attachment, InputStream inputStream) {
37 File file = getFile(attachment);
38 FileOutputStream out = null;
39 try {
40 byte[] buffer = new byte[1024 * 1024];
41 out = new FileOutputStream(file);
42 int read = -1;
43 while ((read = inputStream.read(buffer)) >= 0) {
44 out.write(buffer, 0, read);
45 }
46 } catch (IOException e) {
47 throw new SlcException("Cannot write attachment " + attachment
48 + " to " + file, e);
49 } finally {
50 IOUtils.closeQuietly(out);
51 }
52
53 }
54
55 protected File getFile(Attachment attachment) {
56 if (!attachmentsDirectory.exists())
57 attachmentsDirectory.mkdirs();
58 File file = new File(attachmentsDirectory + File.separator
59 + attachment.getUuid());
60 return file;
61 }
62 }