KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mortbay > util > FileResource


1 // ========================================================================
2
// $Id: FileResource.java,v 1.31 2006/01/04 13:55:31 gregwilkins Exp $
3
// Copyright 1996-2004 Mort Bay Consulting Pty. Ltd.
4
// ------------------------------------------------------------------------
5
// Licensed under the Apache License, Version 2.0 (the "License");
6
// you may not use this file except in compliance with the License.
7
// You may obtain a copy of the License at
8
// http://www.apache.org/licenses/LICENSE-2.0
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
// ========================================================================
15
package org.mortbay.util;
16
17 import java.io.File JavaDoc;
18 import java.io.FileInputStream JavaDoc;
19 import java.io.FileOutputStream JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.io.InputStream JavaDoc;
22 import java.io.OutputStream JavaDoc;
23 import java.net.MalformedURLException JavaDoc;
24 import java.net.URI JavaDoc;
25 import java.net.URISyntaxException JavaDoc;
26 import java.net.URL JavaDoc;
27 import java.net.URLConnection JavaDoc;
28 import java.security.Permission JavaDoc;
29
30 import org.apache.commons.logging.Log;
31 import org.mortbay.log.LogFactory;
32
33
34 /* ------------------------------------------------------------ */
35 /** File Resource.
36  *
37  * Handle resources of implied or explicit file type.
38  * This class can check for aliasing in the filesystem (eg case
39  * insensitivity). By default this is turned on if the platform does
40  * not have the "/" path separator, or it can be controlled with the
41  * "org.mortbay.util.FileResource.checkAliases" system parameter.
42  *
43  * If alias checking is turned on, then aliased resources are
44  * treated as if they do not exist, nor can they be created.
45  *
46  * @version $Revision: 1.31 $
47  * @author Greg Wilkins (gregw)
48  */

49 public class FileResource extends URLResource
50 {
51     private static Log log = LogFactory.getLog(Credential.class);
52     private static boolean __checkAliases;
53     static
54     {
55         __checkAliases=
56             "true".equalsIgnoreCase
57             (System.getProperty("org.mortbay.util.FileResource.checkAliases","true"));
58  
59        if (__checkAliases)
60             log.info("Checking Resource aliases");
61     }
62     
63     /* ------------------------------------------------------------ */
64     private File JavaDoc _file;
65     private transient URL JavaDoc _alias=null;
66     private transient boolean _aliasChecked=false;
67
68     /* ------------------------------------------------------------------------------- */
69     /** setCheckAliases.
70      * @param checkAliases True of resource aliases are to be checked for (eg case insensitivity or 8.3 short names) and treated as not found.
71      */

72     public static void setCheckAliases(boolean checkAliases)
73     {
74         __checkAliases=checkAliases;
75     }
76
77     /* ------------------------------------------------------------------------------- */
78     /** getCheckAliases.
79      * @return True of resource aliases are to be checked for (eg case insensitivity or 8.3 short names) and treated as not found.
80      */

81     public static boolean getCheckAliases()
82     {
83         return __checkAliases;
84     }
85     
86     /* -------------------------------------------------------- */
87     FileResource(URL JavaDoc url)
88         throws IOException JavaDoc, URISyntaxException JavaDoc
89     {
90         super(url,null);
91
92         try
93         {
94             // Try standard API to convert URL to file.
95
_file =new File JavaDoc(new URI(url.toString()));
96         }
97         catch (Exception JavaDoc e)
98         {
99             LogSupport.ignore(log,e);
100             try
101             {
102                 // Assume that File.toURL produced unencoded chars. So try
103
// encoding them.
104
String JavaDoc urls=
105                     "file:"+org.mortbay.util.URI.encodePath(url.toString().substring(5));
106                 _file =new File JavaDoc(new URI(urls));
107             }
108             catch (Exception JavaDoc e2)
109             {
110                 LogSupport.ignore(log,e2);
111
112                 // Still can't get the file. Doh! try good old hack!
113
checkConnection();
114                 Permission JavaDoc perm = _connection.getPermission();
115                 _file = new File JavaDoc(perm==null?url.getFile():perm.getName());
116             }
117         }
118         
119         if (_file.isDirectory() && !_urlString.endsWith("/"))
120             _urlString=_urlString+"/";
121     }
122     
123     /* -------------------------------------------------------- */
124     FileResource(URL JavaDoc url, URLConnection JavaDoc connection, File JavaDoc file)
125     {
126         super(url,connection);
127         _file=file;
128         if (_file.isDirectory() && !_urlString.endsWith("/"))
129             _urlString=_urlString+"/";
130     }
131     
132     /* -------------------------------------------------------- */
133     public Resource addPath(String JavaDoc path)
134         throws IOException JavaDoc,MalformedURLException JavaDoc
135     {
136         FileResource r=null;
137
138         if (!isDirectory())
139         {
140             r=(FileResource)super.addPath(path);
141         }
142         else
143         {
144             path = org.mortbay.util.URI.canonicalPath(path);
145             
146             // treat all paths being added as relative
147
String JavaDoc rel=path;
148             if (path.startsWith("/"))
149                 rel = path.substring(1);
150             
151             File JavaDoc newFile = new File JavaDoc(_file,rel.replace('/', File.separatorChar));
152             r=new FileResource(newFile.toURI().toURL(),null,newFile);
153         }
154         
155         String JavaDoc encoded=org.mortbay.util.URI.encodePath(path);
156         int expected=r._urlString.length()-encoded.length();
157         int index = r._urlString.lastIndexOf(encoded, expected);
158         
159         if (expected!=index && ((expected-1)!=index || path.endsWith("/") || !r.isDirectory()))
160         {
161             r._alias=r._url;
162             r._aliasChecked=true;
163         }
164         return r;
165     }
166    
167     
168     /* ------------------------------------------------------------ */
169     public URL JavaDoc getAlias()
170     {
171         if (__checkAliases && !_aliasChecked)
172         {
173             try
174             {
175                 String JavaDoc abs=_file.getAbsolutePath();
176                 String JavaDoc can=_file.getCanonicalPath();
177                 
178                 if (abs.length()!=can.length() || !abs.equals(can))
179                     _alias=new File JavaDoc(can).toURI().toURL();
180                 
181                 _aliasChecked=true;
182                 
183                 if (_alias!=null && log.isDebugEnabled())
184                 {
185                     log.debug("ALIAS abs="+abs);
186                     log.debug("ALIAS can="+can);
187                 }
188             }
189             catch(Exception JavaDoc e)
190             {
191                 log.warn(LogSupport.EXCEPTION,e);
192                 return getURL();
193             }
194         }
195         return _alias;
196     }
197     
198     /* -------------------------------------------------------- */
199     /**
200      * Returns true if the resource exists.
201      */

202     public boolean exists()
203     {
204         return _file.exists();
205     }
206         
207     /* -------------------------------------------------------- */
208     /**
209      * Returns the last modified time
210      */

211     public long lastModified()
212     {
213         return _file.lastModified();
214     }
215
216     /* -------------------------------------------------------- */
217     /**
218      * Returns true if the respresenetd resource is a container/directory.
219      */

220     public boolean isDirectory()
221     {
222         return _file.isDirectory();
223     }
224
225     /* --------------------------------------------------------- */
226     /**
227      * Return the length of the resource
228      */

229     public long length()
230     {
231         return _file.length();
232     }
233         
234
235     /* --------------------------------------------------------- */
236     /**
237      * Returns the name of the resource
238      */

239     public String JavaDoc getName()
240     {
241         return _file.getAbsolutePath();
242     }
243         
244     /* ------------------------------------------------------------ */
245     /**
246      * Returns an File representing the given resource or NULL if this
247      * is not possible.
248      */

249     public File JavaDoc getFile()
250     {
251         return _file;
252     }
253         
254     /* --------------------------------------------------------- */
255     /**
256      * Returns an input stream to the resource
257      */

258     public InputStream JavaDoc getInputStream() throws IOException JavaDoc
259     {
260         return new FileInputStream JavaDoc(_file);
261     }
262         
263     /* --------------------------------------------------------- */
264     /**
265      * Returns an output stream to the resource
266      */

267     public OutputStream JavaDoc getOutputStream()
268         throws java.io.IOException JavaDoc, SecurityException JavaDoc
269     {
270         return new FileOutputStream JavaDoc(_file);
271     }
272         
273     /* --------------------------------------------------------- */
274     /**
275      * Deletes the given resource
276      */

277     public boolean delete()
278         throws SecurityException JavaDoc
279     {
280         return _file.delete();
281     }
282
283     /* --------------------------------------------------------- */
284     /**
285      * Rename the given resource
286      */

287     public boolean renameTo( Resource dest)
288         throws SecurityException JavaDoc
289     {
290         if( dest instanceof FileResource)
291             return _file.renameTo( ((FileResource)dest)._file);
292         else
293             return false;
294     }
295
296     /* --------------------------------------------------------- */
297     /**
298      * Returns a list of resources contained in the given resource
299      */

300     public String JavaDoc[] list()
301     {
302         String JavaDoc[] list =_file.list();
303         if (list==null)
304             return null;
305         for (int i=list.length;i-->0;)
306         {
307             if (new File JavaDoc(_file,list[i]).isDirectory() &&
308                 !list[i].endsWith("/"))
309                 list[i]+="/";
310         }
311         return list;
312     }
313          
314     /* ------------------------------------------------------------ */
315     /** Encode according to this resource type.
316      * File URIs are encoded.
317      * @param uri URI to encode.
318      * @return The uri unchanged.
319      */

320     public String JavaDoc encode(String JavaDoc uri)
321     {
322         return uri;
323     }
324     
325     /* ------------------------------------------------------------ */
326     /**
327      * @param o
328      * @return
329      */

330     public boolean equals( Object JavaDoc o)
331     {
332         if (this == o)
333             return true;
334
335         if (null == o || ! (o instanceof FileResource))
336             return false;
337
338         FileResource f=(FileResource)o;
339         return f._file == _file || (null != _file && _file.equals(f._file));
340     }
341
342     /* ------------------------------------------------------------ */
343     /**
344      * @return the hashcode.
345      */

346     public int hashCode()
347     {
348        return null == _file ? super.hashCode() : _file.hashCode();
349     }
350 }
351
Popular Tags