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