Source code: com/obinary/cms/core/CacheHandler.java
1 /**
2 *
3 * Magnolia and its source-code is licensed under the LGPL.
4 * You may copy, adapt, and redistribute this file for commercial or non-commercial use.
5 * When copying, adapting, or redistributing this document in keeping with the guidelines above,
6 * you are required to provide proper attribution to obinary.
7 * If you reproduce or distribute the document without making any substantive modifications to its content,
8 * please use the following attribution line:
9 *
10 * Copyright 1993-2003 obinary Ltd. (http://www.obinary.com) All rights reserved.
11 *
12 * */
13
14
15
16
17
18
19 package com.obinary.cms.core;
20
21
22 import com.obinary.cms.beans.ServerInfo;
23 import com.obinary.cms.util.FileNameFilter;
24
25 import javax.servlet.http.HttpServletRequest;
26 import javax.servlet.http.HttpServletResponse;
27 import javax.servlet.ServletOutputStream;
28 import java.io.*;
29 import java.net.URLConnection;
30 import java.net.URL;
31 import java.util.Enumeration;
32 import java.util.zip.GZIPOutputStream;
33
34
35 /**
36 * User: sameercharles
37 * Date: Jul 14, 2003
38 * Time: 4:22:14 PM
39 * @author Sameer Charles
40 * @version 1.0
41 */
42
43
44 public class CacheHandler {
45
46 public static final String CACHE_DIRECTORY = PathUtil.getCacheDirectoryPath();
47
48
49
50
51
52 /**
53 *
54 * @param request
55 */
56 public static void cacheURI(HttpServletRequest request) throws IOException {
57 String URI = request.getRequestURI();
58 FileOutputStream out = null;
59 try {
60 if (!ServerInfo.isCacheable(URI))
61 return;
62 File file = getDestinationFile(URI);
63 if (file.exists())
64 return;
65 file.createNewFile();
66 out = new FileOutputStream(file);
67 streamURI(URI,out,request);
68 } catch (Exception e) {
69 e.printStackTrace();
70 } finally {
71 if (out != null)
72 out.close();
73 }
74 }
75
76
77
78 /**
79 * @param URI
80 * @param out
81 */
82 private static void streamURI(String URI, OutputStream out, HttpServletRequest request) throws IOException {
83 int indexOfSlash = request.getProtocol().indexOf("/");
84 InputStream in = null;
85 try {
86 URL url = new URL(request.getProtocol().substring(0,indexOfSlash)+"://"+request.getServerName()+":"+request.getServerPort()+URI);
87 URLConnection urlConnection = url.openConnection();
88 if (ServerInfo.isContextProtected())
89 urlConnection.setRequestProperty("Authorization",request.getHeader("Authorization"));
90 byte[] buffer = new byte[8192];
91 int read = 0;
92 in = urlConnection.getInputStream();
93 /* strip all white spaces */
94 int firstByte = stripWhiteSpaces(in);
95 out.write(firstByte);
96 while ((read = in.read(buffer)) > 0) {
97 out.write(buffer, 0, read);
98 }
99 in.close();
100 } catch (Exception e) {
101 e.printStackTrace();
102 } finally {
103 if (in != null)
104 in.close();
105 }
106 }
107
108
109 private static int stripWhiteSpaces(InputStream in) {
110 int read = 0;
111 try {
112 while ((read = in.read()) > -1) {
113 if ((read != 32) && (read != 10))
114 break;
115 }
116 } catch (IOException e) {e.printStackTrace();}
117 return read;
118 }
119
120
121
122 /**
123 * @param URI
124 */
125 private static File getDestinationFile(String URI) throws Exception {
126 String[] items = URI.split("/");
127 StringBuffer buffer = new StringBuffer();
128 int i = 0;
129 for (; i<(items.length-1); i++) {
130 if (items[i].equals(""))
131 continue;
132 buffer.append("/"+items[i]);
133 validatePath(CACHE_DIRECTORY+buffer.toString());
134 }
135 buffer.append("/"+items[i]);
136 return (new File(CACHE_DIRECTORY+buffer.toString()));
137 }
138
139
140
141 /**
142 * @param path to the directory
143 */
144 public static void validatePath(String path) {
145 File file = new File(path);
146 if (!file.isDirectory()) {
147 if (!file.mkdir())
148 System.out.println("Can not create directory : "+path);
149 }
150 }
151
152
153
154 /**
155 * @param request
156 * @param response
157 * @throws IOException
158 */
159 public static boolean streamFromCache(HttpServletRequest request,HttpServletResponse response) throws IOException {
160 /* make sure not to stream anything from cache if its a POST request or has ? in URL */
161 if (request.getMethod().toLowerCase().equals("post"))
162 return false;
163 Enumeration paramList = request.getParameterNames();
164 if (paramList.hasMoreElements())
165 return false;
166 FileInputStream fin = null;
167 try {
168 File file = new File(CACHE_DIRECTORY+request.getRequestURI());
169 if (!file.exists())
170 return false;
171 if (file.length() < 4)
172 return false;
173 fin = new FileInputStream(file);
174 byte[] buffer = new byte[8192];
175 int read = 0;
176 response.setContentType(""); // hack
177 ServletOutputStream out = response.getOutputStream();
178 while ((read = fin.read(buffer)) > 0) {
179 out.write(buffer, 0, read);
180 }
181 } catch (Exception e) {
182 } finally {
183 if (fin != null)
184 fin.close();
185 }
186 return true;
187 }
188
189
190
191 /**
192 * @param URI
193 */
194 public static void flushResource(String URI) {
195 File file = new File(URI);
196 try {
197 if (file.isDirectory()) {
198 File[] children = file.listFiles();
199 for (int i=0; i<children.length; i++) {
200 if (children[i].isDirectory())
201 flushResource(children[i].getPath());
202 else
203 children[i].delete();
204 }
205 } else {
206 file.delete();
207 }
208 } catch (Exception e) {
209 e.printStackTrace();
210 }
211 }
212
213
214
215 /**
216 * @param path
217 */
218 public static void flushCache(String path) {
219 path = CACHE_DIRECTORY+path;
220 /* first flush the directory together with all sub resources */
221 CacheHandler.flushResource(path);
222 /* flush all pages which end with path.(*) on the same level */
223 File file = new File(path);
224 File parent = file.getParentFile();
225 if (parent != null) {
226 FileNameFilter filenameFilter = new FileNameFilter();
227 filenameFilter.setSearchString(file.getName());
228 File[] files = parent.listFiles(filenameFilter);
229 for (int i=0; i<files.length; i++)
230 files[i].delete();
231 }
232 }
233
234
235
236 /**
237 * <p>flushes entire cache</p>
238 */
239 public static void flushCache() {
240 CacheHandler.flushResource(CACHE_DIRECTORY);
241 /* this will create cache start directory again */
242 CacheHandler.validatePath(CACHE_DIRECTORY);
243 }
244
245
246
247
248
249
250 }