/*
 * Common Library for TBAS Softwares
 * Language: Java
 *
 * All Rights Reserved.
 * (c) Copyright 2003 by Tsukuba Bunko.
 *
 * $Id: ResourceLocatorImpl.java,v 1.1 2003/08/31 08:20:49 ppoi Exp $
 */
package tsukuba_bunko.util.locator;

import	java.io.File;
import	java.io.UnsupportedEncodingException;

import	java.net.URL;
import	java.net.URLDecoder;

import	tsukuba_bunko.util.ResourceLocator;
import	tsukuba_bunko.util.ResourceDetectionException;


/**
 * デフォルトの {@link tsukuba_bunko.util.ResourceLocator} 実装です。
 * @author	$Author: ppoi $
 * @version	$Revision: 1.1 $
 */
public class ResourceLocatorImpl	extends ResourceLocator	{

	/**
	 * 指定されたリソースを検索し、リソースの URL が file URL の場合、ファイルシステム上のパスを、JAR URL の場合、JAR のファイルパスを返します。
	 * それ以外の種類の URL の場合、<code>null</code> を返します。
	 * @see tsukuba_bunko.util.ResourceLocator#findLocation(java.lang.String, java.lang.ClassLoader)
	 */
	public File findLocation( String resourceName, ClassLoader classLoader )
		throws ResourceDetectionException
	{
		URL	resourceURL = classLoader.getResource( resourceName );
		if( resourceURL == null )	{
			throw new ResourceDetectionException( "fail to find resource from classpath" );
		}

		String	protocol = resourceURL.getProtocol();
		if( "file".equals(protocol) )	{
			String	path =   resourceURL.getFile();
			try	{
				path = URLDecoder.decode( path, "UTF-8" );
			}
			catch( UnsupportedEncodingException uee )	{
				throw new ResourceDetectionException( "system is not supoort UTF-8. This Java VM may be broken.", uee );
			}

			int	index = path.indexOf( resourceName );
			if( index > 0 )	{
				resourceName = resourceName.substring( 0, index );
			}
			return new File( resourceName );
		}
		else if( "jar".equals(protocol) )	{
			String	jarUri = resourceURL.toString();
			int	delemiterIndex = jarUri.indexOf( "!/" );
			if( delemiterIndex == -1 )	{
				throw new ResourceDetectionException( "invalid JAR URL." );
			}
			else	{
				String	resourceUri = jarUri.substring( 4, delemiterIndex );
				if( !resourceUri.startsWith("file:") )	{
					throw new ResourceDetectionException( "supported file protocol only" );
				}
				else	{
					try	{
						return new File( URLDecoder.decode( new URL(resourceUri).getFile(), "UTF-8") );
					}
					catch( Exception e )	{
						throw new ResourceDetectionException( "invalid URL.", e );
					}
				}
			}
		}
		else	{
			throw new ResourceDetectionException( "supported jar or file protocol only" );
		}
	}
}