1   /**
2    * Copyright (c) 2000-2009 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.util.portlet;
24  
25  import com.liferay.portal.kernel.log.Log;
26  import com.liferay.portal.kernel.log.LogFactoryUtil;
27  import com.liferay.portal.kernel.portlet.LiferayWindowState;
28  import com.liferay.portal.kernel.util.HttpUtil;
29  import com.liferay.portal.kernel.util.StringPool;
30  import com.liferay.portal.kernel.util.Validator;
31  import com.liferay.portal.kernel.util.WebKeys;
32  import com.liferay.portal.kernel.xml.Document;
33  import com.liferay.portal.kernel.xml.Element;
34  import com.liferay.portal.kernel.xml.SAXReaderUtil;
35  import com.liferay.portal.theme.PortletDisplay;
36  import com.liferay.portal.theme.ThemeDisplay;
37  import com.liferay.util.xml.DocUtil;
38  
39  import java.io.ByteArrayOutputStream;
40  import java.io.IOException;
41  import java.io.InputStream;
42  
43  import java.util.Collection;
44  import java.util.Enumeration;
45  import java.util.List;
46  import java.util.Map;
47  
48  import javax.portlet.ActionRequest;
49  import javax.portlet.MimeResponse;
50  import javax.portlet.PortletRequest;
51  import javax.portlet.PortletResponse;
52  import javax.portlet.PortletSession;
53  import javax.portlet.PortletURL;
54  import javax.portlet.RenderRequest;
55  import javax.portlet.ResourceRequest;
56  import javax.portlet.ResourceURL;
57  import javax.portlet.WindowStateException;
58  
59  import org.apache.commons.fileupload.disk.DiskFileItem;
60  import org.apache.commons.fileupload.disk.DiskFileItemFactory;
61  import org.apache.commons.fileupload.portlet.PortletFileUpload;
62  
63  /**
64   * <a href="PortletRequestUtil.java.html"><b><i>View Source</i></b></a>
65   *
66   * @author Brian Wing Shun Chan
67   * @author Raymond Augé
68   *
69   */
70  public class PortletRequestUtil {
71  
72      public static List<DiskFileItem> testMultipartWithCommonsFileUpload(
73              ActionRequest actionRequest)
74          throws Exception {
75  
76          // Check if the given request is a multipart request
77  
78          boolean multiPartContent = PortletFileUpload.isMultipartContent(
79              actionRequest);
80  
81          if (multiPartContent) {
82              _log.info("The given request is a multipart request");
83          }
84          else {
85              _log.info("The given request is NOT a multipart request");
86          }
87  
88          // Check for the number of file items
89  
90          DiskFileItemFactory factory = new DiskFileItemFactory();
91  
92          PortletFileUpload upload = new PortletFileUpload(factory);
93  
94          List<DiskFileItem> fileItems = upload.parseRequest(actionRequest);
95  
96          if (_log.isInfoEnabled()) {
97              _log.info(
98                  "Apache commons upload was able to parse " + fileItems.size() +
99                      " items");
100         }
101 
102         for (int i = 0; i < fileItems.size(); i++) {
103             DiskFileItem fileItem = fileItems.get(i);
104 
105             if (_log.isInfoEnabled()) {
106                 _log.info("Item " + i + " " + fileItem);
107             }
108         }
109 
110         return fileItems;
111     }
112 
113     public static int testMultipartWithPortletInputStream(
114             ActionRequest actionRequest)
115         throws Exception {
116 
117         // Read directly from the portlet input stream
118 
119         InputStream is = actionRequest.getPortletInputStream();
120 
121         if (is != null) {
122             ByteArrayOutputStream baos = new ByteArrayOutputStream();
123 
124             int c = -1;
125 
126             try {
127                 while ((c = is.read()) != -1) {
128                     baos.write(c);
129                 }
130             }
131             finally {
132                 is.close();
133             }
134 
135             byte[] bytes = baos.toByteArray();
136 
137             if (_log.isInfoEnabled()) {
138                 _log.info(
139                     "Byte array size from the raw input stream is " +
140                         bytes.length);
141             }
142 
143             return bytes.length;
144         }
145 
146         return -1;
147     }
148 
149     public static String toXML(
150         PortletRequest portletRequest, PortletResponse portletResponse) {
151 
152         String xml = null;
153 
154         Document doc = SAXReaderUtil.createDocument();
155 
156         Element reqEl = doc.addElement("request");
157 
158         DocUtil.add(reqEl, "container-type", "portlet");
159         DocUtil.add(
160             reqEl, "container-namespace", portletRequest.getContextPath());
161         DocUtil.add(
162             reqEl, "content-type", portletRequest.getResponseContentType());
163         DocUtil.add(reqEl, "server-name", portletRequest.getServerName());
164         DocUtil.add(reqEl, "server-port", portletRequest.getServerPort());
165         DocUtil.add(reqEl, "secure", portletRequest.isSecure());
166         DocUtil.add(reqEl, "auth-type", portletRequest.getAuthType());
167         DocUtil.add(reqEl, "remote-user", portletRequest.getRemoteUser());
168         DocUtil.add(reqEl, "context-path", portletRequest.getContextPath());
169         DocUtil.add(reqEl, "locale", portletRequest.getLocale());
170         DocUtil.add(reqEl, "portlet-mode", portletRequest.getPortletMode());
171         DocUtil.add(
172             reqEl, "portlet-session-id",
173             portletRequest.getRequestedSessionId());
174         DocUtil.add(reqEl, "scheme", portletRequest.getScheme());
175         DocUtil.add(reqEl, "window-state", portletRequest.getWindowState());
176 
177         if (portletRequest instanceof ActionRequest) {
178             DocUtil.add(reqEl, "lifecycle", RenderRequest.ACTION_PHASE);
179         }
180         else if (portletRequest instanceof RenderRequest) {
181             DocUtil.add(reqEl, "lifecycle", RenderRequest.RENDER_PHASE);
182         }
183         else if (portletRequest instanceof ResourceRequest) {
184             DocUtil.add(reqEl, "lifecycle", RenderRequest.RESOURCE_PHASE);
185         }
186 
187         if (portletResponse instanceof MimeResponse) {
188             _mimeResponseToXML((MimeResponse)portletResponse, reqEl);
189         }
190 
191         ThemeDisplay themeDisplay = (ThemeDisplay)portletRequest.getAttribute(
192             WebKeys.THEME_DISPLAY);
193 
194         if (themeDisplay != null) {
195             Element themeDisplayEl = reqEl.addElement("theme-display");
196 
197             _themeDisplayToXML(themeDisplay, themeDisplayEl);
198         }
199 
200         Element parametersEl = reqEl.addElement("parameters");
201 
202         Enumeration<String> enu = portletRequest.getParameterNames();
203 
204         while (enu.hasMoreElements()) {
205             String name = enu.nextElement();
206 
207             Element parameterEl = parametersEl.addElement("parameter");
208 
209             DocUtil.add(parameterEl, "name", name);
210 
211             String[] values = portletRequest.getParameterValues(name);
212 
213             for (int i = 0; i < values.length; i++) {
214                 DocUtil.add(parameterEl, "value", values[i]);
215             }
216         }
217 
218         Element attributesEl = reqEl.addElement("attributes");
219 
220         enu = portletRequest.getAttributeNames();
221 
222         while (enu.hasMoreElements()) {
223             String name = enu.nextElement();
224 
225             if (!_isValidAttributeName(name)) {
226                 continue;
227             }
228 
229             Object value = portletRequest.getAttribute(name);
230 
231             if (!_isValidAttributeValue(value)) {
232                 continue;
233             }
234 
235             Element attributeEl = attributesEl.addElement("attribute");
236 
237             DocUtil.add(attributeEl, "name", name);
238             DocUtil.add(attributeEl, "value", String.valueOf(value));
239         }
240 
241         Element portletSessionEl = reqEl.addElement("portlet-session");
242 
243         attributesEl = portletSessionEl.addElement("portlet-attributes");
244 
245         PortletSession portletSession = portletRequest.getPortletSession();
246 
247         try {
248             enu = portletSession.getAttributeNames(
249                 PortletSession.PORTLET_SCOPE);
250 
251             while (enu.hasMoreElements()) {
252                 String name = enu.nextElement();
253 
254                 if (!_isValidAttributeName(name)) {
255                     continue;
256                 }
257 
258                 Object value = portletSession.getAttribute(
259                     name, PortletSession.PORTLET_SCOPE);
260 
261                 if (!_isValidAttributeValue(value)) {
262                     continue;
263                 }
264 
265                 Element attributeEl = attributesEl.addElement("attribute");
266 
267                 DocUtil.add(attributeEl, "name", name);
268                 DocUtil.add(attributeEl, "value", String.valueOf(value));
269             }
270 
271             attributesEl = portletSessionEl.addElement(
272                 "application-attributes");
273 
274             enu = portletSession.getAttributeNames(
275                 PortletSession.APPLICATION_SCOPE);
276 
277             while (enu.hasMoreElements()) {
278                 String name = enu.nextElement();
279 
280                 if (!_isValidAttributeName(name)) {
281                     continue;
282                 }
283 
284                 Object value = portletSession.getAttribute(
285                     name, PortletSession.APPLICATION_SCOPE);
286 
287                 if (!_isValidAttributeValue(value)) {
288                     continue;
289                 }
290 
291                 Element attributeEl = attributesEl.addElement("attribute");
292 
293                 DocUtil.add(attributeEl, "name", name);
294                 DocUtil.add(attributeEl, "value", String.valueOf(value));
295             }
296         }
297         catch (IllegalStateException ise) {
298         }
299 
300         try {
301             xml = doc.formattedString();
302         }
303         catch (IOException ioe) {
304         }
305 
306         return xml;
307     }
308 
309     private static void _mimeResponseToXML(
310         MimeResponse mimeResponse, Element reqEl) {
311 
312         String namespace = mimeResponse.getNamespace();
313 
314         DocUtil.add(reqEl, "portlet-namespace", namespace);
315 
316         PortletURL actionUrl = mimeResponse.createActionURL();
317 
318         DocUtil.add(reqEl, "action-url", actionUrl);
319 
320         PortletURL renderUrl = mimeResponse.createRenderURL();
321 
322         DocUtil.add(reqEl, "render-url", renderUrl);
323 
324         try {
325             renderUrl.setWindowState(LiferayWindowState.EXCLUSIVE);
326 
327             DocUtil.add(reqEl, "render-url-exclusive", renderUrl);
328         }
329         catch (WindowStateException wse) {
330         }
331 
332         try {
333             renderUrl.setWindowState(LiferayWindowState.MAXIMIZED);
334 
335             DocUtil.add(reqEl, "render-url-maximized", renderUrl);
336         }
337         catch (WindowStateException wse) {
338         }
339 
340         try {
341             renderUrl.setWindowState(LiferayWindowState.MINIMIZED);
342 
343             DocUtil.add(reqEl, "render-url-minimized", renderUrl);
344         }
345         catch (WindowStateException wse) {
346         }
347 
348         try {
349             renderUrl.setWindowState(LiferayWindowState.NORMAL);
350 
351             DocUtil.add(reqEl, "render-url-normal", renderUrl);
352         }
353         catch (WindowStateException wse) {
354         }
355 
356         try {
357             renderUrl.setWindowState(LiferayWindowState.POP_UP);
358 
359             DocUtil.add(reqEl, "render-url-pop-up", renderUrl);
360         }
361         catch (WindowStateException wse) {
362         }
363 
364         ResourceURL resourceURL = mimeResponse.createResourceURL();
365 
366         String resourceURLString = HttpUtil.removeParameter(
367             resourceURL.toString(), namespace + "struts_action");
368 
369         resourceURLString = HttpUtil.removeParameter(
370             resourceURLString, namespace + "redirect");
371 
372         DocUtil.add(reqEl, "resource-url", resourceURLString);
373     }
374 
375     private static void _themeDisplayToXML(
376         ThemeDisplay themeDisplay, Element themeDisplayEl) {
377 
378         DocUtil.add(themeDisplayEl, "cdn-host", themeDisplay.getCDNHost());
379         DocUtil.add(themeDisplayEl, "company-id", themeDisplay.getCompanyId());
380         DocUtil.add(
381             themeDisplayEl, "do-as-user-id", themeDisplay.getDoAsUserId());
382         DocUtil.add(
383             themeDisplayEl, "i18n-language-id",
384             themeDisplay.getI18nLanguageId());
385         DocUtil.add(
386             themeDisplayEl, "language-id", themeDisplay.getLanguageId());
387         DocUtil.add(themeDisplayEl, "locale", themeDisplay.getLocale());
388         DocUtil.add(
389             themeDisplayEl, "path-context", themeDisplay.getPathContext());
390         DocUtil.add(
391             themeDisplayEl, "path-friendly-url-private-group",
392             themeDisplay.getPathFriendlyURLPrivateGroup());
393         DocUtil.add(
394             themeDisplayEl, "path-friendly-url-private-user",
395             themeDisplay.getPathFriendlyURLPrivateUser());
396         DocUtil.add(
397             themeDisplayEl, "path-friendly-url-public",
398             themeDisplay.getPathFriendlyURLPublic());
399         DocUtil.add(themeDisplayEl, "path-image", themeDisplay.getPathImage());
400         DocUtil.add(themeDisplayEl, "path-main", themeDisplay.getPathMain());
401         DocUtil.add(
402             themeDisplayEl, "path-theme-images",
403             themeDisplay.getPathThemeImages());
404         DocUtil.add(themeDisplayEl, "plid", themeDisplay.getPlid());
405         DocUtil.add(
406             themeDisplayEl, "portal-url",
407             HttpUtil.removeProtocol(themeDisplay.getPortalURL()));
408         DocUtil.add(
409             themeDisplayEl, "real-user-id", themeDisplay.getRealUserId());
410         DocUtil.add(
411             themeDisplayEl, "scope-group-id", themeDisplay.getScopeGroupId());
412         DocUtil.add(themeDisplayEl, "secure", themeDisplay.isSecure());
413         DocUtil.add(
414             themeDisplayEl, "server-name", themeDisplay.getServerName());
415         DocUtil.add(
416             themeDisplayEl, "server-port", themeDisplay.getServerPort());
417         DocUtil.add(
418             themeDisplayEl, "time-zone", themeDisplay.getTimeZone().getID());
419         DocUtil.add(
420             themeDisplayEl, "url-portal",
421             HttpUtil.removeProtocol(themeDisplay.getURLPortal()));
422         DocUtil.add(themeDisplayEl, "user-id", themeDisplay.getUserId());
423 
424         if (themeDisplay.getPortletDisplay() != null) {
425             Element portletDisplayEl = themeDisplayEl.addElement(
426                 "portlet-display");
427 
428             _portletDisplayToXML(
429                 themeDisplay.getPortletDisplay(), portletDisplayEl);
430         }
431     }
432 
433     private static boolean _isValidAttributeName(String name) {
434         if (name.equalsIgnoreCase("j_password") ||
435             name.equalsIgnoreCase("LAYOUT_CONTENT") ||
436             name.equalsIgnoreCase("LAYOUTS") ||
437             name.equalsIgnoreCase("PORTLET_RENDER_PARAMETERS") ||
438             name.equalsIgnoreCase("USER_PASSWORD") ||
439             name.startsWith("javax.") ||
440             name.startsWith("liferay-ui:")) {
441 
442             return false;
443         }
444         else {
445             return true;
446         }
447     }
448 
449     private static boolean _isValidAttributeValue(Object obj) {
450         if (obj == null) {
451             return false;
452         }
453         else if (obj instanceof Collection) {
454             Collection<?> col = (Collection<?>)obj;
455 
456             if (col.size() == 0) {
457                 return false;
458             }
459             else {
460                 return true;
461             }
462         }
463         else if (obj instanceof Map) {
464             Map<?, ?> map = (Map<?, ?>)obj;
465 
466             if (map.size() == 0) {
467                 return false;
468             }
469             else {
470                 return true;
471             }
472         }
473         else {
474             String objString = String.valueOf(obj);
475 
476             if (Validator.isNull(objString)) {
477                 return false;
478             }
479 
480             String hashCode =
481                 StringPool.AT + Integer.toHexString(obj.hashCode());
482 
483             if (objString.endsWith(hashCode)) {
484                 return false;
485             }
486 
487             return true;
488         }
489     }
490 
491     private static void _portletDisplayToXML(
492         PortletDisplay portletDisplay, Element portletDisplayEl) {
493 
494         DocUtil.add(portletDisplayEl, "id", portletDisplay.getId());
495         DocUtil.add(
496             portletDisplayEl, "instance-id", portletDisplay.getInstanceId());
497         DocUtil.add(
498             portletDisplayEl, "portlet-name", portletDisplay.getPortletName());
499         DocUtil.add(
500             portletDisplayEl, "resource-pk", portletDisplay.getResourcePK());
501         DocUtil.add(
502             portletDisplayEl, "root-portlet-id",
503             portletDisplay.getRootPortletId());
504         DocUtil.add(
505             portletDisplayEl, "title", portletDisplay.getTitle());
506     }
507 
508     private static Log _log = LogFactoryUtil.getLog(PortletRequestUtil.class);
509 
510 }