View Javadoc

1   /*
2    * Copyright (c) 2001 Peter Antman Tim <peter.antman@tim.se>
3    *
4    * This library is free software; you can redistribute it and/or
5    * modify it under the terms of the GNU Lesser General Public
6    * License as published by the Free Software Foundation; either
7    * version 2 of the License, or (at your option) any later version
8    * 
9    * This library is distributed in the hope that it will be useful,
10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12   * Lesser General Public License for more details.
13   * 
14   * You should have received a copy of the GNU Lesser General Public
15   * License along with this library; if not, write to the Free Software
16   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17   */
18  package org.backsource.utils.resource;
19  
20  import java.net.URL;
21  import java.net.MalformedURLException;
22  
23  import javax.servlet.ServletContext;
24  /***
25   * <p>Resolve URI:s to URL by looking them up in the ServletContext.
26   *
27   * <p>The URI.getPath() is used to get the resource name.
28   *
29   * @author Peter Antman
30   * @version $Revison$
31   */
32  
33  public class ServletContextURLFactory implements URLFactory {
34      private ServletContext ctx = null;
35      
36      private ServletContextURLFactory() {
37  	// Must have a servlet context
38  	
39      }
40      
41      /***
42       * Create with a ServletContext.
43       *
44       * @param ctx a servlet context
45       * @exception IllegalArgumentException thrown if ctx is null
46       */
47      public ServletContextURLFactory(ServletContext ctx) {
48  	if (ctx == null)
49  	    throw new IllegalArgumentException("ServletContext must not be null");
50  	this.ctx = ctx;
51      }
52      /***
53       * Construct an URL from URI by looking it up in the ContextClassLoader.
54       */
55      public URL getURL(URI uri) throws  MalformedURLException {
56  	String resUri = getResURI(uri);
57  	URL url = ctx.getResource( resUri );
58  	if (url == null)
59  	     throw new MalformedURLException("Could not find resource: " + resUri);
60  	return url;
61      }
62  
63      protected String getResURI(URI uri) {
64  	// We only use the file part
65  	// FIXME, should the beginning / be removed?
66  	return uri.getPath();
67      }
68  } // ServletContextURLFactory