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             if (_log.isWarnEnabled()) {
299                 _log.warn(ise.getMessage());
300             }
301         }
302 
303         try {
304             xml = doc.formattedString();
305         }
306         catch (IOException ioe) {
307         }
308 
309         return xml;
310     }
311 
312     private static void _mimeResponseToXML(
313         MimeResponse mimeResponse, Element reqEl) {
314 
315         String namespace = mimeResponse.getNamespace();
316 
317         DocUtil.add(reqEl, "portlet-namespace", namespace);
318 
319         try {
320             PortletURL actionUrl = mimeResponse.createActionURL();
321 
322             DocUtil.add(reqEl, "action-url", actionUrl);
323         }
324         catch (IllegalStateException ise) {
325             if (_log.isWarnEnabled()) {
326                 _log.warn(ise.getMessage());
327             }
328         }
329 
330         try {
331             PortletURL renderUrl = mimeResponse.createRenderURL();
332 
333             DocUtil.add(reqEl, "render-url", renderUrl);
334 
335             try {
336                 renderUrl.setWindowState(LiferayWindowState.EXCLUSIVE);
337 
338                 DocUtil.add(reqEl, "render-url-exclusive", renderUrl);
339             }
340             catch (WindowStateException wse) {
341             }
342 
343             try {
344                 renderUrl.setWindowState(LiferayWindowState.MAXIMIZED);
345 
346                 DocUtil.add(reqEl, "render-url-maximized", renderUrl);
347             }
348             catch (WindowStateException wse) {
349             }
350 
351             try {
352                 renderUrl.setWindowState(LiferayWindowState.MINIMIZED);
353 
354                 DocUtil.add(reqEl, "render-url-minimized", renderUrl);
355             }
356             catch (WindowStateException wse) {
357             }
358 
359             try {
360                 renderUrl.setWindowState(LiferayWindowState.NORMAL);
361 
362                 DocUtil.add(reqEl, "render-url-normal", renderUrl);
363             }
364             catch (WindowStateException wse) {
365             }
366 
367             try {
368                 renderUrl.setWindowState(LiferayWindowState.POP_UP);
369 
370                 DocUtil.add(reqEl, "render-url-pop-up", renderUrl);
371             }
372             catch (WindowStateException wse) {
373             }
374         }
375         catch (IllegalStateException ise) {
376             if (_log.isWarnEnabled()) {
377                 _log.warn(ise.getMessage());
378             }
379         }
380 
381         ResourceURL resourceURL = mimeResponse.createResourceURL();
382 
383         String resourceURLString = HttpUtil.removeParameter(
384             resourceURL.toString(), namespace + "struts_action");
385 
386         resourceURLString = HttpUtil.removeParameter(
387             resourceURLString, namespace + "redirect");
388 
389         DocUtil.add(reqEl, "resource-url", resourceURLString);
390     }
391 
392     private static void _themeDisplayToXML(
393         ThemeDisplay themeDisplay, Element themeDisplayEl) {
394 
395         DocUtil.add(themeDisplayEl, "cdn-host", themeDisplay.getCDNHost());
396         DocUtil.add(themeDisplayEl, "company-id", themeDisplay.getCompanyId());
397         DocUtil.add(
398             themeDisplayEl, "do-as-user-id", themeDisplay.getDoAsUserId());
399         DocUtil.add(
400             themeDisplayEl, "i18n-language-id",
401             themeDisplay.getI18nLanguageId());
402         DocUtil.add(
403             themeDisplayEl, "language-id", themeDisplay.getLanguageId());
404         DocUtil.add(themeDisplayEl, "locale", themeDisplay.getLocale());
405         DocUtil.add(
406             themeDisplayEl, "path-context", themeDisplay.getPathContext());
407         DocUtil.add(
408             themeDisplayEl, "path-friendly-url-private-group",
409             themeDisplay.getPathFriendlyURLPrivateGroup());
410         DocUtil.add(
411             themeDisplayEl, "path-friendly-url-private-user",
412             themeDisplay.getPathFriendlyURLPrivateUser());
413         DocUtil.add(
414             themeDisplayEl, "path-friendly-url-public",
415             themeDisplay.getPathFriendlyURLPublic());
416         DocUtil.add(themeDisplayEl, "path-image", themeDisplay.getPathImage());
417         DocUtil.add(themeDisplayEl, "path-main", themeDisplay.getPathMain());
418         DocUtil.add(
419             themeDisplayEl, "path-theme-images",
420             themeDisplay.getPathThemeImages());
421         DocUtil.add(themeDisplayEl, "plid", themeDisplay.getPlid());
422         DocUtil.add(
423             themeDisplayEl, "portal-url",
424             HttpUtil.removeProtocol(themeDisplay.getPortalURL()));
425         DocUtil.add(
426             themeDisplayEl, "real-user-id", themeDisplay.getRealUserId());
427         DocUtil.add(
428             themeDisplayEl, "scope-group-id", themeDisplay.getScopeGroupId());
429         DocUtil.add(themeDisplayEl, "secure", themeDisplay.isSecure());
430         DocUtil.add(
431             themeDisplayEl, "server-name", themeDisplay.getServerName());
432         DocUtil.add(
433             themeDisplayEl, "server-port", themeDisplay.getServerPort());
434         DocUtil.add(
435             themeDisplayEl, "time-zone", themeDisplay.getTimeZone().getID());
436         DocUtil.add(
437             themeDisplayEl, "url-portal",
438             HttpUtil.removeProtocol(themeDisplay.getURLPortal()));
439         DocUtil.add(themeDisplayEl, "user-id", themeDisplay.getUserId());
440 
441         if (themeDisplay.getPortletDisplay() != null) {
442             Element portletDisplayEl = themeDisplayEl.addElement(
443                 "portlet-display");
444 
445             _portletDisplayToXML(
446                 themeDisplay.getPortletDisplay(), portletDisplayEl);
447         }
448     }
449 
450     private static boolean _isValidAttributeName(String name) {
451         if (name.equalsIgnoreCase("j_password") ||
452             name.equalsIgnoreCase("LAYOUT_CONTENT") ||
453             name.equalsIgnoreCase("LAYOUTS") ||
454             name.equalsIgnoreCase("PORTLET_RENDER_PARAMETERS") ||
455             name.equalsIgnoreCase("USER_PASSWORD") ||
456             name.startsWith("javax.") ||
457             name.startsWith("liferay-ui:")) {
458 
459             return false;
460         }
461         else {
462             return true;
463         }
464     }
465 
466     private static boolean _isValidAttributeValue(Object obj) {
467         if (obj == null) {
468             return false;
469         }
470         else if (obj instanceof Collection) {
471             Collection<?> col = (Collection<?>)obj;
472 
473             if (col.size() == 0) {
474                 return false;
475             }
476             else {
477                 return true;
478             }
479         }
480         else if (obj instanceof Map) {
481             Map<?, ?> map = (Map<?, ?>)obj;
482 
483             if (map.size() == 0) {
484                 return false;
485             }
486             else {
487                 return true;
488             }
489         }
490         else {
491             String objString = String.valueOf(obj);
492 
493             if (Validator.isNull(objString)) {
494                 return false;
495             }
496 
497             String hashCode =
498                 StringPool.AT + Integer.toHexString(obj.hashCode());
499 
500             if (objString.endsWith(hashCode)) {
501                 return false;
502             }
503 
504             return true;
505         }
506     }
507 
508     private static void _portletDisplayToXML(
509         PortletDisplay portletDisplay, Element portletDisplayEl) {
510 
511         DocUtil.add(portletDisplayEl, "id", portletDisplay.getId());
512         DocUtil.add(
513             portletDisplayEl, "instance-id", portletDisplay.getInstanceId());
514         DocUtil.add(
515             portletDisplayEl, "portlet-name", portletDisplay.getPortletName());
516         DocUtil.add(
517             portletDisplayEl, "resource-pk", portletDisplay.getResourcePK());
518         DocUtil.add(
519             portletDisplayEl, "root-portlet-id",
520             portletDisplay.getRootPortletId());
521         DocUtil.add(
522             portletDisplayEl, "title", portletDisplay.getTitle());
523     }
524 
525     private static Log _log = LogFactoryUtil.getLog(PortletRequestUtil.class);
526 
527 }