View Javadoc

1   /*
2    * @(#) URLResource.java Jun 17, 2004
3    * 
4    * Copyright (c) 2003 Delft University of Technology Jaffalaan 5, 2628 BX Delft,
5    * the Netherlands All rights reserved.
6    * 
7    * This software is proprietary information of Delft University of Technology
8    * The code is published under the General Public License
9    */
10  package nl.tudelft.simulation.language.io;
11  
12  import java.io.File;
13  import java.io.InputStream;
14  import java.net.URL;
15  
16  /***
17   * <p>
18   * (c) copyright 2003 <a href="http://www.simulation.tudelft.nl">Delft
19   * University of Technology </a>, the Netherlands. <br>
20   * See for project information <a
21   * href="http://www.simulation.tudelft.nl">www.simulation.tudelft.nl </a> <br>
22   * License of use: <a href="http://www.gnu.org/copyleft/gpl.html">General Public
23   * License (GPL) </a>, no warranty <br>
24   * 
25   * @author <a href="http://www.tbm.tudelft.nl/webstaf/peterja/index.htm">Peter
26   *         Jacobs </a>
27   * @version 1.2 Jun 17, 2004
28   * @since 1.4
29   */
30  public final class URLResource
31  {
32  	/***
33  	 * constructs a new URLResource
34  	 */
35  	private URLResource()
36  	{
37  		super();
38  		//unreachable code
39  	}
40  
41  	/***
42  	 * resolves a resource for name
43  	 * 
44  	 * @param name the name to search for
45  	 * @return the resolved URL
46  	 */
47  	public static URL getResource(final String name)
48  	{
49  		try
50  		{
51  			if (name.startsWith("/"))
52  			{
53  				URL url = URLResource.class.getResource(name);
54  				if (url != null)
55  				{
56  					return url;
57  				}
58  				url = Thread.currentThread().getContextClassLoader()
59  						.getResource(name.substring(1));
60  				if (url != null)
61  				{
62  					return url;
63  				}
64  				File file = new File(name);
65  				if (file.exists())
66  				{
67  					return new URL("file:" + name);
68  				}
69  			} else
70  			{
71  				return new URL(name);
72  			}
73  		} catch (Exception exception)
74  		{
75  			exception = null;
76  			//We neglect exceptions since we return null
77  		}
78  		return null;
79  	}
80  
81  	/***
82  	 * returns the reseource as stream
83  	 * 
84  	 * @param name the name of the resource
85  	 * @return the inputStream
86  	 */
87  	public static InputStream getResourceAsStream(final String name)
88  	{
89  		try
90  		{
91  			URL url = URLResource.getResource(name);
92  			if (url == null)
93  			{
94  				return null;
95  			}
96  			return url.openStream();
97  		} catch (Exception exception)
98  		{
99  			return null;
100 		}
101 	}
102 }