1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.ui.editor;
35
36 import info.magnolia.jcr.util.PropertyUtil;
37 import info.magnolia.objectfactory.Components;
38 import info.magnolia.ui.framework.util.TempFilesManager;
39
40 import java.io.File;
41 import java.io.FileInputStream;
42 import java.io.IOException;
43
44 import javax.jcr.Node;
45 import javax.jcr.Property;
46 import javax.jcr.RepositoryException;
47
48 import org.apache.commons.io.FileUtils;
49 import org.apache.commons.io.FilenameUtils;
50 import org.apache.jackrabbit.JcrConstants;
51 import org.apache.tika.Tika;
52
53
54
55
56 public interface JcrBinaryHelper {
57 Tika TIKA = new Tika();
58
59 default void createBinary(Node node, File file) throws RepositoryException, IOException {
60 node.setProperty(JcrConstants.JCR_MIMETYPE, TIKA.detect(file));
61 node.setProperty("fileName", Components.newInstance(TempFilesManager.class).toStandardFileName(file.getName()));
62 node.setProperty("size", FileUtils.sizeOf(file));
63 node.setProperty("extension", FilenameUtils.getExtension(file.getName()));
64 node.setProperty(JcrConstants.JCR_DATA, node.getSession().getValueFactory().createBinary(new FileInputStream(file)));
65 }
66
67 default File getBinary(Node node) throws RepositoryException, IOException {
68 if (!node.hasProperty(JcrConstants.JCR_DATA)) {
69 return null;
70 }
71
72 Property property = node.getProperty(JcrConstants.JCR_DATA);
73 String fileName = PropertyUtil.getString(node, "fileName", node.getName());
74 File tempFile = Components.newInstance(TempFilesManager.class).createTempFile(fileName);
75 FileUtils.copyInputStreamToFile(property.getBinary().getStream(), tempFile);
76 return tempFile;
77 }
78 }