KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > web > portlet > util > PortletUtils


1 /*
2  * Copyright 2002-2006 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.springframework.web.portlet.util;
18
19 import java.io.File JavaDoc;
20 import java.io.FileNotFoundException JavaDoc;
21 import java.util.Enumeration JavaDoc;
22 import java.util.HashMap JavaDoc;
23 import java.util.Iterator JavaDoc;
24 import java.util.Map JavaDoc;
25 import java.util.TreeMap JavaDoc;
26
27 import javax.portlet.ActionRequest;
28 import javax.portlet.ActionResponse;
29 import javax.portlet.PortletContext;
30 import javax.portlet.PortletRequest;
31 import javax.portlet.PortletSession;
32
33 import org.springframework.util.Assert;
34 import org.springframework.web.util.WebUtils;
35
36 /**
37  * Miscellaneous utilities for portlet applications.
38  * Used by various framework classes.
39  *
40  * @author Juergen Hoeller
41  * @author William G. Thompson, Jr.
42  * @author John A. Lewis
43  * @since 2.0
44  */

45 public abstract class PortletUtils {
46
47     /**
48      * Return the temporary directory for the current web application,
49      * as provided by the portlet container.
50      * @param portletContext the portlet context of the web application
51      * @return the File representing the temporary directory
52      * @throws IllegalArgumentException if the supplied <code>portletContext</code> is <code>null</code>
53      */

54     public static File JavaDoc getTempDir(PortletContext portletContext) {
55         Assert.notNull(portletContext, "PortletContext must not be null");
56         return (File JavaDoc) portletContext.getAttribute(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE);
57     }
58
59     /**
60      * Return the real path of the given path within the web application,
61      * as provided by the portlet container.
62      * <p>Prepends a slash if the path does not already start with a slash,
63      * and throws a {@link java.io.FileNotFoundException} if the path cannot
64      * be resolved to a resource (in contrast to
65      * {@link javax.portlet.PortletContext#getRealPath PortletContext's <code>getRealPath</code>},
66      * which simply returns <code>null</code>).
67      * @param portletContext the portlet context of the web application
68      * @param path the relative path within the web application
69      * @return the corresponding real path
70      * @throws FileNotFoundException if the path cannot be resolved to a resource
71      * @throws IllegalArgumentException if the supplied <code>portletContext</code> is <code>null</code>
72      * @throws NullPointerException if the supplied <code>path</code> is <code>null</code>
73      * @see javax.portlet.PortletContext#getRealPath
74      */

75     public static String JavaDoc getRealPath(PortletContext portletContext, String JavaDoc path) throws FileNotFoundException JavaDoc {
76         Assert.notNull(portletContext, "PortletContext must not be null");
77         // Interpret location as relative to the web application root directory.
78
if (!path.startsWith("/")) {
79             path = "/" + path;
80         }
81         String JavaDoc realPath = portletContext.getRealPath(path);
82         if (realPath == null) {
83             throw new FileNotFoundException JavaDoc(
84                     "PortletContext resource [" + path + "] cannot be resolved to absolute file path - " +
85                     "web application archive not expanded?");
86         }
87         return realPath;
88     }
89
90
91     /**
92      * Check the given request for a session attribute of the given name under the
93      * {@link javax.portlet.PortletSession#PORTLET_SCOPE}.
94      * Returns <code>null</code> if there is no session or if the session has no such attribute in that scope.
95      * Does not create a new session if none has existed before!
96      * @param request current portlet request
97      * @param name the name of the session attribute
98      * @return the value of the session attribute, or <code>null</code> if not found
99      * @throws IllegalArgumentException if the supplied <code>request</code> is <code>null</code>
100      */

101     public static Object JavaDoc getSessionAttribute(PortletRequest request, String JavaDoc name) {
102         return getSessionAttribute(request, name, PortletSession.PORTLET_SCOPE);
103     }
104
105     /**
106      * Check the given request for a session attribute of the given name in the given scope.
107      * Returns <code>null</code> if there is no session or if the session has no such attribute in that scope.
108      * Does not create a new session if none has existed before!
109      * @param request current portlet request
110      * @param name the name of the session attribute
111      * @param scope session scope of this attribute
112      * @return the value of the session attribute, or <code>null</code> if not found
113      * @throws IllegalArgumentException if the supplied <code>request</code> is <code>null</code>
114      */

115     public static Object JavaDoc getSessionAttribute(PortletRequest request, String JavaDoc name, int scope) {
116         Assert.notNull(request, "Request must not be null");
117         PortletSession session = request.getPortletSession(false);
118         return (session != null ? session.getAttribute(name, scope) : null);
119     }
120
121     /**
122      * Check the given request for a session attribute of the given name under the {@link javax.portlet.PortletSession#PORTLET_SCOPE}.
123      * Throws an exception if there is no session or if the session has no such attribute in that scope.
124      * Does not create a new session if none has existed before!
125      * @param request current portlet request
126      * @param name the name of the session attribute
127      * @return the value of the session attribute
128      * @throws IllegalStateException if the session attribute could not be found
129      * @throws IllegalArgumentException if the supplied <code>request</code> is <code>null</code>
130      */

131     public static Object JavaDoc getRequiredSessionAttribute(PortletRequest request, String JavaDoc name)
132             throws IllegalStateException JavaDoc {
133         return getRequiredSessionAttribute(request, name, PortletSession.PORTLET_SCOPE);
134     }
135
136     /**
137      * Check the given request for a session attribute of the given name in the given scope.
138      * Throws an exception if there is no session or if the session has no such attribute in that scope.
139      * Does not create a new session if none has existed before!
140      * @param request current portlet request
141      * @param name the name of the session attribute
142      * @param scope session scope of this attribute
143      * @return the value of the session attribute
144      * @throws IllegalStateException if the session attribute could not be found
145      * @throws IllegalArgumentException if the supplied <code>request</code> is <code>null</code>
146      */

147     public static Object JavaDoc getRequiredSessionAttribute(PortletRequest request, String JavaDoc name, int scope)
148             throws IllegalStateException JavaDoc {
149         Object JavaDoc attr = getSessionAttribute(request, name, scope);
150         if (attr == null) {
151             throw new IllegalStateException JavaDoc("No session attribute '" + name + "' found");
152         }
153         return attr;
154     }
155
156     /**
157      * Set the session attribute with the given name to the given value under the {@link javax.portlet.PortletSession#PORTLET_SCOPE}.
158      * Removes the session attribute if value is <code>null</code>, if a session existed at all.
159      * Does not create a new session if not necessary!
160      * @param request current portlet request
161      * @param name the name of the session attribute
162      * @param value the value of the session attribute
163      * @throws IllegalArgumentException if the supplied <code>request</code> is <code>null</code>
164      */

165     public static void setSessionAttribute(PortletRequest request, String JavaDoc name, Object JavaDoc value) {
166         setSessionAttribute(request, name, value, PortletSession.PORTLET_SCOPE);
167     }
168
169     /**
170      * Set the session attribute with the given name to the given value in the given scope.
171      * Removes the session attribute if value is <code>null</code>, if a session existed at all.
172      * Does not create a new session if not necessary!
173      * @param request current portlet request
174      * @param name the name of the session attribute
175      * @param value the value of the session attribute
176      * @param scope session scope of this attribute
177      * @throws IllegalArgumentException if the supplied <code>request</code> is <code>null</code>
178      */

179     public static void setSessionAttribute(PortletRequest request, String JavaDoc name, Object JavaDoc value, int scope) {
180         Assert.notNull(request, "Request must not be null");
181         if (value != null) {
182             request.getPortletSession().setAttribute(name, value, scope);
183         }
184         else {
185             PortletSession session = request.getPortletSession(false);
186             if (session != null) {
187                 session.removeAttribute(name, scope);
188             }
189         }
190     }
191
192     /**
193      * Get the specified session attribute under the {@link javax.portlet.PortletSession#PORTLET_SCOPE},
194      * creating and setting a new attribute if no existing found. The given class
195      * needs to have a public no-arg constructor.
196      * Useful for on-demand state objects in a web tier, like shopping carts.
197      * @param session current portlet session
198      * @param name the name of the session attribute
199      * @param clazz the class to instantiate for a new attribute
200      * @return the value of the session attribute, newly created if not found
201      * @throws IllegalArgumentException if the session attribute could not be instantiated; or if the supplied <code>session</code> argument is <code>null</code>
202      */

203     public static Object JavaDoc getOrCreateSessionAttribute(PortletSession session, String JavaDoc name, Class JavaDoc clazz)
204             throws IllegalArgumentException JavaDoc {
205         return getOrCreateSessionAttribute(session, name, clazz, PortletSession.PORTLET_SCOPE);
206     }
207
208     /**
209      * Get the specified session attribute in the given scope,
210      * creating and setting a new attribute if no existing found. The given class
211      * needs to have a public no-arg constructor.
212      * Useful for on-demand state objects in a web tier, like shopping carts.
213      * @param session current portlet session
214      * @param name the name of the session attribute
215      * @param clazz the class to instantiate for a new attribute
216      * @param scope the session scope of this attribute
217      * @return the value of the session attribute, newly created if not found
218      * @throws IllegalArgumentException if the session attribute could not be instantiated; or if the supplied <code>session</code> argument is <code>null</code>
219      */

220     public static Object JavaDoc getOrCreateSessionAttribute(PortletSession session, String JavaDoc name, Class JavaDoc clazz, int scope)
221             throws IllegalArgumentException JavaDoc {
222         Assert.notNull(session, "Session must not be null");
223         Object JavaDoc sessionObject = session.getAttribute(name, scope);
224         if (sessionObject == null) {
225             Assert.notNull(clazz, "Class must not be null if attribute value is to be instantiated");
226             try {
227                 sessionObject = clazz.newInstance();
228             }
229             catch (InstantiationException JavaDoc ex) {
230                 throw new IllegalArgumentException JavaDoc(
231                         "Could not instantiate class [" + clazz.getName() +
232                         "] for session attribute '" + name + "': " + ex.getMessage());
233             }
234             catch (IllegalAccessException JavaDoc ex) {
235                 throw new IllegalArgumentException JavaDoc(
236                         "Could not access default constructor of class [" + clazz.getName() +
237                         "] for session attribute '" + name + "': " + ex.getMessage());
238             }
239             session.setAttribute(name, sessionObject, scope);
240         }
241         return sessionObject;
242     }
243
244     /**
245      * Return the best available mutex for the given session:
246      * that is, an object to synchronize on for the given session.
247      * <p>Returns the session mutex attribute if available; usually,
248      * this means that the
249      * {@link org.springframework.web.util.HttpSessionMutexListener}
250      * needs to be defined in <code>web.xml</code>. Falls back to the
251      * {@link javax.portlet.PortletSession} itself if no mutex attribute found.
252      * <p>The session mutex is guaranteed to be the same object during
253      * the entire lifetime of the session, available under the key defined
254      * by the {@link org.springframework.web.util.WebUtils#SESSION_MUTEX_ATTRIBUTE}
255      * constant. It serves as a safe reference to synchronize on for locking
256      * on the current session.
257      * <p>In many cases, the {@link javax.portlet.PortletSession} reference
258      * itself is a safe mutex as well, since it will always be the same
259      * object reference for the same active logical session. However, this is
260      * not guaranteed across different servlet containers; the only 100% safe
261      * way is a session mutex.
262      * @param session the HttpSession to find a mutex for
263      * @return the mutex object (never <code>null</code>)
264      * @see org.springframework.web.util.WebUtils#SESSION_MUTEX_ATTRIBUTE
265      * @see org.springframework.web.util.HttpSessionMutexListener
266      */

267     public static Object JavaDoc getSessionMutex(PortletSession session) {
268         Assert.notNull(session, "Session must not be null");
269         Object JavaDoc mutex = session.getAttribute(WebUtils.SESSION_MUTEX_ATTRIBUTE);
270         if (mutex == null) {
271             mutex = session;
272         }
273         return mutex;
274     }
275
276     /**
277      * Expose the given Map as request attributes, using the keys as attribute names
278      * and the values as corresponding attribute values. Keys must be Strings.
279      * @param request current portlet request
280      * @param attributes the attributes Map
281      * @throws IllegalArgumentException if an invalid key is found in the Map (i.e. the key is not a String); or if
282      * either of the supplied arguments is <code>null</code>
283      */

284     public static void exposeRequestAttributes(PortletRequest request, Map JavaDoc attributes)
285             throws IllegalArgumentException JavaDoc {
286         Assert.notNull(request, "Request must not be null");
287         Assert.notNull(attributes, "attributes Map must not be null");
288         Iterator JavaDoc it = attributes.entrySet().iterator();
289         while (it.hasNext()) {
290             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) it.next();
291             if (!(entry.getKey() instanceof String JavaDoc)) {
292                 throw new IllegalArgumentException JavaDoc(
293                         "Invalid key [" + entry.getKey() + "] in attributes Map - only Strings allowed as attribute keys");
294             }
295             request.setAttribute((String JavaDoc) entry.getKey(), entry.getValue());
296         }
297     }
298
299     /**
300      * Check if a specific input type="submit" parameter was sent in the request,
301      * either via a button (directly with name) or via an image (name + ".x" or
302      * name + ".y").
303      * @param request current portlet request
304      * @param name name of the parameter
305      * @return if the parameter was sent
306      * @see org.springframework.web.util.WebUtils#SUBMIT_IMAGE_SUFFIXES
307      */

308     public static boolean hasSubmitParameter(PortletRequest request, String JavaDoc name) {
309         return getSubmitParameter(request, name) != null;
310     }
311
312     /**
313      * Return the full name of a specific input type="submit" parameter
314      * if it was sent in the request, either via a button (directly with name)
315      * or via an image (name + ".x" or name + ".y").
316      * @param request current portlet request
317      * @param name name of the parameter
318      * @return the actual parameter name with suffix if needed - null if not present
319      * @see org.springframework.web.util.WebUtils#SUBMIT_IMAGE_SUFFIXES
320      */

321     public static String JavaDoc getSubmitParameter(PortletRequest request, String JavaDoc name) {
322         Assert.notNull(request, "Request must not be null");
323         if (request.getParameter(name) != null) {
324             return name;
325         }
326         for (int i = 0; i < WebUtils.SUBMIT_IMAGE_SUFFIXES.length; i++) {
327             String JavaDoc suffix = WebUtils.SUBMIT_IMAGE_SUFFIXES[i];
328             String JavaDoc parameter = name + suffix;
329             if (request.getParameter(parameter) != null) {
330                 return parameter;
331             }
332         }
333         return null;
334     }
335
336     /**
337      * Return a map containing all parameters with the given prefix.
338      * Maps single values to String and multiple values to String array.
339      * <p>For example, with a prefix of "spring_", "spring_param1" and
340      * "spring_param2" result in a Map with "param1" and "param2" as keys.
341      * <p>Similar to portlet
342      * {@link javax.portlet.PortletRequest#getParameterMap()},
343      * but more flexible.
344      * @param request portlet request in which to look for parameters
345      * @param prefix the beginning of parameter names
346      * (if this is <code>null</code> or the empty string, all parameters will match)
347      * @return map containing request parameters <b>without the prefix</b>,
348      * containing either a String or a String array as values
349      * @see javax.portlet.PortletRequest#getParameterNames
350      * @see javax.portlet.PortletRequest#getParameterValues
351      * @see javax.portlet.PortletRequest#getParameterMap
352      */

353     public static Map JavaDoc getParametersStartingWith(PortletRequest request, String JavaDoc prefix) {
354         Assert.notNull(request, "Request must not be null");
355         Enumeration JavaDoc paramNames = request.getParameterNames();
356         Map JavaDoc params = new TreeMap JavaDoc();
357         if (prefix == null) {
358             prefix = "";
359         }
360         while (paramNames != null && paramNames.hasMoreElements()) {
361             String JavaDoc paramName = (String JavaDoc) paramNames.nextElement();
362             if ("".equals(prefix) || paramName.startsWith(prefix)) {
363                 String JavaDoc unprefixed = paramName.substring(prefix.length());
364                 String JavaDoc[] values = request.getParameterValues(paramName);
365                 if (values == null) {
366                     // do nothing, no values found at all
367
}
368                 else if (values.length > 1) {
369                     params.put(unprefixed, values);
370                 }
371                 else {
372                     params.put(unprefixed, values[0]);
373                 }
374             }
375         }
376         return params;
377     }
378
379
380     /**
381      * Pass all the action request parameters to the render phase by putting them into
382      * the action response object. This may not be called when the action will call
383      * {@link javax.portlet.ActionResponse#sendRedirect sendRedirect}.
384      * @param request the current action request
385      * @param response the current action response
386      * @see javax.portlet.ActionResponse#setRenderParameter
387      */

388     public static void passAllParametersToRenderPhase(ActionRequest request, ActionResponse response) {
389         try {
390             Enumeration JavaDoc en = request.getParameterNames();
391             while (en.hasMoreElements()) {
392                 String JavaDoc param = (String JavaDoc) en.nextElement();
393                 String JavaDoc values[] = request.getParameterValues(param);
394                 response.setRenderParameter(param, values);
395             }
396         }
397         catch (IllegalStateException JavaDoc ex) {
398             // Ignore in case sendRedirect was already set.
399
}
400     }
401
402     /**
403      * Clear all the render parameters from the {@link javax.portlet.ActionResponse}.
404      * This may not be called when the action will call
405      * {@link ActionResponse#sendRedirect sendRedirect}.
406      * @param response the current action response
407      * @see ActionResponse#setRenderParameters
408      */

409     public static void clearAllRenderParameters(ActionResponse response) {
410         try {
411             response.setRenderParameters(new HashMap JavaDoc());
412         }
413         catch (IllegalStateException JavaDoc ex) {
414             // Ignore in case sendRedirect was already set.
415
}
416     }
417
418 }
419
Popular Tags