KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openlaszlo > data > FileDataSource


1 /* *****************************************************************************
2  * FileDataSource.java
3 * ****************************************************************************/

4
5 /* J_LZ_COPYRIGHT_BEGIN *******************************************************
6 * Copyright 2001-2004 Laszlo Systems, Inc. All Rights Reserved. *
7 * Use is subject to license terms. *
8 * J_LZ_COPYRIGHT_END *********************************************************/

9
10 package org.openlaszlo.data;
11
12 import java.io.*;
13 import java.net.URL JavaDoc;
14 import java.net.MalformedURLException JavaDoc;
15 import javax.servlet.http.HttpServletRequest JavaDoc;
16 import javax.servlet.http.HttpServletResponse JavaDoc;
17 import org.apache.log4j.Logger;
18 import org.openlaszlo.utils.ChainedException;
19 import org.openlaszlo.utils.LZHttpUtils;
20 import org.openlaszlo.utils.FileUtils;
21 import org.openlaszlo.media.MimeType;
22
23 /**
24  * File Transport
25  */

26 public class FileDataSource extends DataSource
27 {
28     private static Logger mLogger = Logger.getLogger(FileDataSource.class);
29
30     /**
31      * @return name
32      */

33     public String JavaDoc name() {
34         return "file";
35     }
36
37     /**
38      * @return the data from this request
39      * @param app absolute pathnane to app file
40      * @param req request in progress
41      * @param lastModifiedTime this is the timestamp on the
42      * currently cached item; this time can be used as the datasource
43      * sees fit (or ignored) in constructing the results. If
44      * the value is -1, assume there is no currently cached item.
45      */

46     public Data getData(String JavaDoc app, HttpServletRequest JavaDoc req,
47                         HttpServletResponse JavaDoc res, long lastModifiedTime)
48         throws IOException, DataSourceException {
49         return getFileData(app, req, res, null, lastModifiedTime);
50     }
51
52     static public Data getFileData(String JavaDoc app, HttpServletRequest JavaDoc req,
53                                    HttpServletResponse JavaDoc res, String JavaDoc urlStr,
54                                    long lastModifiedTime)
55         throws IOException, DataSourceException {
56
57         if (urlStr == null) {
58             urlStr = DataSource.getURL(req);
59         }
60
61         URL JavaDoc url = new URL JavaDoc(urlStr);
62
63         String JavaDoc protocol = url.getProtocol();
64
65         if ( protocol == null || ! protocol.equals("file")){
66             mLogger.error( " bad protocol for " + url );
67             throw new DataSourceException("protocol " + protocol + "is not 'file:' ");
68         }
69
70         // We are not supporting 'file' type requests anymore.
71
if (true) {
72             throw new IOException("'file' data request type is not supported.");
73         }
74
75         String JavaDoc filename = url.getFile();
76         mLogger.debug("filename " + filename);
77
78         if ( filename == null || filename.equals("") ) {
79             throw new DataSourceException("empty filename");
80         }
81
82         // For relative urls, add app path before
83
if (filename.charAt(0) != '/') {
84             mLogger.debug("app " + app);
85             String JavaDoc appdir = app.substring(0,
86                             app.lastIndexOf(File.separatorChar) + 1);
87             mLogger.debug("appdir " + appdir);
88             filename = appdir + filename;
89             mLogger.debug("filename " + filename);
90         }
91
92         // Cope with Windows wackiness.
93
if (File.separatorChar == '\\') {
94             while (filename.startsWith("/")) {
95                 filename = filename.substring(1);
96             }
97             filename = filename.replace('/', '\\');
98         }
99
100         FileData data = new FileData(filename, lastModifiedTime);
101
102         // proxy date header
103
res.setDateHeader(LZHttpUtils.LAST_MODIFIED, data.lastModified());
104
105         return data;
106     }
107
108     /**
109      * A class for holding on to results of a File fetch.
110      *
111      * @author <a HREF="mailto:bloch@laszlosystems.com">Eric Bloch</a>
112      */

113
114     public static class FileData extends Data {
115
116         /** response code */
117         public FileInputStream str = null;
118
119         /** file */
120         public final File file;
121
122         /** lastModifiedTime from request (or -1)*/
123         public final long lastModifiedTime;
124
125         /**
126          * @param f file
127          */

128         public FileData(String JavaDoc filename, long lm) throws IOException {
129             mLogger.debug("filename " + filename);
130             File f = new File(filename);
131             if (f == null) {
132                 throw new IOException("can't construct file");
133             } else if (!f.exists()) {
134                 throw new IOException(filename + " doesn't exist.");
135             } else if (!f.canRead()) {
136                 throw new IOException("can't read " + filename);
137             }
138             lastModifiedTime = lm;
139             file = f;
140         }
141     
142         /**
143          * @return size of file
144          */

145         public long size() {
146             try {
147                 return FileUtils.fileSize(file);
148             } catch (Exception JavaDoc e) {
149                 throw new ChainedException(e);
150             }
151         }
152     
153         /**
154          * @return true if the data was "not modified"
155          * compared to the cached lastModified time.
156          */

157         public boolean notModified() {
158
159             long l = lastModified();
160             if (l == -1) {
161                 return false;
162             }
163
164             return (l <= lastModifiedTime);
165         }
166     
167         /**
168          * @return the lastModified time of the data
169          */

170         public long lastModified() {
171
172             long l = file.lastModified();
173             if (l == 0) {
174                 l = -1;
175             }
176             // Truncate to nearest second
177
l = ((l)/1000L) * 1000L;
178             mLogger.debug("lm is " + l);
179             return l;
180         }
181     
182         /**
183          * append response headers
184          */

185         public void appendResponseHeadersAsXML(StringBuffer JavaDoc xmlResponse) {
186             // TODO: [2003-04-17 bloch] should this be a string or a long?
187
xmlResponse.append("<header name=\"Last-Modified\" "
188                              + "value=\"" + lastModified() + "\" />");
189         }
190     
191         /**
192          * release any resources associated with this data
193          */

194         public synchronized void release() {
195             try {
196                 if (str != null) {
197                     str.close();
198                     str = null;
199                 }
200             } catch (Exception JavaDoc e) {
201                 mLogger.warn("ignoring exception while closing stream: ", e);
202             }
203         }
204
205         /**
206          * @return mime type
207          */

208         public String JavaDoc getMimeType() {
209             return MimeType.fromExtension(file.getPath());
210         }
211
212         /**
213          * @return input stream
214          */

215         public synchronized InputStream getInputStream() throws IOException {
216             if (str == null) {
217                 str = new FileInputStream(file);
218             }
219             return str;
220         }
221
222         /**
223          * @return string
224          */

225         public String JavaDoc getAsString() throws IOException {
226             return FileUtils.readFileString(file);
227         }
228     }
229 }
230
Popular Tags