1 19 20 package org.apache.cayenne.util; 21 22 import java.net.MalformedURLException ; 23 import java.net.URL ; 24 import java.util.ArrayList ; 25 import java.util.Iterator ; 26 import java.util.List ; 27 28 import javax.servlet.ServletContext ; 29 30 import org.apache.commons.logging.Log; 31 import org.apache.commons.logging.LogFactory; 32 33 38 public class WebApplicationResourceLocator extends ResourceLocator { 39 40 private static Log logObj = LogFactory.getLog(WebApplicationResourceLocator.class); 41 42 protected ServletContext context; 43 protected List additionalContextPaths; 44 45 48 public WebApplicationResourceLocator() { 49 this.additionalContextPaths = new ArrayList (); 50 this.addFilesystemPath("/WEB-INF/"); 51 } 52 53 57 public WebApplicationResourceLocator(ServletContext context) { 58 this(); 59 setServletContext(context); 60 } 61 62 65 public void setServletContext(ServletContext servletContext) { 66 this.context = servletContext; 67 } 68 69 72 public ServletContext getServletContext() { 73 return this.context; 74 } 75 76 80 public URL findResource(String location) { 81 if (!additionalContextPaths.isEmpty() && getServletContext() != null) { 82 83 String suffix = location != null ? location : ""; 84 if (suffix.startsWith("/")) { 85 suffix = suffix.substring(1); 86 } 87 88 Iterator cpi = this.additionalContextPaths.iterator(); 89 while (cpi.hasNext()) { 90 String prefix = (String ) cpi.next(); 91 92 if (!prefix.endsWith("/")) { 93 prefix += "/"; 94 } 95 96 String fullName = prefix + suffix; 97 logObj.debug("searching for: " + fullName); 98 try { 99 URL url = getServletContext().getResource(fullName); 100 if (url != null) { 101 return url; 102 } 103 } 104 catch (MalformedURLException ex) { 105 logObj.debug("Malformed URL, ignoring.", ex); 107 } 108 } 109 } 110 111 return super.findResource(location); 112 } 113 114 118 public void addFilesystemPath(String path) { 119 if (path != null) { 120 if (path.startsWith("/WEB-INF/")) { 121 this.additionalContextPaths.add(path); 122 } 123 else { 124 super.addFilesystemPath(path); 125 } 126 } 127 else { 128 throw new IllegalArgumentException ("Path must not be null."); 129 } 130 } 131 } 132 | Popular Tags |