1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package org.nuiton.util;
24
25 import org.apache.commons.logging.Log;
26 import org.apache.commons.logging.LogFactory;
27
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.OutputStream;
31 import java.util.Map;
32 import java.util.zip.Deflater;
33 import java.util.zip.ZipEntry;
34 import java.util.zip.ZipOutputStream;
35
36
37 public class ZipStreamEncoder extends Thread {
38
39
40 private static final Log log = LogFactory.getLog(ZipStreamEncoder.class);
41
42
43 static final int BUFFER = 2048;
44
45
46 private Map<String, InputStream> files;
47
48
49 private ZipOutputStream zos;
50
51
52
53
54
55
56
57 public ZipStreamEncoder(Map<String, InputStream> files, OutputStream os) {
58 this.files = files;
59
60 zos = new ZipOutputStream(os);
61 zos.setMethod(ZipOutputStream.DEFLATED);
62 zos.setLevel(Deflater.BEST_COMPRESSION);
63 }
64
65
66
67
68 @Override
69 public void run() {
70 byte data[] = new byte[BUFFER];
71 try {
72 for (Map.Entry<String, InputStream> kv : files.entrySet()) {
73 ZipEntry entry = new ZipEntry(kv.getKey());
74 InputStream origin = kv.getValue();
75 zos.putNextEntry(entry);
76 int count;
77 while ((count = origin.read(data, 0, BUFFER)) != -1) {
78 zos.write(data, 0, count);
79 }
80 origin.close();
81 }
82
83 zos.close();
84 } catch (IOException e) {
85 for (Map.Entry<String, InputStream> kv : files.entrySet()) {
86 InputStream origin = kv.getValue();
87 try {
88 origin.close();
89 } catch (IOException ioe) {
90 log.error("Impossible to close " + kv.getKey());
91 }
92 }
93 log.error("Impossible to compress in stream");
94 throw new RuntimeException("Impossible to compress in stream");
95 }
96 }
97
98 }