View Javadoc

1   /**
2    * This file Copyright (c) 2003-2014 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.freemarker;
35  
36  import info.magnolia.cms.util.ClasspathResourcesUtil;
37  
38  import java.beans.PropertyDescriptor;
39  import java.io.File;
40  import java.io.FileInputStream;
41  import java.io.FileNotFoundException;
42  import java.io.InputStream;
43  import java.net.MalformedURLException;
44  import java.net.URL;
45  import java.net.URLClassLoader;
46  import java.util.Enumeration;
47  import java.util.HashSet;
48  import java.util.List;
49  import java.util.Set;
50  
51  import javax.servlet.RequestDispatcher;
52  import javax.servlet.Servlet;
53  import javax.servlet.ServletContext;
54  import javax.servlet.ServletException;
55  
56  import org.apache.commons.io.FileUtils;
57  import org.apache.commons.lang.StringUtils;
58  import org.slf4j.Logger;
59  import org.slf4j.LoggerFactory;
60  
61  
62  /**
63   * Wraps the servlet context expecially for freemarker taglib resolution. This will trick freemarker TaglibFactory class
64   * to "see" all jars in classpath as if they were jars in /WEB-INF/lib
65   * @author Danilo Ghirardelli
66   */
67  public class FreemarkerServletContextWrapper implements ServletContext {
68  
69      private final ServletContext parentContext;
70  
71      /**
72       * Logger.
73       */
74      private static Logger log = LoggerFactory.getLogger(FreemarkerServletContextWrapper.class);
75  
76      public FreemarkerServletContextWrapper(ServletContext parentServletContext) {
77          // allow also a null parent context for unit tests
78          this.parentContext = parentServletContext;
79      }
80  
81      @Override
82      public URL getResource(String path) throws MalformedURLException {
83  
84          URL result = null;
85          if (path.startsWith("/")) {
86              result = parentContext.getResource(path);
87          }
88          if (result == null) {
89              // Trying the absolute path if the parent context fails.
90              File file = new File(path);
91              if ((file.exists()) && (file.isFile())) {
92                  result = file.toURI().toURL();
93              }
94          }
95          return result;
96      }
97  
98      @Override
99      public InputStream getResourceAsStream(String path) {
100 
101         InputStream is = null;
102         if (path.startsWith("/")) {
103             is = parentContext.getResourceAsStream(path);
104         }
105         if (is == null) {
106             // Trying the absolute path if the parent context fails.
107             File file = new File(path);
108             if ((file.exists()) && (file.isFile())) {
109                 try {
110                     return new FileInputStream(file);
111                 }
112                 catch (FileNotFoundException e) {
113                     // Ignore, file not found
114                 }
115             }
116         }
117         return is;
118     }
119 
120     @Override
121     @SuppressWarnings({"unchecked", "rawtypes"})
122     public Set getResourcePaths(String path) {
123         if (StringUtils.equals(path, "/WEB-INF/lib")) {
124             log.debug("returning resources from classpath");
125             // Just when asking libraries, pass the classpath ones.
126             final Set<String> resources = new HashSet<String>();
127             final ClassLoader cl = Thread.currentThread().getContextClassLoader();
128             // if the classloader is an URLClassloader we have a better method for discovering resources
129             // whis will also fetch files from jars outside WEB-INF/lib, useful during development
130             if (cl instanceof URLClassLoader) {
131                 final URLClassLoader urlClassLoader = (URLClassLoader) cl;
132                 final URL[] urls = urlClassLoader.getURLs();
133                 for (int j = 0; j < urls.length; j++) {
134                     final File tofile = ClasspathResourcesUtil.sanitizeToFile(urls[j]);
135                     if (tofile == null) {
136                         continue;
137                     }
138                     if (tofile.isDirectory()) {
139                         for (File file : ((List<File>) FileUtils.listFiles(tofile, null, true))) {
140                             resources.add(file.getAbsolutePath());
141                         }
142                     }
143                     else {
144                         resources.add(tofile.getAbsolutePath());
145                     }
146                 }
147 
148                 return resources;
149             }
150             try {
151                 // be friendly to WAS developers too...
152                 // in development mode under RAD 7.5 here we have an instance of com.ibm.ws.classloader.WsClassLoader
153                 // and jars are NOT deployed to WEB-INF/lib by default, so they can't be found without this explicit
154                 // check
155                 //
156                 // but since we don't want to depend on WAS stuff we just check if the cl exposes a "classPath" property
157                 PropertyDescriptor pd = new PropertyDescriptor("classPath", cl.getClass());
158                 if (pd != null && pd.getReadMethod() != null) {
159                     String classpath = (String) pd.getReadMethod().invoke(cl, new Object[]{});
160                     if (StringUtils.isNotBlank(classpath)) {
161                         String[] paths = StringUtils.split(classpath, File.pathSeparator);
162                         for (int j = 0; j < paths.length; j++) {
163                             final File tofile = new File(paths[j]);
164                             // there can be several missing (optional?) paths here...
165                             if (tofile.exists()) {
166                                 if (tofile.isDirectory()) {
167                                     for (File file : ((List<File>) FileUtils.listFiles(tofile, null, true))) {
168                                         resources.add(file.getAbsolutePath());
169                                     }
170                                 }
171                                 else {
172                                     resources.add(tofile.getAbsolutePath());
173                                 }
174                             }
175                         }
176                         return resources;
177                     }
178                 }
179             }
180             catch (Throwable e) {
181                 // no, it's not a classloader we can handle in a special way
182             }
183             // no way, we have to assume a standard war structure and look in the WEB-INF/lib and WEB-INF/classes dirs
184             // read the jars in the lib dir
185         }
186         return parentContext.getResourcePaths(path);
187     }
188 
189     // Below here, just methods that redirects to the wrapped context.
190     @Override
191     public Object getAttribute(String name) {
192         return parentContext.getAttribute(name);
193     }
194 
195     @SuppressWarnings("rawtypes")
196     @Override
197     public Enumeration getAttributeNames() {
198         return parentContext.getAttributeNames();
199     }
200 
201     @Override
202     public ServletContext getContext(String uripath) {
203         return parentContext.getContext(uripath);
204     }
205 
206     @Override
207     public String getContextPath() {
208         return parentContext.getContextPath();
209     }
210 
211     @Override
212     public String getInitParameter(String name) {
213         return parentContext.getInitParameter(name);
214     }
215 
216     @SuppressWarnings("rawtypes")
217     @Override
218     public Enumeration getInitParameterNames() {
219         return parentContext.getInitParameterNames();
220     }
221 
222     @Override
223     public int getMajorVersion() {
224         return parentContext.getMajorVersion();
225     }
226 
227     @Override
228     public String getMimeType(String file) {
229         return parentContext.getMimeType(file);
230     }
231 
232     @Override
233     public int getMinorVersion() {
234         return parentContext.getMinorVersion();
235     }
236 
237     @Override
238     public RequestDispatcher getNamedDispatcher(String name) {
239         return parentContext.getNamedDispatcher(name);
240     }
241 
242     @Override
243     public String getRealPath(String path) {
244         return parentContext.getRealPath(path);
245     }
246 
247     @Override
248     public RequestDispatcher getRequestDispatcher(String path) {
249         return parentContext.getRequestDispatcher(path);
250     }
251 
252     @Override
253     public String getServerInfo() {
254         return parentContext.getServerInfo();
255     }
256 
257     @SuppressWarnings("deprecation")
258     @Override
259     public Servlet getServlet(String name) throws ServletException {
260         return parentContext.getServlet(name);
261     }
262 
263     @Override
264     public String getServletContextName() {
265         return parentContext.getServletContextName();
266     }
267 
268     @SuppressWarnings({"rawtypes", "deprecation"})
269     @Override
270     public Enumeration getServletNames() {
271         return parentContext.getServletNames();
272     }
273 
274     @SuppressWarnings({"rawtypes", "deprecation"})
275     @Override
276     public Enumeration getServlets() {
277         return parentContext.getServlets();
278     }
279 
280     @Override
281     public void log(String msg) {
282         parentContext.log(msg);
283     }
284 
285     @SuppressWarnings("deprecation")
286     @Override
287     public void log(Exception exception, String msg) {
288         parentContext.log(exception, msg);
289     }
290 
291     @Override
292     public void log(String message, Throwable throwable) {
293         parentContext.log(message, throwable);
294     }
295 
296     @Override
297     public void removeAttribute(String name) {
298         parentContext.removeAttribute(name);
299     }
300 
301     @Override
302     public void setAttribute(String name, Object object) {
303         parentContext.setAttribute(name, object);
304     }
305 }