]> git.argeo.org Git - gpl/argeo-slc.git/blob - runtime/org.argeo.slc.core/src/main/java/org/argeo/slc/core/attachment/FileAttachmentsStorage.java
Add security
[gpl/argeo-slc.git] / runtime / org.argeo.slc.core / 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 int read = -1;
40 while ((read = in.read(buffer)) >= 0) {
41 outputStream.write(buffer, 0, read);
42 }
43 } catch (IOException e) {
44 throw new SlcException("Cannot write attachment " + attachment
45 + " to " + file, e);
46 } finally {
47 IOUtils.closeQuietly(in);
48 }
49 }
50
51 public void storeAttachment(Attachment attachment, InputStream inputStream) {
52 File file = getFile(attachment);
53 FileOutputStream out = null;
54 try {
55 byte[] buffer = new byte[1024 * 1024];
56 out = new FileOutputStream(file);
57 int read = -1;
58 while ((read = inputStream.read(buffer)) >= 0) {
59 out.write(buffer, 0, read);
60 }
61 } catch (IOException e) {
62 throw new SlcException("Cannot write attachment " + attachment
63 + " to " + file, e);
64 } finally {
65 IOUtils.closeQuietly(out);
66 }
67
68 }
69
70 protected File getFile(Attachment attachment) {
71 if (!attachmentsDirectory.exists())
72 attachmentsDirectory.mkdirs();
73 File file = new File(attachmentsDirectory + File.separator
74 + attachment.getUuid());
75 return file;
76 }
77 }