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.portlet.layoutconfiguration.util;
24  
25  import com.liferay.portal.kernel.servlet.StringServletResponse;
26  import com.liferay.portal.kernel.util.JavaConstants;
27  import com.liferay.portal.kernel.util.MethodInvoker;
28  import com.liferay.portal.kernel.util.MethodWrapper;
29  import com.liferay.portal.kernel.util.StringPool;
30  import com.liferay.portal.kernel.util.StringUtil;
31  import com.liferay.portal.kernel.util.Validator;
32  import com.liferay.portal.model.Portlet;
33  import com.liferay.portal.service.PortletLocalServiceUtil;
34  import com.liferay.portal.theme.PortletDisplay;
35  import com.liferay.portal.theme.PortletDisplayFactory;
36  import com.liferay.portal.theme.ThemeDisplay;
37  import com.liferay.portal.util.PortalUtil;
38  import com.liferay.portal.util.WebKeys;
39  import com.liferay.portal.velocity.VelocityVariables;
40  import com.liferay.portlet.layoutconfiguration.util.velocity.TemplateProcessor;
41  import com.liferay.portlet.layoutconfiguration.util.xml.RuntimeLogic;
42  
43  import java.io.StringWriter;
44  
45  import java.util.Iterator;
46  import java.util.Map;
47  
48  import javax.portlet.PortletConfig;
49  import javax.portlet.RenderRequest;
50  import javax.portlet.RenderResponse;
51  
52  import javax.servlet.ServletContext;
53  import javax.servlet.http.HttpServletRequest;
54  import javax.servlet.http.HttpServletResponse;
55  import javax.servlet.jsp.PageContext;
56  
57  import org.apache.commons.logging.Log;
58  import org.apache.commons.logging.LogFactory;
59  import org.apache.velocity.VelocityContext;
60  import org.apache.velocity.app.Velocity;
61  
62  /**
63   * <a href="RuntimePortletUtil.java.html"><b><i>View Source</i></b></a>
64   *
65   * @author Brian Wing Shun Chan
66   * @author Raymond Aug�
67   *
68   */
69  public class RuntimePortletUtil {
70  
71      public static void processPortlet(
72              StringBuilder sb, ServletContext servletContext,
73              HttpServletRequest request, HttpServletResponse response,
74              RenderRequest renderRequest, RenderResponse renderResponse,
75              String portletId, String queryString)
76          throws Exception {
77  
78          processPortlet(
79              sb, servletContext, request, response, renderRequest,
80              renderResponse, portletId, queryString, null, null, null);
81      }
82  
83      public static void processPortlet(
84              StringBuilder sb, ServletContext servletContext,
85              HttpServletRequest request, HttpServletResponse response,
86              RenderRequest renderRequest, RenderResponse renderResponse,
87              String portletId, String queryString, String columnId,
88              Integer columnPos, Integer columnCount)
89          throws Exception {
90  
91          processPortlet(
92              sb, servletContext, request, response, renderRequest,
93              renderResponse, null, portletId, queryString, columnId, columnPos,
94              columnCount, null);
95      }
96  
97      public static void processPortlet(
98              StringBuilder sb, ServletContext servletContext,
99              HttpServletRequest request, HttpServletResponse response,
100             Portlet portlet, String queryString, String columnId,
101             Integer columnPos, Integer columnCount, String path)
102         throws Exception {
103 
104         processPortlet(
105             sb, servletContext, request, response, null, null, portlet,
106             portlet.getPortletId(), queryString, columnId, columnPos,
107             columnCount, path);
108     }
109 
110     public static void processPortlet(
111             StringBuilder sb, ServletContext servletContext,
112             HttpServletRequest request, HttpServletResponse response,
113             RenderRequest renderRequest, RenderResponse renderResponse,
114             Portlet portlet, String portletId, String queryString,
115             String columnId, Integer columnPos, Integer columnCount,
116             String path)
117         throws Exception {
118 
119         ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(
120             WebKeys.THEME_DISPLAY);
121 
122         if (portlet == null) {
123             portlet = PortletLocalServiceUtil.getPortletById(
124                 themeDisplay.getCompanyId(), portletId);
125         }
126 
127         if ((portlet != null) && (portlet.isInstanceable()) &&
128             (!portlet.isAddDefaultResource())) {
129 
130             String instanceId = portlet.getInstanceId();
131 
132             if (Validator.isNotNull(instanceId) &&
133                 Validator.isPassword(instanceId) &&
134                 (instanceId.length() == 4)) {
135 
136                 /*portletId +=
137                     PortletConstants.INSTANCE_SEPARATOR + instanceId;
138 
139                 portlet = PortletLocalServiceUtil.getPortletById(
140                     themeDisplay.getCompanyId(), portletId);*/
141             }
142             else {
143                 if (_log.isDebugEnabled()) {
144                     _log.debug(
145                         "Portlet " + portlet.getPortletId() +
146                             " is instanceable but does not have a " +
147                                 "valid instance id");
148                 }
149 
150                 portlet = null;
151             }
152         }
153 
154         if (portlet == null) {
155             return;
156         }
157 
158         // Capture the current portlet's settings to reset them once the child
159         // portlet is rendered
160 
161         PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();
162 
163         PortletDisplay portletDisplayClone = PortletDisplayFactory.create();
164 
165         portletDisplay.copyTo(portletDisplayClone);
166 
167         PortletConfig portletConfig = (PortletConfig)request.getAttribute(
168             JavaConstants.JAVAX_PORTLET_CONFIG);
169 
170         try {
171             PortalUtil.renderPortlet(
172                 sb, servletContext, request, response, portlet, queryString,
173                 columnId, columnPos, columnCount, path);
174         }
175         finally {
176             portletDisplay.copyFrom(portletDisplayClone);
177 
178             try {
179                 PortletDisplayFactory.recycle(portletDisplayClone);
180             }
181             catch (Exception e) {
182                 _log.error(e);
183             }
184 
185             _defineObjects(
186                 request, portletConfig, renderRequest, renderResponse);
187         }
188     }
189 
190     public static String processTemplate(
191             ServletContext servletContext, HttpServletRequest request,
192             HttpServletResponse response, PageContext pageContext,
193             String content)
194         throws Exception {
195 
196         return processTemplate(
197             servletContext, request, response, pageContext, null, content);
198     }
199 
200     public static String processTemplate(
201             ServletContext servletContext, HttpServletRequest request,
202             HttpServletResponse response, PageContext pageContext,
203             String portletId, String content)
204         throws Exception {
205 
206         if (Validator.isNull(content)) {
207             return StringPool.BLANK;
208         }
209 
210         TemplateProcessor processor = new TemplateProcessor(
211             servletContext, request, response, portletId);
212 
213         VelocityContext velocityContext = null;
214 
215         // LEP-6865
216 
217         if (_innerVelocityContext == null) {
218             velocityContext = new VelocityContext();
219 
220             _innerVelocityContext = velocityContext;
221         }
222         else {
223             velocityContext = new VelocityContext(_innerVelocityContext);
224         }
225 
226         velocityContext.put("processor", processor);
227 
228         // Velocity variables
229 
230         VelocityVariables.insertVariables(velocityContext, request);
231 
232         // liferay:include tag library
233 
234         StringServletResponse stringResponse = new StringServletResponse(
235             response);
236 
237         MethodWrapper methodWrapper = new MethodWrapper(
238             "com.liferay.taglib.util.VelocityTaglib", "init",
239             new Object[] {
240                 servletContext, request, stringResponse, pageContext
241             });
242 
243         Object velocityTaglib = MethodInvoker.invoke(methodWrapper);
244 
245         velocityContext.put("taglibLiferay", velocityTaglib);
246         velocityContext.put("theme", velocityTaglib);
247 
248         StringWriter sw = new StringWriter();
249 
250         try {
251             Velocity.evaluate(
252                 velocityContext, sw, RuntimePortletUtil.class.getName(),
253                 content);
254         }
255         catch (Exception e) {
256             _log.error(e, e);
257 
258             throw e;
259         }
260 
261         String output = sw.toString();
262 
263         Map<String, String> columnsMap = processor.getColumnsMap();
264 
265         Iterator<Map.Entry<String, String>> columnsMapItr =
266             columnsMap.entrySet().iterator();
267 
268         while (columnsMapItr.hasNext()) {
269             Map.Entry<String, String> entry = columnsMapItr.next();
270 
271             String key = entry.getKey();
272             String value = entry.getValue();
273 
274             output = StringUtil.replace(output, key, value);
275         }
276 
277         Map<Portlet, Object[]> portletsMap = processor.getPortletsMap();
278 
279         Iterator<Map.Entry<Portlet, Object[]>> portletsMapItr =
280             portletsMap.entrySet().iterator();
281 
282         while (portletsMapItr.hasNext()) {
283             Map.Entry<Portlet, Object[]> entry = portletsMapItr.next();
284 
285             Portlet portlet = entry.getKey();
286             Object[] value = entry.getValue();
287 
288             String queryString = (String)value[0];
289             String columnId = (String)value[1];
290             Integer columnPos = (Integer)value[2];
291             Integer columnCount = (Integer)value[3];
292 
293             StringBuilder sb = new StringBuilder();
294 
295             processPortlet(
296                 sb, servletContext, request, response, portlet, queryString,
297                 columnId, columnPos, columnCount, null);
298 
299             output = StringUtil.replace(
300                 output, "[$TEMPLATE_PORTLET_" + portlet.getPortletId() + "$]",
301                 sb.toString());
302         }
303 
304         return output;
305     }
306 
307     public static String processXML(
308             HttpServletRequest request, String content,
309             RuntimeLogic runtimeLogic)
310         throws Exception {
311 
312         if (Validator.isNull(content)) {
313             return StringPool.BLANK;
314         }
315 
316         try {
317             request.setAttribute(WebKeys.RENDER_PORTLET_RESOURCE, Boolean.TRUE);
318 
319             StringBuilder sb = new StringBuilder();
320 
321             int x = 0;
322             int y = content.indexOf(runtimeLogic.getOpenTag());
323 
324             while (y != -1) {
325                 sb.append(content.substring(x, y));
326 
327                 int close1 = content.indexOf(runtimeLogic.getClose1Tag(), y);
328                 int close2 = content.indexOf(runtimeLogic.getClose2Tag(), y);
329 
330                 if ((close2 == -1) || ((close1 != -1) && (close1 < close2))) {
331                     x = close1 + runtimeLogic.getClose1Tag().length();
332                 }
333                 else {
334                     x = close2 + runtimeLogic.getClose2Tag().length();
335                 }
336 
337                 runtimeLogic.processXML(sb, content.substring(y, x));
338 
339                 y = content.indexOf(runtimeLogic.getOpenTag(), x);
340             }
341 
342             if (y == -1) {
343                 sb.append(content.substring(x, content.length()));
344             }
345 
346             return sb.toString();
347         }
348         finally {
349             request.removeAttribute(WebKeys.RENDER_PORTLET_RESOURCE);
350         }
351     }
352 
353     private static void _defineObjects(
354         HttpServletRequest request, PortletConfig portletConfig,
355         RenderRequest renderRequest, RenderResponse renderResponse) {
356 
357         if (portletConfig != null) {
358             request.setAttribute(
359                 JavaConstants.JAVAX_PORTLET_CONFIG, portletConfig);
360         }
361 
362         if (renderRequest != null) {
363             request.setAttribute(
364                 JavaConstants.JAVAX_PORTLET_REQUEST, renderRequest);
365         }
366 
367         if (renderResponse != null) {
368             request.setAttribute(
369                 JavaConstants.JAVAX_PORTLET_RESPONSE, renderResponse);
370         }
371     }
372 
373     private static Log _log = LogFactory.getLog(RuntimePortletUtil.class);
374 
375     private static VelocityContext _innerVelocityContext;
376 
377 }