View Javadoc
1   /**
2    * This file Copyright (c) 2003-2018 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  import info.magnolia.servlet.ServletContextWrapper;
38  
39  import java.beans.PropertyDescriptor;
40  import java.io.File;
41  import java.io.FileInputStream;
42  import java.io.FileNotFoundException;
43  import java.io.InputStream;
44  import java.net.MalformedURLException;
45  import java.net.URL;
46  import java.net.URLClassLoader;
47  import java.util.HashSet;
48  import java.util.Set;
49  
50  import javax.servlet.ServletContext;
51  
52  import org.apache.commons.io.FileUtils;
53  import org.apache.commons.lang3.StringUtils;
54  import org.slf4j.Logger;
55  import org.slf4j.LoggerFactory;
56  
57  
58  /**
59   * Wraps the servlet context especially for freemarker taglib resolution. This will trick freemarker TaglibFactory class
60   * to "see" all jars in classpath as if they were jars in /WEB-INF/lib.
61   *
62   * On Windows systems the implementation of getResourcePaths will return absolute paths including the drive letter. When
63   * freemarker then calls getResource and getResourceAsStream we must not call the wrapped servlet context because its
64   * not a valid URL and it will fail with a MalformedURLException. See MAGNOLIA-5651.
65   */
66  public class FreemarkerServletContextWrapper extends ServletContextWrapper {
67  
68      private final ServletContext parentContext;
69  
70      private static Logger log = LoggerFactory.getLogger(FreemarkerServletContextWrapper.class);
71  
72      public FreemarkerServletContextWrapper(ServletContext parentServletContext) {
73          super(parentServletContext);
74          // allow also a null parent context for unit tests
75          this.parentContext = parentServletContext;
76      }
77  
78      @Override
79      public URL getResource(String path) throws MalformedURLException {
80  
81          URL result = null;
82          if (path.startsWith("/")) {
83              result = parentContext.getResource(path);
84          }
85          if (result == null) {
86              // Trying the absolute path if the parent context fails.
87              File file = new File(path);
88              if ((file.exists()) && (file.isFile())) {
89                  result = file.toURI().toURL();
90              }
91          }
92          return result;
93      }
94  
95      @Override
96      public InputStream getResourceAsStream(String path) {
97  
98          InputStream is = null;
99          if (path.startsWith("/")) {
100             is = parentContext.getResourceAsStream(path);
101         }
102         if (is == null) {
103             // Trying the absolute path if the parent context fails.
104             File file = new File(path);
105             if ((file.exists()) && (file.isFile())) {
106                 try {
107                     return new FileInputStream(file);
108                 } catch (FileNotFoundException e) {
109                     // Ignore, file not found
110                 }
111             }
112         }
113         return is;
114     }
115 
116     @Override
117     public Set<String> getResourcePaths(String path) {
118         if (StringUtils.equals(path, "/WEB-INF/lib")) {
119             log.debug("returning resources from classpath");
120             // Just when asking libraries, pass the classpath ones.
121             final Set<String> resources = new HashSet<String>();
122             final ClassLoader cl = Thread.currentThread().getContextClassLoader();
123             // if the classloader is an URLClassloader we have a better method for discovering resources
124             // whis will also fetch files from jars outside WEB-INF/lib, useful during development
125             if (cl instanceof URLClassLoader) {
126                 final URLClassLoader urlClassLoader = (URLClassLoader) cl;
127                 final URL[] urls = urlClassLoader.getURLs();
128                 for (int j = 0; j < urls.length; j++) {
129                     final File tofile = ClasspathResourcesUtil.sanitizeToFile(urls[j]);
130                     if (tofile.isDirectory()) {
131                         for (File file : (FileUtils.listFiles(tofile, null, true))) {
132                             resources.add(file.getAbsolutePath());
133                         }
134                     } else {
135                         resources.add(tofile.getAbsolutePath());
136                     }
137                 }
138 
139                 return resources;
140             }
141             try {
142                 // be friendly to WAS developers too...
143                 // in development mode under RAD 7.5 here we have an instance of com.ibm.ws.classloader.WsClassLoader
144                 // and jars are NOT deployed to WEB-INF/lib by default, so they can't be found without this explicit
145                 // check
146                 //
147                 // but since we don't want to depend on WAS stuff we just check if the cl exposes a "classPath" property
148                 PropertyDescriptor pd = new PropertyDescriptor("classPath", cl.getClass());
149                 if (pd != null && pd.getReadMethod() != null) {
150                     String classpath = (String) pd.getReadMethod().invoke(cl);
151                     if (StringUtils.isNotBlank(classpath)) {
152                         String[] paths = StringUtils.split(classpath, File.pathSeparator);
153                         for (int j = 0; j < paths.length; j++) {
154                             final File tofile = new File(paths[j]);
155                             // there can be several missing (optional?) paths here...
156                             if (tofile.exists()) {
157                                 if (tofile.isDirectory()) {
158                                     for (File file : (FileUtils.listFiles(tofile, null, true))) {
159                                         resources.add(file.getAbsolutePath());
160                                     }
161                                 } else {
162                                     resources.add(tofile.getAbsolutePath());
163                                 }
164                             }
165                         }
166                         return resources;
167                     }
168                 }
169             } catch (Throwable e) {
170                 // no, it's not a classloader we can handle in a special way
171             }
172             // no way, we have to assume a standard war structure and look in the WEB-INF/lib and WEB-INF/classes dirs
173             // read the jars in the lib dir
174         }
175         return parentContext.getResourcePaths(path);
176     }
177 }