View Javadoc

1   /*
2    * Common Library for TBAS Softwares
3    * Language: Java
4    *
5    * All Rights Reserved.
6    * (c) Copyright 2003 by Tsukuba Bunko.
7    *
8    * $Id: ResourceLocatorImpl.java,v 1.1 2005/07/11 12:49:19 ppoi Exp $
9    */
10  package tsukuba_bunko.util.locator;
11  
12  import	java.io.File;
13  import	java.io.UnsupportedEncodingException;
14  
15  import	java.net.URL;
16  import	java.net.URLDecoder;
17  
18  import	tsukuba_bunko.util.ResourceLocator;
19  import	tsukuba_bunko.util.ResourceDetectionException;
20  
21  
22  /***
23   * デフォルトの {@link tsukuba_bunko.util.ResourceLocator} 実装です。
24   * @author	$Author: ppoi $
25   * @version	$Revision: 1.1 $
26   */
27  public class ResourceLocatorImpl	extends ResourceLocator	{
28  
29  	/***
30  	 * 指定されたリソースを検索し、リソースの URL が file URL の場合、ファイルシステム上のパスを、JAR URL の場合、JAR のファイルパスを返します。
31  	 * それ以外の種類の URL の場合、<code>null</code> を返します。
32  	 * @see tsukuba_bunko.util.ResourceLocator#findLocation(java.lang.String, java.lang.ClassLoader)
33  	 */
34  	public File findLocation( String resourceName, ClassLoader classLoader )
35  		throws ResourceDetectionException
36  	{
37  		URL	resourceURL = classLoader.getResource( resourceName );
38  		if( resourceURL == null )	{
39  			throw new ResourceDetectionException( "fail to find resource from classpath" );
40  		}
41  
42  		String	protocol = resourceURL.getProtocol();
43  		if( "file".equals(protocol) )	{
44  			String	path =   resourceURL.getFile();
45  			try	{
46  				path = URLDecoder.decode( path, "UTF-8" );
47  			}
48  			catch( UnsupportedEncodingException uee )	{
49  				throw new ResourceDetectionException( "system is not supoort UTF-8. This Java VM may be broken.", uee );
50  			}
51  
52  			int	index = path.indexOf( resourceName );
53  			if( index > 0 )	{
54  				resourceName = resourceName.substring( 0, index );
55  			}
56  			return new File( resourceName );
57  		}
58  		else if( "jar".equals(protocol) )	{
59  			String	jarUri = resourceURL.toString();
60  			int	delemiterIndex = jarUri.indexOf( "!/" );
61  			if( delemiterIndex == -1 )	{
62  				throw new ResourceDetectionException( "invalid JAR URL." );
63  			}
64  			else	{
65  				String	resourceUri = jarUri.substring( 4, delemiterIndex );
66  				if( !resourceUri.startsWith("file:") )	{
67  					throw new ResourceDetectionException( "supported file protocol only" );
68  				}
69  				else	{
70  					try	{
71  						return new File( URLDecoder.decode( new URL(resourceUri).getFile(), "UTF-8") );
72  					}
73  					catch( Exception e )	{
74  						throw new ResourceDetectionException( "invalid URL.", e );
75  					}
76  				}
77  			}
78  		}
79  		else	{
80  			throw new ResourceDetectionException( "supported jar or file protocol only" );
81  		}
82  	}
83  }