]> 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
45bf35fb5e9d14514a571a3a645bdeb9bc3198f0
[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;
15
16 public FileAttachmentsStorage() {
17 String osgiInstanceArea = System.getProperty("osgi.instance.area");
18 if (osgiInstanceArea != null) {
19 if (osgiInstanceArea.startsWith("file:"))
20 osgiInstanceArea = osgiInstanceArea.substring("file:".length());
21 attachmentsDirectory = new File(osgiInstanceArea + File.separator
22 + "slcAttachments");
23 }
24
25 if (attachmentsDirectory == null) {
26 String tempDir = System.getProperty("java.io.tmpdir");
27 attachmentsDirectory = new File(tempDir + File.separator
28 + "slcAttachments");
29 }
30 }
31
32 public void retrieveAttachment(Attachment attachment,
33 OutputStream outputStream) {
34 File file = getFile(attachment);
35 InputStream in = null;
36 try {
37 byte[] buffer = new byte[1024 * 1024];
38 in = new FileInputStream(file);
39 while (in.read(buffer) >= 0) {
40 outputStream.write(buffer);
41 }
42 } catch (IOException e) {
43 throw new SlcException("Cannot write attachment " + attachment
44 + " to " + file, e);
45 } finally {
46 IOUtils.closeQuietly(in);
47 }
48 }
49
50 public void storeAttachment(Attachment attachment, InputStream inputStream) {
51 File file = getFile(attachment);
52 FileOutputStream out = null;
53 try {
54 byte[] buffer = new byte[1024 * 1024];
55 out = new FileOutputStream(file);
56 int read = -1;
57 while ((read = inputStream.read(buffer)) >= 0) {
58 out.write(buffer, 0, read);
59 }
60 } catch (IOException e) {
61 throw new SlcException("Cannot write attachment " + attachment
62 + " to " + file, e);
63 } finally {
64 IOUtils.closeQuietly(out);
65 }
66
67 }
68
69 protected File getFile(Attachment attachment) {
70 if (!attachmentsDirectory.exists())
71 attachmentsDirectory.mkdirs();
72 File file = new File(attachmentsDirectory + File.separator
73 + attachment.getUuid());
74 return file;
75 }
76 }