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.cache.util;
35
36 import info.magnolia.cms.util.RequestHeaderUtil;
37 import info.magnolia.module.cache.CacheModule;
38 import info.magnolia.objectfactory.Components;
39
40 import java.io.ByteArrayInputStream;
41 import java.io.ByteArrayOutputStream;
42 import java.io.IOException;
43 import java.util.Arrays;
44 import java.util.List;
45 import java.util.zip.GZIPInputStream;
46 import java.util.zip.GZIPOutputStream;
47
48 import javax.servlet.http.HttpServletRequest;
49
50
51
52
53
54
55
56 public class GZipUtil {
57 private static final List GZIP_MIMETYPES = Arrays.asList(new String[]{
58 "application/x-compressed",
59 "application/x-gzip",
60 "application/gnutar",
61 "multipart/x-gzip"
62 });
63
64 private static final int FOUR_KB = 4196;
65 private static final int GZIP_MAGIC_NUMBER_BYTE_1 = 31;
66 private static final int GZIP_MAGIC_NUMBER_BYTE_2 = -117;
67
68 public static byte[] gzip(byte[] ungzipped) throws IOException {
69 if (isGZipped(ungzipped)) {
70 throw new IllegalStateException("The byte[] is already gzipped. It should not be gzipped again.");
71 }
72 final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
73 final GZIPOutputStream gzipOutputStream = new GZIPOutputStream(bytes);
74 gzipOutputStream.write(ungzipped);
75 gzipOutputStream.close();
76 return bytes.toByteArray();
77 }
78
79 public static byte[] ungzip(final byte[] gzipped) throws IOException {
80 final GZIPInputStream inputStream = new GZIPInputStream(new ByteArrayInputStream(gzipped));
81 final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(gzipped.length);
82 final byte[] buffer = new byte[FOUR_KB];
83 int bytesRead = 0;
84 while (bytesRead != -1) {
85 bytesRead = inputStream.read(buffer, 0, FOUR_KB);
86 if (bytesRead != -1) {
87 byteArrayOutputStream.write(buffer, 0, bytesRead);
88 }
89 }
90 byte[] ungzipped = byteArrayOutputStream.toByteArray();
91 inputStream.close();
92 byteArrayOutputStream.close();
93 return ungzipped;
94 }
95
96
97
98
99 public static boolean isGZipped(byte[] candidate) {
100 if (candidate == null || candidate.length < 2) {
101 return false;
102 } else {
103 return (candidate[0] == GZIP_MAGIC_NUMBER_BYTE_1 && candidate[1] == GZIP_MAGIC_NUMBER_BYTE_2);
104 }
105 }
106
107 public static boolean isGZipMimeType(String contentType) {
108 return GZIP_MIMETYPES.contains(contentType);
109 }
110
111
112
113
114 public static boolean isAcceptsGzip(HttpServletRequest request){
115 CacheModule module = Components.getComponent(CacheModule.class);
116 boolean compressionVote = module.getCompression().getVoters().vote(request)>0;
117 boolean requestAcceptsGzip = RequestHeaderUtil.acceptsGzipEncoding(request);
118 return requestAcceptsGzip && compressionVote;
119 }
120
121 }