1   /**
2    * Copyright (c) 2000-2008 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.servlet.filters.velocity;
24  
25  import com.liferay.portal.kernel.log.Log;
26  import com.liferay.portal.kernel.log.LogFactoryUtil;
27  import com.liferay.portal.kernel.servlet.BaseFilter;
28  import com.liferay.portal.kernel.servlet.BrowserSniffer;
29  import com.liferay.portal.kernel.util.GetterUtil;
30  import com.liferay.portal.kernel.util.LocaleUtil;
31  import com.liferay.portal.kernel.util.ParamUtil;
32  import com.liferay.portal.model.ColorScheme;
33  import com.liferay.portal.model.Company;
34  import com.liferay.portal.model.Theme;
35  import com.liferay.portal.service.CompanyLocalServiceUtil;
36  import com.liferay.portal.service.impl.ThemeLocalUtil;
37  import com.liferay.portal.theme.ThemeDisplay;
38  import com.liferay.portal.theme.ThemeDisplayFactory;
39  import com.liferay.portal.util.PortalUtil;
40  import com.liferay.portal.util.WebKeys;
41  import com.liferay.portal.velocity.VelocityVariables;
42  import com.liferay.util.Http;
43  import com.liferay.util.SystemProperties;
44  import com.liferay.util.servlet.filters.CacheResponse;
45  import com.liferay.util.servlet.filters.CacheResponseData;
46  import com.liferay.util.servlet.filters.CacheResponseUtil;
47  
48  import java.io.IOException;
49  import java.io.StringReader;
50  import java.io.StringWriter;
51  
52  import java.util.Locale;
53  import java.util.regex.Matcher;
54  import java.util.regex.Pattern;
55  
56  import javax.servlet.FilterChain;
57  import javax.servlet.FilterConfig;
58  import javax.servlet.ServletException;
59  import javax.servlet.ServletRequest;
60  import javax.servlet.ServletResponse;
61  import javax.servlet.http.HttpServletRequest;
62  import javax.servlet.http.HttpServletResponse;
63  
64  import org.apache.velocity.VelocityContext;
65  import org.apache.velocity.app.Velocity;
66  
67  /**
68   * <a href="VelocityFilter.java.html"><b><i>View Source</i></b></a>
69   *
70   * @author Brian Wing Shun Chan
71   * @author Raymond Augé
72   *
73   */
74  public class VelocityFilter extends BaseFilter {
75  
76      public static final boolean USE_FILTER = GetterUtil.getBoolean(
77          SystemProperties.get(VelocityFilter.class.getName()), true);
78  
79      public static final String ENCODING = GetterUtil.getString(
80          SystemProperties.get("file.encoding"), "UTF-8");
81  
82      public void init(FilterConfig config) throws ServletException {
83          super.init(config);
84  
85          String pattern = config.getInitParameter("pattern");
86  
87          _pattern = Pattern.compile(pattern);
88      }
89  
90      public void doFilter(
91              ServletRequest req, ServletResponse res, FilterChain chain)
92          throws IOException, ServletException {
93  
94          if (_log.isDebugEnabled()) {
95              if (USE_FILTER) {
96                  _log.debug("Velocity is enabled");
97              }
98              else {
99                  _log.debug("Velocity is disabled");
100             }
101         }
102 
103         HttpServletRequest httpReq = (HttpServletRequest)req;
104         HttpServletResponse httpRes = (HttpServletResponse)res;
105 
106         String completeURL = Http.getCompleteURL(httpReq);
107 
108         if (USE_FILTER && isMatchingURL(completeURL)) {
109             if (_log.isDebugEnabled()) {
110                 _log.debug("Processing " + completeURL);
111             }
112 
113             CacheResponse cacheResponse = new CacheResponse(
114                 httpRes, ENCODING);
115 
116             doFilter(VelocityFilter.class, req, cacheResponse, chain);
117 
118             VelocityContext context = new VelocityContext();
119 
120             StringReader reader = new StringReader(
121                 new String(cacheResponse.getData()));
122             StringWriter writer = new StringWriter();
123 
124             ThemeDisplay themeDisplay = null;
125 
126             try {
127 
128                 // Company
129 
130                 long companyId = ParamUtil.getLong(req, "companyId");
131 
132                 Company company = CompanyLocalServiceUtil.getCompanyById(
133                     companyId);
134 
135                 // Paths
136 
137                 String contextPath = PortalUtil.getPathContext();
138 
139                 // Locale
140 
141                 String languageId = ParamUtil.getString(req, "languageId");
142 
143                 Locale locale = LocaleUtil.fromLanguageId(languageId);
144 
145                 // Theme and color scheme
146 
147                 String themeId = ParamUtil.getString(req, "themeId");
148                 String colorSchemeId = ParamUtil.getString(
149                     req, "colorSchemeId");
150 
151                 boolean wapTheme = BrowserSniffer.is_wap_xhtml(httpReq);
152 
153                 Theme theme = ThemeLocalUtil.getTheme(
154                     companyId, themeId, wapTheme);
155                 ColorScheme colorScheme = ThemeLocalUtil.getColorScheme(
156                     companyId, theme.getThemeId(), colorSchemeId, wapTheme);
157 
158                 // Theme display
159 
160                 themeDisplay = ThemeDisplayFactory.create();
161 
162                 themeDisplay.setCompany(company);
163                 themeDisplay.setLocale(locale);
164                 themeDisplay.setLookAndFeel(contextPath, theme, colorScheme);
165                 themeDisplay.setPathContext(contextPath);
166 
167                 req.setAttribute(WebKeys.THEME_DISPLAY, themeDisplay);
168 
169                 // Velocity variables
170 
171                 VelocityVariables.insertVariables(context, httpReq);
172 
173                 // Evaluate template
174 
175                 Velocity.evaluate(
176                     context, writer, VelocityFilter.class.getName(), reader);
177             }
178             catch (Exception e) {
179                 _log.error(e, e);
180             }
181             finally {
182                 try {
183                     if (themeDisplay != null) {
184                         ThemeDisplayFactory.recycle(themeDisplay);
185                     }
186                 }
187                 catch (Exception e) {
188                 }
189             }
190 
191             CacheResponseData data = new CacheResponseData(
192                 writer.toString().getBytes(ENCODING),
193                 cacheResponse.getContentType(), cacheResponse.getHeaders());
194 
195             CacheResponseUtil.write(httpRes, data);
196         }
197         else {
198             if (_log.isDebugEnabled()) {
199                 _log.debug("Not processing " + completeURL);
200             }
201 
202             doFilter(VelocityFilter.class, req, res, chain);
203         }
204     }
205 
206     protected boolean isMatchingURL(String completeURL) {
207         Matcher matcher = _pattern.matcher(completeURL);
208 
209         return matcher.matches();
210     }
211 
212     private static Log _log = LogFactoryUtil.getLog(VelocityFilter.class);
213 
214     private Pattern _pattern;
215 
216 }