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.module.files;
35
36 import info.magnolia.cms.util.ClasspathResourcesUtil;
37
38 import java.io.File;
39 import java.io.FileOutputStream;
40 import java.io.IOException;
41 import java.io.InputStream;
42 import java.io.OutputStream;
43
44 import org.apache.commons.io.IOUtils;
45
46
47
48
49
50 public class BasicFileExtractorOperation implements FileExtractorOperation {
51 protected final String resourcePath;
52 protected final String absoluteTargetPath;
53
54 BasicFileExtractorOperation(String resourcePath, String absoluteTargetPath) {
55 this.resourcePath = resourcePath;
56 this.absoluteTargetPath = absoluteTargetPath;
57 }
58
59 @Override
60 public void extract() throws IOException {
61 final InputStream resourceStream = checkInput();
62 final File checkedTargetFile = checkOutput();
63 if (checkedTargetFile != null) {
64 final OutputStream out = openOutput(checkedTargetFile);
65
66 copyAndClose(resourceStream, out);
67 }
68 }
69
70 protected InputStream checkInput() throws IOException {
71 final InputStream resourceStream = ClasspathResourcesUtil.getStream(resourcePath, false);
72 if (resourceStream == null) {
73 throw new IOException("Can't open " + resourcePath);
74 }
75 return resourceStream;
76 }
77
78
79
80
81
82 protected File checkOutput() throws IOException {
83 final File targetFile = new File(absoluteTargetPath);
84 final File parent = targetFile.getParentFile();
85 if (!parent.exists() && !parent.mkdirs()) {
86 throw new IOException("Can't create directories for " + targetFile.getAbsolutePath());
87 } else if (!parent.canWrite()) {
88 throw new IOException("Can't write to " + targetFile.getAbsolutePath());
89 }
90 return targetFile;
91 }
92
93 protected OutputStream openOutput(File targetFile) throws IOException {
94 return new FileOutputStream(targetFile);
95 }
96
97 protected void copyAndClose(InputStream in, OutputStream out) throws IOException {
98 try {
99 IOUtils.copy(in, out);
100 } finally {
101 IOUtils.closeQuietly(in);
102 IOUtils.closeQuietly(out);
103 }
104 }
105 }