View Javadoc
1   /**
2    * This file Copyright (c) 2003-2016 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.Set;
49  
50  import javax.servlet.RequestDispatcher;
51  import javax.servlet.Servlet;
52  import javax.servlet.ServletContext;
53  import javax.servlet.ServletException;
54  
55  import org.apache.commons.io.FileUtils;
56  import org.apache.commons.lang3.StringUtils;
57  import org.slf4j.Logger;
58  import org.slf4j.LoggerFactory;
59  
60  
61  /**
62   * Wraps the servlet context especially for freemarker taglib resolution. This will trick freemarker TaglibFactory class
63   * to "see" all jars in classpath as if they were jars in /WEB-INF/lib.
64   *
65   * On Windows systems the implementation of getResourcePaths will return absolute paths including the drive letter. When
66   * freemarker then calls getResource and getResourceAsStream we must not call the wrapped servlet context because its
67   * not a valid URL and it will fail with a MalformedURLException. See MAGNOLIA-5651.
68   */
69  public class FreemarkerServletContextWrapper implements ServletContext {
70  
71      private final ServletContext parentContext;
72  
73      private static Logger log = LoggerFactory.getLogger(FreemarkerServletContextWrapper.class);
74  
75      public FreemarkerServletContextWrapper(ServletContext parentServletContext) {
76          // allow also a null parent context for unit tests
77          this.parentContext = parentServletContext;
78      }
79  
80      @Override
81      public URL getResource(String path) throws MalformedURLException {
82  
83          URL result = null;
84          if (path.startsWith("/")) {
85              result = parentContext.getResource(path);
86          }
87          if (result == null) {
88              // Trying the absolute path if the parent context fails.
89              File file = new File(path);
90              if ((file.exists()) && (file.isFile())) {
91                  result = file.toURI().toURL();
92              }
93          }
94          return result;
95      }
96  
97      @Override
98      public InputStream getResourceAsStream(String path) {
99  
100         InputStream is = null;
101         if (path.startsWith("/")) {
102             is = parentContext.getResourceAsStream(path);
103         }
104         if (is == null) {
105             // Trying the absolute path if the parent context fails.
106             File file = new File(path);
107             if ((file.exists()) && (file.isFile())) {
108                 try {
109                     return new FileInputStream(file);
110                 } catch (FileNotFoundException e) {
111                     // Ignore, file not found
112                 }
113             }
114         }
115         return is;
116     }
117 
118     @Override
119     @SuppressWarnings("rawtypes")
120     public Set getResourcePaths(String path) {
121         if (StringUtils.equals(path, "/WEB-INF/lib")) {
122             log.debug("returning resources from classpath");
123             // Just when asking libraries, pass the classpath ones.
124             final Set<String> resources = new HashSet<String>();
125             final ClassLoader cl = Thread.currentThread().getContextClassLoader();
126             // if the classloader is an URLClassloader we have a better method for discovering resources
127             // whis will also fetch files from jars outside WEB-INF/lib, useful during development
128             if (cl instanceof URLClassLoader) {
129                 final URLClassLoader urlClassLoader = (URLClassLoader) cl;
130                 final URL[] urls = urlClassLoader.getURLs();
131                 for (int j = 0; j < urls.length; j++) {
132                     final File tofile = ClasspathResourcesUtil.sanitizeToFile(urls[j]);
133                     if (tofile.isDirectory()) {
134                         for (File file : (FileUtils.listFiles(tofile, null, true))) {
135                             resources.add(file.getAbsolutePath());
136                         }
137                     } else {
138                         resources.add(tofile.getAbsolutePath());
139                     }
140                 }
141 
142                 return resources;
143             }
144             try {
145                 // be friendly to WAS developers too...
146                 // in development mode under RAD 7.5 here we have an instance of com.ibm.ws.classloader.WsClassLoader
147                 // and jars are NOT deployed to WEB-INF/lib by default, so they can't be found without this explicit
148                 // check
149                 //
150                 // but since we don't want to depend on WAS stuff we just check if the cl exposes a "classPath" property
151                 PropertyDescriptor pd = new PropertyDescriptor("classPath", cl.getClass());
152                 if (pd != null && pd.getReadMethod() != null) {
153                     String classpath = (String) pd.getReadMethod().invoke(cl);
154                     if (StringUtils.isNotBlank(classpath)) {
155                         String[] paths = StringUtils.split(classpath, File.pathSeparator);
156                         for (int j = 0; j < paths.length; j++) {
157                             final File tofile = new File(paths[j]);
158                             // there can be several missing (optional?) paths here...
159                             if (tofile.exists()) {
160                                 if (tofile.isDirectory()) {
161                                     for (File file : (FileUtils.listFiles(tofile, null, true))) {
162                                         resources.add(file.getAbsolutePath());
163                                     }
164                                 } else {
165                                     resources.add(tofile.getAbsolutePath());
166                                 }
167                             }
168                         }
169                         return resources;
170                     }
171                 }
172             } catch (Throwable e) {
173                 // no, it's not a classloader we can handle in a special way
174             }
175             // no way, we have to assume a standard war structure and look in the WEB-INF/lib and WEB-INF/classes dirs
176             // read the jars in the lib dir
177         }
178         return parentContext.getResourcePaths(path);
179     }
180 
181     // Below here, just methods that redirects to the wrapped context.
182     @Override
183     public Object getAttribute(String name) {
184         return parentContext.getAttribute(name);
185     }
186 
187     @SuppressWarnings("rawtypes")
188     @Override
189     public Enumeration getAttributeNames() {
190         return parentContext.getAttributeNames();
191     }
192 
193     @Override
194     public ServletContext getContext(String uripath) {
195         return parentContext.getContext(uripath);
196     }
197 
198     @Override
199     public String getContextPath() {
200         return parentContext.getContextPath();
201     }
202 
203     @Override
204     public String getInitParameter(String name) {
205         return parentContext.getInitParameter(name);
206     }
207 
208     @SuppressWarnings("rawtypes")
209     @Override
210     public Enumeration getInitParameterNames() {
211         return parentContext.getInitParameterNames();
212     }
213 
214     @Override
215     public int getMajorVersion() {
216         return parentContext.getMajorVersion();
217     }
218 
219     @Override
220     public String getMimeType(String file) {
221         return parentContext.getMimeType(file);
222     }
223 
224     @Override
225     public int getMinorVersion() {
226         return parentContext.getMinorVersion();
227     }
228 
229     @Override
230     public RequestDispatcher getNamedDispatcher(String name) {
231         return parentContext.getNamedDispatcher(name);
232     }
233 
234     @Override
235     public String getRealPath(String path) {
236         return parentContext.getRealPath(path);
237     }
238 
239     @Override
240     public RequestDispatcher getRequestDispatcher(String path) {
241         return parentContext.getRequestDispatcher(path);
242     }
243 
244     @Override
245     public String getServerInfo() {
246         return parentContext.getServerInfo();
247     }
248 
249     @SuppressWarnings("deprecation")
250     @Override
251     public Servlet getServlet(String name) throws ServletException {
252         return parentContext.getServlet(name);
253     }
254 
255     @Override
256     public String getServletContextName() {
257         return parentContext.getServletContextName();
258     }
259 
260     @SuppressWarnings({"rawtypes", "deprecation"})
261     @Override
262     public Enumeration getServletNames() {
263         return parentContext.getServletNames();
264     }
265 
266     @SuppressWarnings({"rawtypes", "deprecation"})
267     @Override
268     public Enumeration getServlets() {
269         return parentContext.getServlets();
270     }
271 
272     @Override
273     public void log(String msg) {
274         parentContext.log(msg);
275     }
276 
277     @SuppressWarnings("deprecation")
278     @Override
279     public void log(Exception exception, String msg) {
280         parentContext.log(exception, msg);
281     }
282 
283     @Override
284     public void log(String message, Throwable throwable) {
285         parentContext.log(message, throwable);
286     }
287 
288     @Override
289     public void removeAttribute(String name) {
290         parentContext.removeAttribute(name);
291     }
292 
293     @Override
294     public void setAttribute(String name, Object object) {
295         parentContext.setAttribute(name, object);
296     }
297 }