1 17 package org.apache.avalon.util.i18n; 18 19 import java.lang.ref.WeakReference ; 20 import java.util.HashMap ; 21 22 27 public class ResourceManager 28 { 29 32 private static final RuntimePermission CLEAR_CACHE_PERMISSION = 33 new RuntimePermission ( "i18n.clearCompleteCache" ); 34 private static final HashMap c_resources = new HashMap (); 35 36 42 public static final Resources getBaseResources( final String baseName ) 43 { 44 return getBaseResources( baseName, null ); 45 } 46 47 54 public synchronized static final Resources getBaseResources( final String baseName, 55 final ClassLoader classLoader ) 56 { 57 Resources resources = getCachedResource( baseName ); 58 if( null == resources ) 59 { 60 resources = new Resources( baseName, classLoader ); 61 putCachedResource( baseName, resources ); 62 } 63 64 return resources; 65 } 66 67 80 public synchronized static final void clearResourceCache() 81 throws SecurityException 82 { 83 final SecurityManager sm = System.getSecurityManager(); 84 if( null != sm ) 85 { 86 sm.checkPermission( CLEAR_CACHE_PERMISSION ); 87 } 88 89 c_resources.clear(); 90 } 91 92 98 private synchronized static final void putCachedResource( final String baseName, 99 final Resources resources ) 100 { 101 c_resources.put( baseName, 102 new WeakReference ( resources ) ); 103 } 104 105 111 private synchronized static final Resources getCachedResource( final String baseName ) 112 { 113 final WeakReference weakReference = 114 (WeakReference )c_resources.get( baseName ); 115 if( null == weakReference ) 116 { 117 return null; 118 } 119 else 120 { 121 return (Resources)weakReference.get(); 122 } 123 } 124 125 132 public static final Resources getResources( final String name ) 133 { 134 return getBaseResources( name + ".Resources" ); 135 } 136 137 145 public static final Resources getPackageResources( final Class clazz ) 146 { 147 return getBaseResources( getPackageResourcesBaseName( clazz ), clazz.getClassLoader() ); 148 } 149 150 158 public static final Resources getClassResources( final Class clazz ) 159 { 160 return getBaseResources( getClassResourcesBaseName( clazz ), clazz.getClassLoader() ); 161 } 162 163 171 public static final String getPackageResourcesBaseName( final Class clazz ) 172 { 173 final Package pkg = clazz.getPackage(); 174 175 String baseName; 176 if( null == pkg ) 177 { 178 final String name = clazz.getName(); 179 if( -1 == name.lastIndexOf( "." ) ) 180 { 181 baseName = "Resources"; 182 } 183 else 184 { 185 baseName = name.substring( 0, name.lastIndexOf( "." ) ) + ".Resources"; 186 } 187 } 188 else 189 { 190 baseName = pkg.getName() + ".Resources"; 191 } 192 193 return baseName; 194 } 195 196 204 public static final String getClassResourcesBaseName( final Class clazz ) 205 { 206 return clazz.getName() + "Resources"; 207 } 208 209 212 private ResourceManager() 213 { 214 } 215 } 216 | Popular Tags |