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