1 16 17 package org.apache.velocity.tools.view.servlet; 18 19 import javax.servlet.ServletContext ; 20 21 import java.io.InputStream ; 22 23 import org.apache.commons.collections.ExtendedProperties; 24 25 import org.apache.velocity.exception.ResourceNotFoundException; 26 import org.apache.velocity.runtime.RuntimeServices; 27 import org.apache.velocity.runtime.resource.Resource; 28 import org.apache.velocity.runtime.resource.loader.ResourceLoader; 29 30 48 public class WebappLoader extends ResourceLoader 49 { 50 51 52 protected String [] paths = null; 53 54 protected ServletContext servletContext = null; 55 56 66 public void init(ExtendedProperties configuration) 67 { 68 rsvc.info("WebappLoader : initialization starting."); 69 70 71 paths = configuration.getStringArray("path"); 72 if (paths == null || paths.length == 0) 73 { 74 paths = new String [1]; 75 paths[0] = "/"; 76 } 77 else 78 { 79 80 for (int i=0; i < paths.length; i++) 81 { 82 if (!paths[i].endsWith("/")) 83 { 84 paths[i] += '/'; 85 } 86 rsvc.info("WebappLoader : added template path - '" + paths[i] + "'"); 87 } 88 } 89 90 91 Object obj = rsvc.getApplicationAttribute(ServletContext .class.getName()); 92 if (obj instanceof ServletContext ) 93 { 94 servletContext = (ServletContext )obj; 95 } 96 else 97 { 98 rsvc.error("WebappLoader : unable to retrieve ServletContext"); 99 } 100 101 rsvc.info("WebappLoader : initialization complete."); 102 } 103 104 113 public synchronized InputStream getResourceStream( String name ) 114 throws ResourceNotFoundException 115 { 116 InputStream result = null; 117 118 if (name == null || name.length() == 0) 119 { 120 throw new ResourceNotFoundException ("WebappLoader : No template name provided"); 121 } 122 123 125 while (name.startsWith("/")) 126 { 127 name = name.substring(1); 128 } 129 130 Exception exception = null; 131 for (int i=0; i < paths.length; i++) 132 { 133 try 134 { 135 result = servletContext.getResourceAsStream(paths[i] + name); 136 137 138 if (result != null) 139 { 140 break; 141 } 142 } 143 catch (Exception e) 144 { 145 146 if (exception == null) 147 { 148 exception = e; 149 } 150 } 151 } 152 153 154 if (result == null) 155 { 156 String msg; 157 if (exception == null) 158 { 159 msg = "WebappLoader : Resource '" + name + "' not found."; 160 } 161 else 162 { 163 msg = exception.getMessage(); 164 } 165 166 throw new ResourceNotFoundException(msg); 167 } 168 169 return result; 170 } 171 172 175 public boolean isSourceModified(Resource resource) 176 { 177 return false; 178 } 179 180 183 public long getLastModified(Resource resource) 184 { 185 return 0; 186 } 187 } 188 | Popular Tags |