1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.exoplatform.wcm.ext.component.activity;
18
19 import java.io.File;
20 import java.io.FileInputStream;
21 import java.io.IOException;
22 import java.io.InputStream;
23
24 import javax.jcr.Node;
25
26 import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
27 import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
28 import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream.UnicodeExtraFieldPolicy;
29 import org.apache.pdfbox.io.IOUtils;
30
31 import org.exoplatform.download.DownloadResource;
32 import org.exoplatform.services.log.ExoLogger;
33 import org.exoplatform.services.log.Log;
34 import org.exoplatform.services.wcm.core.NodeLocation;
35 import org.exoplatform.services.wcm.core.NodetypeConstant;
36
37
38
39
40
41
42
43 public class ActivityFilesDownloadResource extends DownloadResource {
44 private static final Log LOG = ExoLogger.getLogger(ActivityFilesDownloadResource.class);
45
46 private NodeLocation[] nodeLocations;
47
48 public ActivityFilesDownloadResource(NodeLocation[] nodelocations) {
49 super("application/zip");
50 this.nodeLocations = nodelocations;
51 }
52
53 @Override
54 public InputStream getInputStream() throws IOException {
55 if (nodeLocations == null || nodeLocations.length == 0) {
56 return null;
57 }
58
59 File zipFile = File.createTempFile("activity_files", ".zip");
60 ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(zipFile);
61 try {
62 zipOutputStream.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
63 zipOutputStream.setEncoding("UTF-8");
64 for (NodeLocation nodeLocation : nodeLocations) {
65 Node node = NodeLocation.getNodeByLocation(nodeLocation);
66 if (node.isNodeType(NodetypeConstant.NT_FILE) && node.hasNode(NodetypeConstant.JCR_CONTENT)) {
67 Node contentNode = node.getNode(NodetypeConstant.JCR_CONTENT);
68 if (contentNode.hasProperty(NodetypeConstant.JCR_DATA)) {
69 String fileName = node.hasProperty(NodetypeConstant.EXO_NAME) ? node.getProperty(NodetypeConstant.EXO_NAME).getString() : node.getName();
70 ZipArchiveEntry entry = new ZipArchiveEntry(fileName);
71 zipOutputStream.putArchiveEntry(entry);
72 InputStream inputStream = null;
73 try {
74 inputStream = contentNode.getProperty(NodetypeConstant.JCR_DATA).getStream();
75 IOUtils.copy(inputStream, zipOutputStream);
76 } finally {
77 if (inputStream != null) {
78 inputStream.close();
79 }
80 }
81 zipOutputStream.closeArchiveEntry();
82 }
83 }
84 }
85 } catch (Exception exp) {
86 IOUtils.closeQuietly(zipOutputStream);
87 zipFile.delete();
88 LOG.error("An error occurred when generating the ZIP file", exp);
89 throw new RuntimeException("An error occurred when generating the ZIP file", exp);
90 } finally {
91 IOUtils.closeQuietly(zipOutputStream);
92 }
93 return new FileInputStream(zipFile);
94 }
95
96 }