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.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  public class PortletRequestUtil {
70  
71      public static List<DiskFileItem> testMultipartWithCommonsFileUpload(
72              ActionRequest actionRequest)
73          throws Exception {
74  
75          // Check if the given request is a multipart request
76  
77          boolean multiPartContent = PortletFileUpload.isMultipartContent(
78              actionRequest);
79  
80          if (multiPartContent) {
81              _log.info("The given request is a multipart request");
82          }
83          else {
84              _log.info("The given request is NOT a multipart request");
85          }
86  
87          // Check for the number of file items
88  
89          DiskFileItemFactory factory = new DiskFileItemFactory();
90  
91          PortletFileUpload upload = new PortletFileUpload(factory);
92  
93          List<DiskFileItem> fileItems = upload.parseRequest(actionRequest);
94  
95          if (_log.isInfoEnabled()) {
96              _log.info(
97                  "Apache commons upload was able to parse " + fileItems.size() +
98                      " items");
99          }
100 
101         for (int i = 0; i < fileItems.size(); i++) {
102             DiskFileItem fileItem = fileItems.get(i);
103 
104             if (_log.isInfoEnabled()) {
105                 _log.info("Item " + i + " " + fileItem);
106             }
107         }
108 
109         return fileItems;
110     }
111 
112     public static int testMultipartWithPortletInputStream(
113             ActionRequest actionRequest)
114         throws Exception {
115 
116         // Read directly from the portlet input stream
117 
118         InputStream is = actionRequest.getPortletInputStream();
119 
120         if (is != null) {
121             ByteArrayOutputStream baos = new ByteArrayOutputStream();
122 
123             int c = -1;
124 
125             try {
126                 while ((c = is.read()) != -1) {
127                     baos.write(c);
128                 }
129             }
130             finally {
131                 is.close();
132             }
133 
134             byte[] bytes = baos.toByteArray();
135 
136             if (_log.isInfoEnabled()) {
137                 _log.info(
138                     "Byte array size from the raw input stream is " +
139                         bytes.length);
140             }
141 
142             return bytes.length;
143         }
144 
145         return -1;
146     }
147 
148     public static String toXML(
149         PortletRequest portletRequest, PortletResponse portletResponse) {
150 
151         String xml = null;
152 
153         Document doc = SAXReaderUtil.createDocument();
154 
155         Element reqEl = doc.addElement("request");
156 
157         DocUtil.add(reqEl, "container-type", "portlet");
158         DocUtil.add(
159             reqEl, "container-namespace", portletRequest.getContextPath());
160         DocUtil.add(
161             reqEl, "content-type", portletRequest.getResponseContentType());
162         DocUtil.add(reqEl, "server-name", portletRequest.getServerName());
163         DocUtil.add(reqEl, "server-port", portletRequest.getServerPort());
164         DocUtil.add(reqEl, "secure", portletRequest.isSecure());
165         DocUtil.add(reqEl, "auth-type", portletRequest.getAuthType());
166         DocUtil.add(reqEl, "remote-user", portletRequest.getRemoteUser());
167         DocUtil.add(reqEl, "context-path", portletRequest.getContextPath());
168         DocUtil.add(reqEl, "locale", portletRequest.getLocale());
169         DocUtil.add(reqEl, "portlet-mode", portletRequest.getPortletMode());
170         DocUtil.add(
171             reqEl, "portlet-session-id",
172             portletRequest.getRequestedSessionId());
173         DocUtil.add(reqEl, "scheme", portletRequest.getScheme());
174         DocUtil.add(reqEl, "window-state", portletRequest.getWindowState());
175 
176         if (portletRequest instanceof ActionRequest) {
177             DocUtil.add(reqEl, "lifecycle", RenderRequest.ACTION_PHASE);
178         }
179         else if (portletRequest instanceof RenderRequest) {
180             DocUtil.add(reqEl, "lifecycle", RenderRequest.RENDER_PHASE);
181         }
182         else if (portletRequest instanceof ResourceRequest) {
183             DocUtil.add(reqEl, "lifecycle", RenderRequest.RESOURCE_PHASE);
184         }
185 
186         if (portletResponse instanceof MimeResponse) {
187             _mimeResponseToXML((MimeResponse)portletResponse, reqEl);
188         }
189 
190         ThemeDisplay themeDisplay = (ThemeDisplay)portletRequest.getAttribute(
191             WebKeys.THEME_DISPLAY);
192 
193         if (themeDisplay != null) {
194             Element themeDisplayEl = reqEl.addElement("theme-display");
195 
196             _themeDisplayToXML(themeDisplay, themeDisplayEl);
197         }
198 
199         Element parametersEl = reqEl.addElement("parameters");
200 
201         Enumeration<String> enu = portletRequest.getParameterNames();
202 
203         while (enu.hasMoreElements()) {
204             String name = enu.nextElement();
205 
206             Element parameterEl = parametersEl.addElement("parameter");
207 
208             DocUtil.add(parameterEl, "name", name);
209 
210             String[] values = portletRequest.getParameterValues(name);
211 
212             for (int i = 0; i < values.length; i++) {
213                 DocUtil.add(parameterEl, "value", values[i]);
214             }
215         }
216 
217         Element attributesEl = reqEl.addElement("attributes");
218 
219         enu = portletRequest.getAttributeNames();
220 
221         while (enu.hasMoreElements()) {
222             String name = enu.nextElement();
223 
224             if (!_isValidAttributeName(name)) {
225                 continue;
226             }
227 
228             Object value = portletRequest.getAttribute(name);
229 
230             if (!_isValidAttributeValue(value)) {
231                 continue;
232             }
233 
234             Element attributeEl = attributesEl.addElement("attribute");
235 
236             DocUtil.add(attributeEl, "name", name);
237             DocUtil.add(attributeEl, "value", String.valueOf(value));
238         }
239 
240         Element portletSessionEl = reqEl.addElement("portlet-session");
241 
242         attributesEl = portletSessionEl.addElement("portlet-attributes");
243 
244         PortletSession portletSession = portletRequest.getPortletSession();
245 
246         try {
247             enu = portletSession.getAttributeNames(
248                 PortletSession.PORTLET_SCOPE);
249 
250             while (enu.hasMoreElements()) {
251                 String name = enu.nextElement();
252 
253                 if (!_isValidAttributeName(name)) {
254                     continue;
255                 }
256 
257                 Object value = portletSession.getAttribute(
258                     name, PortletSession.PORTLET_SCOPE);
259 
260                 if (!_isValidAttributeValue(value)) {
261                     continue;
262                 }
263 
264                 Element attributeEl = attributesEl.addElement("attribute");
265 
266                 DocUtil.add(attributeEl, "name", name);
267                 DocUtil.add(attributeEl, "value", String.valueOf(value));
268             }
269 
270             attributesEl = portletSessionEl.addElement(
271                 "application-attributes");
272 
273             enu = portletSession.getAttributeNames(
274                 PortletSession.APPLICATION_SCOPE);
275 
276             while (enu.hasMoreElements()) {
277                 String name = enu.nextElement();
278 
279                 if (!_isValidAttributeName(name)) {
280                     continue;
281                 }
282 
283                 Object value = portletSession.getAttribute(
284                     name, PortletSession.APPLICATION_SCOPE);
285 
286                 if (!_isValidAttributeValue(value)) {
287                     continue;
288                 }
289 
290                 Element attributeEl = attributesEl.addElement("attribute");
291 
292                 DocUtil.add(attributeEl, "name", name);
293                 DocUtil.add(attributeEl, "value", String.valueOf(value));
294             }
295         }
296         catch (IllegalStateException ise) {
297             if (_log.isWarnEnabled()) {
298                 _log.warn(ise.getMessage());
299             }
300         }
301 
302         try {
303             xml = doc.formattedString();
304         }
305         catch (IOException ioe) {
306         }
307 
308         return xml;
309     }
310 
311     private static void _mimeResponseToXML(
312         MimeResponse mimeResponse, Element reqEl) {
313 
314         String namespace = mimeResponse.getNamespace();
315 
316         DocUtil.add(reqEl, "portlet-namespace", namespace);
317 
318         try {
319             PortletURL actionUrl = mimeResponse.createActionURL();
320 
321             DocUtil.add(reqEl, "action-url", actionUrl);
322         }
323         catch (IllegalStateException ise) {
324             if (_log.isWarnEnabled()) {
325                 _log.warn(ise.getMessage());
326             }
327         }
328 
329         try {
330             PortletURL renderUrl = mimeResponse.createRenderURL();
331 
332             DocUtil.add(reqEl, "render-url", renderUrl);
333 
334             try {
335                 renderUrl.setWindowState(LiferayWindowState.EXCLUSIVE);
336 
337                 DocUtil.add(reqEl, "render-url-exclusive", renderUrl);
338             }
339             catch (WindowStateException wse) {
340             }
341 
342             try {
343                 renderUrl.setWindowState(LiferayWindowState.MAXIMIZED);
344 
345                 DocUtil.add(reqEl, "render-url-maximized", renderUrl);
346             }
347             catch (WindowStateException wse) {
348             }
349 
350             try {
351                 renderUrl.setWindowState(LiferayWindowState.MINIMIZED);
352 
353                 DocUtil.add(reqEl, "render-url-minimized", renderUrl);
354             }
355             catch (WindowStateException wse) {
356             }
357 
358             try {
359                 renderUrl.setWindowState(LiferayWindowState.NORMAL);
360 
361                 DocUtil.add(reqEl, "render-url-normal", renderUrl);
362             }
363             catch (WindowStateException wse) {
364             }
365 
366             try {
367                 renderUrl.setWindowState(LiferayWindowState.POP_UP);
368 
369                 DocUtil.add(reqEl, "render-url-pop-up", renderUrl);
370             }
371             catch (WindowStateException wse) {
372             }
373         }
374         catch (IllegalStateException ise) {
375             if (_log.isWarnEnabled()) {
376                 _log.warn(ise.getMessage());
377             }
378         }
379 
380         ResourceURL resourceURL = mimeResponse.createResourceURL();
381 
382         String resourceURLString = HttpUtil.removeParameter(
383             resourceURL.toString(), namespace + "struts_action");
384 
385         resourceURLString = HttpUtil.removeParameter(
386             resourceURLString, namespace + "redirect");
387 
388         DocUtil.add(reqEl, "resource-url", resourceURLString);
389     }
390 
391     private static void _themeDisplayToXML(
392         ThemeDisplay themeDisplay, Element themeDisplayEl) {
393 
394         DocUtil.add(themeDisplayEl, "cdn-host", themeDisplay.getCDNHost());
395         DocUtil.add(themeDisplayEl, "company-id", themeDisplay.getCompanyId());
396         DocUtil.add(
397             themeDisplayEl, "do-as-user-id", themeDisplay.getDoAsUserId());
398         DocUtil.add(
399             themeDisplayEl, "i18n-language-id",
400             themeDisplay.getI18nLanguageId());
401         DocUtil.add(themeDisplayEl, "i18n-path", themeDisplay.getI18nPath());
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 }