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