PageRenderTime 25ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/projects/springframework-3.0.5/projects/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/util/PortletUtils.java

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Java | 494 lines | 223 code | 33 blank | 238 comment | 50 complexity | f677a392ee68f0047f2d0e48b2cc91ea MD5 | raw file
  1. /*
  2. * Copyright 2002-2009 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. package org.springframework.web.portlet.util;
  17. import java.io.File;
  18. import java.io.FileNotFoundException;
  19. import java.io.IOException;
  20. import java.util.Enumeration;
  21. import java.util.HashMap;
  22. import java.util.Map;
  23. import java.util.TreeMap;
  24. import javax.portlet.ActionRequest;
  25. import javax.portlet.ActionResponse;
  26. import javax.portlet.PortletContext;
  27. import javax.portlet.PortletException;
  28. import javax.portlet.PortletRequest;
  29. import javax.portlet.PortletRequestDispatcher;
  30. import javax.portlet.PortletSession;
  31. import javax.portlet.ResourceRequest;
  32. import javax.portlet.ResourceResponse;
  33. import javax.servlet.http.Cookie;
  34. import org.springframework.util.Assert;
  35. import org.springframework.util.StringUtils;
  36. import org.springframework.web.util.WebUtils;
  37. /**
  38. * Miscellaneous utilities for portlet applications.
  39. * Used by various framework classes.
  40. *
  41. * @author Juergen Hoeller
  42. * @author William G. Thompson, Jr.
  43. * @author John A. Lewis
  44. * @since 2.0
  45. */
  46. public abstract class PortletUtils {
  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. */
  53. public static File getTempDir(PortletContext portletContext) {
  54. Assert.notNull(portletContext, "PortletContext must not be null");
  55. return (File) portletContext.getAttribute(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE);
  56. }
  57. /**
  58. * Return the real path of the given path within the web application,
  59. * as provided by the portlet container.
  60. * <p>Prepends a slash if the path does not already start with a slash,
  61. * and throws a {@link java.io.FileNotFoundException} if the path cannot
  62. * be resolved to a resource (in contrast to
  63. * {@link javax.portlet.PortletContext#getRealPath PortletContext's <code>getRealPath</code>},
  64. * which simply returns <code>null</code>).
  65. * @param portletContext the portlet context of the web application
  66. * @param path the relative path within the web application
  67. * @return the corresponding real path
  68. * @throws FileNotFoundException if the path cannot be resolved to a resource
  69. * @see javax.portlet.PortletContext#getRealPath
  70. */
  71. public static String getRealPath(PortletContext portletContext, String path) throws FileNotFoundException {
  72. Assert.notNull(portletContext, "PortletContext must not be null");
  73. // Interpret location as relative to the web application root directory.
  74. if (!path.startsWith("/")) {
  75. path = "/" + path;
  76. }
  77. String realPath = portletContext.getRealPath(path);
  78. if (realPath == null) {
  79. throw new FileNotFoundException(
  80. "PortletContext resource [" + path + "] cannot be resolved to absolute file path - " +
  81. "web application archive not expanded?");
  82. }
  83. return realPath;
  84. }
  85. /**
  86. * Check the given request for a session attribute of the given name under the
  87. * {@link javax.portlet.PortletSession#PORTLET_SCOPE}.
  88. * Returns <code>null</code> if there is no session or if the session has no such attribute in that scope.
  89. * Does not create a new session if none has existed before!
  90. * @param request current portlet request
  91. * @param name the name of the session attribute
  92. * @return the value of the session attribute, or <code>null</code> if not found
  93. */
  94. public static Object getSessionAttribute(PortletRequest request, String name) {
  95. return getSessionAttribute(request, name, PortletSession.PORTLET_SCOPE);
  96. }
  97. /**
  98. * Check the given request for a session attribute of the given name in the given scope.
  99. * Returns <code>null</code> if there is no session or if the session has no such attribute in that scope.
  100. * Does not create a new session if none has existed before!
  101. * @param request current portlet request
  102. * @param name the name of the session attribute
  103. * @param scope session scope of this attribute
  104. * @return the value of the session attribute, or <code>null</code> if not found
  105. */
  106. public static Object getSessionAttribute(PortletRequest request, String name, int scope) {
  107. Assert.notNull(request, "Request must not be null");
  108. PortletSession session = request.getPortletSession(false);
  109. return (session != null ? session.getAttribute(name, scope) : null);
  110. }
  111. /**
  112. * Check the given request for a session attribute of the given name
  113. * under the {@link javax.portlet.PortletSession#PORTLET_SCOPE}.
  114. * Throws an exception if there is no session or if the session has
  115. * no such attribute in that scope.
  116. * <p>Does not create a new session if none has existed before!
  117. * @param request current portlet request
  118. * @param name the name of the session attribute
  119. * @return the value of the session attribute
  120. * @throws IllegalStateException if the session attribute could not be found
  121. */
  122. public static Object getRequiredSessionAttribute(PortletRequest request, String name)
  123. throws IllegalStateException {
  124. return getRequiredSessionAttribute(request, name, PortletSession.PORTLET_SCOPE);
  125. }
  126. /**
  127. * Check the given request for a session attribute of the given name in the given scope.
  128. * Throws an exception if there is no session or if the session has no such attribute
  129. * in that scope.
  130. * <p>Does not create a new session if none has existed before!
  131. * @param request current portlet request
  132. * @param name the name of the session attribute
  133. * @param scope session scope of this attribute
  134. * @return the value of the session attribute
  135. * @throws IllegalStateException if the session attribute could not be found
  136. */
  137. public static Object getRequiredSessionAttribute(PortletRequest request, String name, int scope)
  138. throws IllegalStateException {
  139. Object attr = getSessionAttribute(request, name, scope);
  140. if (attr == null) {
  141. throw new IllegalStateException("No session attribute '" + name + "' found");
  142. }
  143. return attr;
  144. }
  145. /**
  146. * Set the session attribute with the given name to the given value under the {@link javax.portlet.PortletSession#PORTLET_SCOPE}.
  147. * Removes the session attribute if value is <code>null</code>, if a session existed at all.
  148. * Does not create a new session if not necessary!
  149. * @param request current portlet request
  150. * @param name the name of the session attribute
  151. * @param value the value of the session attribute
  152. */
  153. public static void setSessionAttribute(PortletRequest request, String name, Object value) {
  154. setSessionAttribute(request, name, value, PortletSession.PORTLET_SCOPE);
  155. }
  156. /**
  157. * Set the session attribute with the given name to the given value in the given 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. * @param scope session scope of this attribute
  164. */
  165. public static void setSessionAttribute(PortletRequest request, String name, Object value, int scope) {
  166. Assert.notNull(request, "Request must not be null");
  167. if (value != null) {
  168. request.getPortletSession().setAttribute(name, value, scope);
  169. }
  170. else {
  171. PortletSession session = request.getPortletSession(false);
  172. if (session != null) {
  173. session.removeAttribute(name, scope);
  174. }
  175. }
  176. }
  177. /**
  178. * Get the specified session attribute under the {@link javax.portlet.PortletSession#PORTLET_SCOPE},
  179. * creating and setting a new attribute if no existing found. The given class
  180. * needs to have a public no-arg constructor.
  181. * Useful for on-demand state objects in a web tier, like shopping carts.
  182. * @param session current portlet session
  183. * @param name the name of the session attribute
  184. * @param clazz the class to instantiate for a new attribute
  185. * @return the value of the session attribute, newly created if not found
  186. * @throws IllegalArgumentException if the session attribute could not be instantiated
  187. */
  188. public static Object getOrCreateSessionAttribute(PortletSession session, String name, Class clazz)
  189. throws IllegalArgumentException {
  190. return getOrCreateSessionAttribute(session, name, clazz, PortletSession.PORTLET_SCOPE);
  191. }
  192. /**
  193. * Get the specified session attribute in the given 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. * @param scope the session scope of this attribute
  201. * @return the value of the session attribute, newly created if not found
  202. * @throws IllegalArgumentException if the session attribute could not be instantiated
  203. */
  204. public static Object getOrCreateSessionAttribute(PortletSession session, String name, Class clazz, int scope)
  205. throws IllegalArgumentException {
  206. Assert.notNull(session, "Session must not be null");
  207. Object sessionObject = session.getAttribute(name, scope);
  208. if (sessionObject == null) {
  209. Assert.notNull(clazz, "Class must not be null if attribute value is to be instantiated");
  210. try {
  211. sessionObject = clazz.newInstance();
  212. }
  213. catch (InstantiationException ex) {
  214. throw new IllegalArgumentException(
  215. "Could not instantiate class [" + clazz.getName() +
  216. "] for session attribute '" + name + "': " + ex.getMessage());
  217. }
  218. catch (IllegalAccessException ex) {
  219. throw new IllegalArgumentException(
  220. "Could not access default constructor of class [" + clazz.getName() +
  221. "] for session attribute '" + name + "': " + ex.getMessage());
  222. }
  223. session.setAttribute(name, sessionObject, scope);
  224. }
  225. return sessionObject;
  226. }
  227. /**
  228. * Return the best available mutex for the given session:
  229. * that is, an object to synchronize on for the given session.
  230. * <p>Returns the session mutex attribute if available; usually,
  231. * this means that the
  232. * {@link org.springframework.web.util.HttpSessionMutexListener}
  233. * needs to be defined in <code>web.xml</code>. Falls back to the
  234. * {@link javax.portlet.PortletSession} itself if no mutex attribute found.
  235. * <p>The session mutex is guaranteed to be the same object during
  236. * the entire lifetime of the session, available under the key defined
  237. * by the {@link org.springframework.web.util.WebUtils#SESSION_MUTEX_ATTRIBUTE}
  238. * constant. It serves as a safe reference to synchronize on for locking
  239. * on the current session.
  240. * <p>In many cases, the {@link javax.portlet.PortletSession} reference
  241. * itself is a safe mutex as well, since it will always be the same
  242. * object reference for the same active logical session. However, this is
  243. * not guaranteed across different servlet containers; the only 100% safe
  244. * way is a session mutex.
  245. * @param session the HttpSession to find a mutex for
  246. * @return the mutex object (never <code>null</code>)
  247. * @see org.springframework.web.util.WebUtils#SESSION_MUTEX_ATTRIBUTE
  248. * @see org.springframework.web.util.HttpSessionMutexListener
  249. */
  250. public static Object getSessionMutex(PortletSession session) {
  251. Assert.notNull(session, "Session must not be null");
  252. Object mutex = session.getAttribute(WebUtils.SESSION_MUTEX_ATTRIBUTE);
  253. if (mutex == null) {
  254. mutex = session;
  255. }
  256. return mutex;
  257. }
  258. /**
  259. * Expose the given Map as request attributes, using the keys as attribute names
  260. * and the values as corresponding attribute values. Keys must be Strings.
  261. * @param request current portlet request
  262. * @param attributes the attributes Map
  263. */
  264. public static void exposeRequestAttributes(PortletRequest request, Map<String, ?> attributes) {
  265. Assert.notNull(request, "Request must not be null");
  266. Assert.notNull(attributes, "Attributes Map must not be null");
  267. for (Map.Entry<String, ?> entry : attributes.entrySet()) {
  268. request.setAttribute(entry.getKey(), entry.getValue());
  269. }
  270. }
  271. /**
  272. * Retrieve the first cookie with the given name. Note that multiple
  273. * cookies can have the same name but different paths or domains.
  274. * @param request current servlet request
  275. * @param name cookie name
  276. * @return the first cookie with the given name, or <code>null</code> if none is found
  277. */
  278. public static Cookie getCookie(PortletRequest request, String name) {
  279. Assert.notNull(request, "Request must not be null");
  280. Cookie cookies[] = request.getCookies();
  281. if (cookies != null) {
  282. for (Cookie cookie : cookies) {
  283. if (name.equals(cookie.getName())) {
  284. return cookie;
  285. }
  286. }
  287. }
  288. return null;
  289. }
  290. /**
  291. * Check if a specific input type="submit" parameter was sent in the request,
  292. * either via a button (directly with name) or via an image (name + ".x" or
  293. * name + ".y").
  294. * @param request current portlet request
  295. * @param name name of the parameter
  296. * @return if the parameter was sent
  297. * @see org.springframework.web.util.WebUtils#SUBMIT_IMAGE_SUFFIXES
  298. */
  299. public static boolean hasSubmitParameter(PortletRequest request, String name) {
  300. return getSubmitParameter(request, name) != null;
  301. }
  302. /**
  303. * Return the full name of a specific input type="submit" parameter
  304. * if it was sent in the request, either via a button (directly with name)
  305. * or via an image (name + ".x" or name + ".y").
  306. * @param request current portlet request
  307. * @param name name of the parameter
  308. * @return the actual parameter name with suffix if needed - null if not present
  309. * @see org.springframework.web.util.WebUtils#SUBMIT_IMAGE_SUFFIXES
  310. */
  311. public static String getSubmitParameter(PortletRequest request, String name) {
  312. Assert.notNull(request, "Request must not be null");
  313. if (request.getParameter(name) != null) {
  314. return name;
  315. }
  316. for (int i = 0; i < WebUtils.SUBMIT_IMAGE_SUFFIXES.length; i++) {
  317. String suffix = WebUtils.SUBMIT_IMAGE_SUFFIXES[i];
  318. String parameter = name + suffix;
  319. if (request.getParameter(parameter) != null) {
  320. return parameter;
  321. }
  322. }
  323. return null;
  324. }
  325. /**
  326. * Return a map containing all parameters with the given prefix.
  327. * Maps single values to String and multiple values to String array.
  328. * <p>For example, with a prefix of "spring_", "spring_param1" and
  329. * "spring_param2" result in a Map with "param1" and "param2" as keys.
  330. * <p>Similar to portlet
  331. * {@link javax.portlet.PortletRequest#getParameterMap()},
  332. * but more flexible.
  333. * @param request portlet request in which to look for parameters
  334. * @param prefix the beginning of parameter names
  335. * (if this is <code>null</code> or the empty string, all parameters will match)
  336. * @return map containing request parameters <b>without the prefix</b>,
  337. * containing either a String or a String array as values
  338. * @see javax.portlet.PortletRequest#getParameterNames
  339. * @see javax.portlet.PortletRequest#getParameterValues
  340. * @see javax.portlet.PortletRequest#getParameterMap
  341. */
  342. public static Map<String, Object> getParametersStartingWith(PortletRequest request, String prefix) {
  343. Assert.notNull(request, "Request must not be null");
  344. Enumeration paramNames = request.getParameterNames();
  345. Map<String, Object> params = new TreeMap<String, Object>();
  346. if (prefix == null) {
  347. prefix = "";
  348. }
  349. while (paramNames != null && paramNames.hasMoreElements()) {
  350. String paramName = (String) paramNames.nextElement();
  351. if ("".equals(prefix) || paramName.startsWith(prefix)) {
  352. String unprefixed = paramName.substring(prefix.length());
  353. String[] values = request.getParameterValues(paramName);
  354. if (values == null || values.length == 0) {
  355. // Do nothing, no values found at all.
  356. }
  357. else if (values.length > 1) {
  358. params.put(unprefixed, values);
  359. }
  360. else {
  361. params.put(unprefixed, values[0]);
  362. }
  363. }
  364. }
  365. return params;
  366. }
  367. /**
  368. * Return the target page specified in the request.
  369. * @param request current portlet request
  370. * @param paramPrefix the parameter prefix to check for
  371. * (e.g. "_target" for parameters like "_target1" or "_target2")
  372. * @param currentPage the current page, to be returned as fallback
  373. * if no target page specified
  374. * @return the page specified in the request, or current page if not found
  375. */
  376. public static int getTargetPage(PortletRequest request, String paramPrefix, int currentPage) {
  377. Enumeration paramNames = request.getParameterNames();
  378. while (paramNames.hasMoreElements()) {
  379. String paramName = (String) paramNames.nextElement();
  380. if (paramName.startsWith(paramPrefix)) {
  381. for (int i = 0; i < WebUtils.SUBMIT_IMAGE_SUFFIXES.length; i++) {
  382. String suffix = WebUtils.SUBMIT_IMAGE_SUFFIXES[i];
  383. if (paramName.endsWith(suffix)) {
  384. paramName = paramName.substring(0, paramName.length() - suffix.length());
  385. }
  386. }
  387. return Integer.parseInt(paramName.substring(paramPrefix.length()));
  388. }
  389. }
  390. return currentPage;
  391. }
  392. /**
  393. * Pass all the action request parameters to the render phase by putting them into
  394. * the action response object. This may not be called when the action will call
  395. * {@link javax.portlet.ActionResponse#sendRedirect sendRedirect}.
  396. * @param request the current action request
  397. * @param response the current action response
  398. * @see javax.portlet.ActionResponse#setRenderParameter
  399. */
  400. public static void passAllParametersToRenderPhase(ActionRequest request, ActionResponse response) {
  401. try {
  402. Enumeration en = request.getParameterNames();
  403. while (en.hasMoreElements()) {
  404. String param = (String) en.nextElement();
  405. String values[] = request.getParameterValues(param);
  406. response.setRenderParameter(param, values);
  407. }
  408. }
  409. catch (IllegalStateException ex) {
  410. // Ignore in case sendRedirect was already set.
  411. }
  412. }
  413. /**
  414. * Clear all the render parameters from the {@link javax.portlet.ActionResponse}.
  415. * This may not be called when the action will call
  416. * {@link ActionResponse#sendRedirect sendRedirect}.
  417. * @param response the current action response
  418. * @see ActionResponse#setRenderParameters
  419. */
  420. public static void clearAllRenderParameters(ActionResponse response) {
  421. try {
  422. response.setRenderParameters(new HashMap<String, String[]>(0));
  423. }
  424. catch (IllegalStateException ex) {
  425. // Ignore in case sendRedirect was already set.
  426. }
  427. }
  428. /**
  429. * Serve the resource as specified in the given request to the given response,
  430. * using the PortletContext's request dispatcher.
  431. * <p>This is roughly equivalent to Portlet 2.0 GenericPortlet.
  432. * @param request the current resource request
  433. * @param response the current resource response
  434. * @param context the current Portlet's PortletContext
  435. * @throws PortletException propagated from Portlet API's forward method
  436. * @throws IOException propagated from Portlet API's forward method
  437. */
  438. public static void serveResource(ResourceRequest request, ResourceResponse response, PortletContext context)
  439. throws PortletException, IOException {
  440. String id = request.getResourceID();
  441. if (id != null) {
  442. if (!PortletUtils.isProtectedResource(id)) {
  443. PortletRequestDispatcher rd = context.getRequestDispatcher(id);
  444. if (rd != null) {
  445. rd.forward(request, response);
  446. return;
  447. }
  448. }
  449. response.setProperty(ResourceResponse.HTTP_STATUS_CODE, "404");
  450. }
  451. }
  452. /**
  453. * Check whether the specified path indicates a resource in the protected
  454. * WEB-INF or META-INF directories.
  455. * @param path the path to check
  456. */
  457. private static boolean isProtectedResource(String path) {
  458. return (StringUtils.startsWithIgnoreCase(path, "/WEB-INF") ||
  459. StringUtils.startsWithIgnoreCase(path, "/META-INF"));
  460. }
  461. }