KickJava   Java API By Example, From Geeks To Geeks.

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


1 // ========================================================================
2
// $Id: Resource.java,v 1.31 2005/10/21 11:36:56 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.IOException JavaDoc;
19 import java.io.InputStream JavaDoc;
20 import java.io.OutputStream JavaDoc;
21 import java.io.Serializable JavaDoc;
22 import java.net.MalformedURLException JavaDoc;
23 import java.net.URL JavaDoc;
24 import java.net.URLConnection JavaDoc;
25 import java.text.DateFormat JavaDoc;
26 import java.util.Arrays JavaDoc;
27 import java.util.Date JavaDoc;
28
29 import org.apache.commons.logging.Log;
30 import org.mortbay.log.LogFactory;
31
32
33 /* ------------------------------------------------------------ */
34 /** Abstract resource class.
35  *
36  * @version $Id: Resource.java,v 1.31 2005/10/21 11:36:56 gregwilkins Exp $
37  * @author Nuno Preguiça
38  * @author Greg Wilkins (gregw)
39  */

40 public abstract class Resource implements Serializable JavaDoc
41 {
42     private static Log log = LogFactory.getLog(Resource.class);
43
44     Object JavaDoc _associate;
45     
46     /* ------------------------------------------------------------ */
47     /** Construct a resource from a url.
48      * @param url A URL.
49      * @return A Resource object.
50      */

51     public static Resource newResource(URL JavaDoc url)
52         throws IOException JavaDoc
53     {
54         if (url==null)
55             return null;
56
57         String JavaDoc urls=url.toExternalForm();
58         if( urls.startsWith( "file:"))
59         {
60             try
61             {
62                 FileResource fileResource= new FileResource(url);
63                 return fileResource;
64             }
65             catch(Exception JavaDoc e)
66             {
67                 log.debug(LogSupport.EXCEPTION,e);
68                 return new BadResource(url,e.toString());
69             }
70         }
71         else if( urls.startsWith( "jar:file:"))
72         {
73             return new JarFileResource(url);
74         }
75         else if( urls.startsWith( "jar:"))
76         {
77             return new JarResource(url);
78         }
79
80         return new URLResource(url,null);
81     }
82
83     /* ------------------------------------------------------------ */
84     /** Construct a resource from a string.
85      * @param resource A URL or filename.
86      * @return A Resource object.
87      */

88     public static Resource newResource(String JavaDoc resource)
89         throws MalformedURLException JavaDoc, IOException JavaDoc
90     {
91         URL JavaDoc url=null;
92         try
93         {
94             // Try to format as a URL?
95
url = new URL JavaDoc(resource);
96         }
97         catch(MalformedURLException JavaDoc e)
98         {
99             if(!resource.startsWith("ftp:") &&
100                !resource.startsWith("file:") &&
101                !resource.startsWith("jar:"))
102             {
103                 try
104                 {
105                     // It's a file.
106
if (resource.startsWith("./"))
107                         resource=resource.substring(2);
108                     
109                     File JavaDoc file=new File JavaDoc(resource).getCanonicalFile();
110                     url=file.toURI().toURL();
111                     
112                     URLConnection JavaDoc connection=url.openConnection();
113                     FileResource fileResource= new FileResource(url,connection,file);
114                     return fileResource;
115                 }
116                 catch(Exception JavaDoc e2)
117                 {
118                     log.debug(LogSupport.EXCEPTION,e2);
119                     throw e;
120                 }
121             }
122             else
123             {
124                 log.warn("Bad Resource: "+resource);
125                 throw e;
126             }
127         }
128
129         String JavaDoc nurl=url.toString();
130         if (nurl.length()>0 &&
131             nurl.charAt(nurl.length()-1)!=
132             resource.charAt(resource.length()-1))
133         {
134             if ((nurl.charAt(nurl.length()-1)!='/' ||
135                  nurl.charAt(nurl.length()-2)!=resource.charAt(resource.length()-1))
136                 &&
137                 (resource.charAt(resource.length()-1)!='/' ||
138                  resource.charAt(resource.length()-2)!=nurl.charAt(nurl.length()-1)
139                  ))
140             {
141                 return new BadResource(url,"Trailing special characters stripped by URL in "+resource);
142             }
143         }
144         return newResource(url);
145     }
146
147     /* ------------------------------------------------------------ */
148     /** Construct a system resource from a string.
149      * The resource is tried as classloader resource before being
150      * treated as a normal resource.
151      */

152     public static Resource newSystemResource(String JavaDoc resource)
153         throws IOException JavaDoc
154     {
155         URL JavaDoc url=null;
156         // Try to format as a URL?
157
ClassLoader JavaDoc
158             loader=Thread.currentThread().getContextClassLoader();
159         if (loader!=null)
160         {
161             url=loader.getResource(resource);
162             if (url==null && resource.startsWith("/"))
163                 url=loader.getResource(resource.substring(1));
164         }
165         if (url==null)
166         {
167             loader=Resource.class.getClassLoader();
168             if (loader!=null)
169             {
170                 url=loader.getResource(resource);
171                 if (url==null && resource.startsWith("/"))
172                     url=loader.getResource(resource.substring(1));
173             }
174         }
175         
176         if (url==null)
177         {
178             url=ClassLoader.getSystemResource(resource);
179             if (url==null && resource.startsWith("/"))
180                 url=loader.getResource(resource.substring(1));
181         }
182         
183         if (url==null)
184             return null;
185         
186         return newResource(url);
187     }
188
189     /* ------------------------------------------------------------ */
190     protected void finalize()
191     {
192         release();
193     }
194
195     /* ------------------------------------------------------------ */
196     /** Release any resources held by the resource.
197      */

198     public abstract void release();
199     
200
201     /* ------------------------------------------------------------ */
202     /**
203      * Returns true if the respresened resource exists.
204      */

205     public abstract boolean exists();
206     
207
208     /* ------------------------------------------------------------ */
209     /**
210      * Returns true if the respresenetd resource is a container/directory.
211      * If the resource is not a file, resources ending with "/" are
212      * considered directories.
213      */

214     public abstract boolean isDirectory();
215
216     /* ------------------------------------------------------------ */
217     /**
218      * Returns the last modified time
219      */

220     public abstract long lastModified();
221
222
223     /* ------------------------------------------------------------ */
224     /**
225      * Return the length of the resource
226      */

227     public abstract long length();
228     
229
230     /* ------------------------------------------------------------ */
231     /**
232      * Returns an URL representing the given resource
233      */

234     public abstract URL JavaDoc getURL();
235     
236
237     /* ------------------------------------------------------------ */
238     /**
239      * Returns an File representing the given resource or NULL if this
240      * is not possible.
241      */

242     public abstract File JavaDoc getFile()
243         throws IOException JavaDoc;
244     
245
246     /* ------------------------------------------------------------ */
247     /**
248      * Returns the name of the resource
249      */

250     public abstract String JavaDoc getName();
251     
252
253     /* ------------------------------------------------------------ */
254     /**
255      * Returns an input stream to the resource
256      */

257     public abstract InputStream JavaDoc getInputStream()
258         throws java.io.IOException JavaDoc;
259
260     /* ------------------------------------------------------------ */
261     /**
262      * Returns an output stream to the resource
263      */

264     public abstract OutputStream JavaDoc getOutputStream()
265         throws java.io.IOException JavaDoc, SecurityException JavaDoc;
266     
267     /* ------------------------------------------------------------ */
268     /**
269      * Deletes the given resource
270      */

271     public abstract boolean delete()
272         throws SecurityException JavaDoc;
273     
274     /* ------------------------------------------------------------ */
275     /**
276      * Rename the given resource
277      */

278     public abstract boolean renameTo( Resource dest)
279         throws SecurityException JavaDoc;
280     
281     /* ------------------------------------------------------------ */
282     /**
283      * Returns a list of resource names contained in the given resource
284      * The resource names are not URL encoded.
285      */

286     public abstract String JavaDoc[] list();
287
288     /* ------------------------------------------------------------ */
289     /**
290      * Returns the resource contained inside the current resource with the
291      * given name.
292      * @param path The path segment to add, which should be encoded by the
293      * encode method.
294      */

295     public abstract Resource addPath(String JavaDoc path)
296         throws IOException JavaDoc,MalformedURLException JavaDoc;
297     
298
299     /* ------------------------------------------------------------ */
300     /** Encode according to this resource type.
301      * The default implementation calls URI.encodePath(uri)
302      * @param uri
303      * @return String encoded for this resource type.
304      */

305     public String JavaDoc encode(String JavaDoc uri)
306     {
307         return URI.encodePath(uri);
308     }
309     
310         
311     /* ------------------------------------------------------------ */
312     public Object JavaDoc getAssociate()
313     {
314         return _associate;
315     }
316
317     /* ------------------------------------------------------------ */
318     public void setAssociate(Object JavaDoc o)
319     {
320         _associate=o;
321     }
322     
323     /* ------------------------------------------------------------ */
324     /**
325      * @return The canonical Alias of this resource or null if none.
326      */

327     public URL JavaDoc getAlias()
328     {
329         return null;
330     }
331     
332
333     /* ------------------------------------------------------------ */
334     public CachedResource cache()
335         throws IOException JavaDoc
336     {
337         return new CachedResource(this);
338     }
339     
340     /* ------------------------------------------------------------ */
341     /** Get the resource list as a HTML directory listing.
342      * @param base The base URL
343      * @param parent True if the parent directory should be included
344      * @return String of HTML
345      */

346     public String JavaDoc getListHTML(String JavaDoc base,
347                               boolean parent)
348         throws IOException JavaDoc
349     {
350         if (!isDirectory())
351             return null;
352         
353       
354         String JavaDoc[] ls = list();
355         if (ls==null)
356             return null;
357         Arrays.sort(ls);
358         
359         String JavaDoc title = "Directory: "+URI.decodePath(base);
360         title=StringUtil.replace(StringUtil.replace(title,"<","&lt;"),">","&gt;");
361         StringBuffer JavaDoc buf=new StringBuffer JavaDoc(4096);
362         buf.append("<HTML><HEAD><TITLE>");
363         buf.append(title);
364         buf.append("</TITLE></HEAD><BODY>\n<H1>");
365         buf.append(title);
366         buf.append("</H1><TABLE BORDER=0>");
367         
368         if (parent)
369         {
370             buf.append("<TR><TD><A HREF=");
371             buf.append(URI.encodePath(URI.addPaths(base,"../")));
372             buf.append(">Parent Directory</A></TD><TD></TD><TD></TD></TR>\n");
373         }
374         
375         DateFormat JavaDoc dfmt=DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
376                                                        DateFormat.MEDIUM);
377         for (int i=0 ; i< ls.length ; i++)
378         {
379             String JavaDoc encoded=URI.encodePath(ls[i]);
380             Resource item = addPath(encoded);
381             
382             buf.append("<TR><TD><A HREF=\"");
383             
384             String JavaDoc path=URI.addPaths(base,encoded);
385             
386             if (item.isDirectory() && !path.endsWith("/"))
387                 path=URI.addPaths(path,"/");
388             buf.append(path);
389             buf.append("\">");
390             buf.append(StringUtil.replace(StringUtil.replace(ls[i],"<","&lt;"),">","&gt;"));
391             buf.append("&nbsp;");
392             buf.append("</TD><TD ALIGN=right>");
393             buf.append(item.length());
394             buf.append(" bytes&nbsp;</TD><TD>");
395             buf.append(dfmt.format(new Date JavaDoc(item.lastModified())));
396             buf.append("</TD></TR>\n");
397         }
398         buf.append("</TABLE>\n");
399     buf.append("</BODY></HTML>\n");
400         
401         return buf.toString();
402     }
403     
404     /* ------------------------------------------------------------ */
405     /**
406      * @param out
407      * @param start First byte to write
408      * @param count Bytes to write or -1 for all of them.
409      */

410     public void writeTo(OutputStream JavaDoc out,long start,long count)
411         throws IOException JavaDoc
412     {
413         InputStream JavaDoc in = getInputStream();
414         try
415         {
416             in.skip(start);
417             if (count<0)
418                 IO.copy(in,out);
419             else
420                 IO.copy(in,out,(int)count);
421         }
422         finally
423         {
424             in.close();
425         }
426     }
427 }
428
Popular Tags