1 13 package com.tonbeller.wcf.utils; 14 15 import java.net.MalformedURLException ; 16 import java.net.URL ; 17 import java.util.Hashtable ; 18 import java.util.Locale ; 19 import java.util.MissingResourceException ; 20 21 import javax.servlet.ServletContext ; 22 23 28 public class ResourceLocator { 29 private static final String WEBKEY = ResourceLocator.class.getName(); 30 private Hashtable urlCache = new Hashtable (); 31 32 private ResourceLocator() { 33 } 34 35 static ResourceLocator instance(ServletContext context) { 36 ResourceLocator loc = (ResourceLocator) context.getAttribute(WEBKEY); 37 if (loc == null) { 38 loc = new ResourceLocator(); 39 context.setAttribute(WEBKEY, loc); 40 } 41 return loc; 42 } 43 44 59 60 public static URL getResource(ServletContext context, Locale locale, String uri) 61 throws MalformedURLException , MissingResourceException { 62 return instance(context).findResource(context, locale, uri); 63 } 64 65 URL findResource(ServletContext context, Locale locale, String path) 66 throws MalformedURLException , MissingResourceException { 67 String ext = ""; 68 69 if (path.lastIndexOf("/") < path.lastIndexOf('.')) { 71 int pos = path.lastIndexOf('.'); 72 ext = path.substring(pos, path.length()); path = path.substring(0, pos); 74 } 75 76 String test1 = path + "_" + locale.getLanguage() + "_" + locale.getCountry() + ext; 77 if (urlCache.containsKey(test1)) { 78 return (URL ) urlCache.get(test1); 79 } 80 81 URL url = context.getResource(test1); 82 if (url != null) { 83 urlCache.put(test1, url); 84 return url; 85 } 86 87 String test = path + "_" + locale.getLanguage() + ext; 88 url = context.getResource(test); 89 if (url != null) { 90 urlCache.put(test1, url); 91 return url; 92 } 93 94 test = path + ext; 95 url = context.getResource(test); 96 if (url != null) { 97 urlCache.put(test1, url); 98 return url; 99 } 100 101 throw new MissingResourceException ("Resource \"" + path + "\" not found", ResourceLocator.class.getName(), path + ext); 102 } 103 104 } 105 | Popular Tags |