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.filter;
35
36 import java.io.File;
37 import java.io.FileInputStream;
38 import java.io.IOException;
39
40 import javax.servlet.FilterChain;
41 import javax.servlet.ServletException;
42 import javax.servlet.http.HttpServletRequest;
43 import javax.servlet.http.HttpServletResponse;
44
45 import org.apache.commons.collections.MultiMap;
46 import org.apache.commons.io.FileUtils;
47 import org.apache.commons.io.IOUtils;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51
52
53
54
55
56
57
58 public class DelegatingBlobCachedEntry extends ContentCachedEntry {
59
60 private static Logger log = LoggerFactory.getLogger(DelegatingBlobCachedEntry.class);
61
62
63 private static final String CONTENT_FILE_ATTIBUTE = DelegatingBlobCachedEntry.class.getName() + ".contentFile";
64
65 private long contentLength;
66
67 public DelegatingBlobCachedEntry(long contentLength, String contentType, String characterEncoding, int statusCode, MultiMap headers, long modificationDate, String originalUrl) throws IOException {
68 super(contentType, characterEncoding, statusCode, headers, modificationDate, originalUrl);
69 this.contentLength = contentLength;
70 }
71
72 @Override
73 protected boolean canServeGzipContent() {
74 return false;
75 }
76
77 public void replay(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
78 File contentFile = getContentFileBoundToTheRequest(request);
79 if(contentFile != null){
80 super.replay(request, response, chain);
81 }
82 else{
83 chain.doFilter(request, response);
84 }
85 }
86
87 @Override
88 protected void writeContent(HttpServletRequest request, HttpServletResponse response, FilterChain chain, boolean acceptsGzipEncoding) throws IOException, ServletException {
89 response.setContentLength((int) contentLength);
90 File contentFile = getContentFileBoundToTheRequest(request);
91 if(contentFile != null){
92 FileInputStream contentStream = FileUtils.openInputStream(contentFile);
93 IOUtils.copy(contentStream,response.getOutputStream());
94 IOUtils.closeQuietly(contentStream);
95 if(!contentFile.delete()){
96 log.error("Can't delete file: " + contentFile);
97 }
98 }
99 else{
100
101 throw new IllegalStateException("No content file attached to the request!");
102 }
103 }
104
105 private File getContentFileBoundToTheRequest(HttpServletRequest request) {
106 return (File) request.getAttribute(CONTENT_FILE_ATTIBUTE);
107 }
108
109 public void bindContentFileToCurrentRequest(HttpServletRequest request, File contentFile){
110 request.setAttribute(DelegatingBlobCachedEntry.CONTENT_FILE_ATTIBUTE, contentFile);
111 }
112
113 }