WebObjects/Web 应用程序/开发/自定义资源管理器
外观
以下是一个关于如何编写自己的 WOResourceManager 的简单示例
需要实现的主要方法是 urlForResourceNamed() 和 bytesForResourceNamed()。
- urlForResourceNamed 简单地从您想要的任何地方(例如 jar 文件)为资源构建一个 URL。不幸的是,urlForResourceNamed 使用 pathForResourceNamed,因此您也需要重写它
private URL urlForResourceNamed(String aResourceName) { return this.getClass().getResource( aResourceName ); } public String pathForResourceNamed(String aResourceName, String aFrameworkName, NSArray someLanguages) { URL anURL = this.urlForResourceNamed( aResourceName ); if ( anURL != null ) { return anURL.toExternalForm(); } return null; } public String urlForResourceNamed(String aResourceName, String aFrameworkName, NSArray someLanguages, WORequest aRequest) { String anURL = super.urlForResourceNamed( aResourceName, aFrameworkName, someLanguages, aRequest ); this.bytesForResourceNamed( aResourceName, aFrameworkName, someLanguages ); return anURL; }
- bytesForResourceNamed 简单地从您想要的任何地方(例如 jar 文件)检索资源
public InputStream inputStreamForResourceNamed(String aResourceName, String aFrameworkName, NSArray someLanguages) { return this.getClass().getResourceAsStream( aResourceName ); } public byte[] bytesForResourceNamed(String aResourceName, String aFrameworkName, NSArray someLanguages) { if ( aResourceName != null ) { URL anURL = this.urlForResourceNamed( aResourceName ); if ( anURL != null ) { String aKey = anURL.toString(); WOURLValuedElementData anElement = (WOURLValuedElementData) _cache.get( aKey ); if ( anElement == null ) { synchronized( this ) { InputStream anInputStream = this.inputStreamForResourceNamed( aResourceName, null, null ); if ( anInputStream != null ) { try { InputStream aBufferStream = new BufferedInputStream( anInputStream ); byte[] someBytes = new byte[ aBufferStream.available() ]; aBufferStream.read( someBytes ); aBufferStream.close(); anInputStream.close(); { Data someData = new Data( someBytes ); String aType = this.contentTypeForResourceNamed( aKey ); anElement = new WOURLValuedElementData( someData, aType, aKey ); _cache.put( aKey, anElement ); } } catch(Exception anException) { SZLog.warning( anException ); } } } } return ( (Data) anElement.data() ).bytesNoCopy(); } SZLog.debug( "Null url for resource named '" + aResourceName + "'." ); return null; } throw new IllegalArgumentException ( "ResourceManager.bytesForResourceNamed: null resource name." ); }
- 最后但并非最不重要的是,您需要处理那些古怪的 WOURLValuedElementData,这样 dataForResourceNamed 才能正常工作
public NSData dataForResourceNamed(String aResourceName) { this.bytesForResourceNamed( aResourceName, null, null ); String aKey = this.urlForResourceNamed( aResourceName ).toString(); WOURLValuedElementData anElement = (WOURLValuedElementData) _cache.get( aKey ); return anElement.data(); }
- 最后,您需要将您的资源管理器注册到 WOApplication
anApplication.setResourceManager( new ResourceManager() );
语言和框架的处理留给读者作为练习。