KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > struts > webapp > tiles > portal > UserMenuAction


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

18
19 package org.apache.struts.webapp.tiles.portal;
20
21 import java.io.IOException JavaDoc;
22 import java.util.ArrayList JavaDoc;
23 import java.util.Iterator JavaDoc;
24 import java.util.List JavaDoc;
25
26 import javax.servlet.ServletContext JavaDoc;
27 import javax.servlet.ServletException JavaDoc;
28 import javax.servlet.http.HttpServletRequest JavaDoc;
29 import javax.servlet.http.HttpServletResponse JavaDoc;
30 import javax.servlet.http.HttpSession JavaDoc;
31
32 import org.apache.commons.logging.Log;
33 import org.apache.commons.logging.LogFactory;
34 import org.apache.struts.action.ActionForm;
35 import org.apache.struts.action.ActionForward;
36 import org.apache.struts.action.ActionMapping;
37 import org.apache.struts.tiles.ComponentContext;
38 import org.apache.struts.tiles.ComponentDefinition;
39 import org.apache.struts.tiles.Controller;
40 import org.apache.struts.tiles.DefinitionsUtil;
41 import org.apache.struts.tiles.actions.TilesAction;
42 import org.apache.struts.tiles.beans.MenuItem;
43
44 /**
45  * This controller load user menu settings and put them in tile context.
46  * If menu settings are not defined for user, defined them based on tiles
47  * attributes used as default.
48  *
49  * This implementation extends Struts Action, and also define Tiles Controller interface.
50  * This allows to use it as well as a controller type or a controller url. If used
51  * as controller type, Struts Action functionality are not availables.
52  *
53  * Tiles input attributes :
54  * <ul>
55  * <li>title : menu title</li>
56  * <li>items : Menu entries used as default when user settings is created</li>
57  * <li>defaultChoice : Menus or menu entries porposed as choice to user</li>
58  * <li>storeUnderName : Store user settings under provided name in session context [optional]</li>
59  * <li></li>
60  * </ul>
61  * Tiles output attributes :
62  * <ul>
63  * <li>title : menu title</li>
64  * <li>items : Menu items to display</li>
65  * <li></li>
66  * </ul>
67  *
68  * @version $Rev: 54929 $ $Date: 2004-10-16 17:38:42 +0100 (Sat, 16 Oct 2004) $
69  */

70 public final class UserMenuAction extends TilesAction implements Controller {
71
72     /**
73      * Commons Logging instance.
74      */

75     private static Log log = LogFactory.getLog(UserMenuAction.class);
76
77     /**
78      * Tile attribute containing name used to store user settings in session
79      * context.
80      */

81     public static String JavaDoc USER_SETTINGS_NAME_ATTRIBUTE = "userSettingsName";
82
83     /**
84      * Default name used to store settings in session context.
85      */

86     public static String JavaDoc DEFAULT_USER_SETTINGS_NAME =
87         "tiles.examples.portal.USER_MENU_SETTINGS";
88
89     /**
90      * Default name used to store menu catalog in application scope.
91      */

92     public static String JavaDoc DEFAULT_MENU_CATALOG_NAME =
93         "tiles.examples.portal.MenuCatalog";
94
95     /**
96      * Tile attribute containing name used to store menu catalog in application
97      * scope.
98      */

99     public static String JavaDoc MENU_CATALOG_NAME_ATTRIBUTE = "catalogName";
100
101     /**
102      * Tile attribute containing name of the settings definition used to
103      * initialize catalog.
104      */

105     public static final String JavaDoc CATALOG_SETTING_ATTRIBUTE = "catalogSettings";
106
107     /**
108      * Tile attribute containing items to render.
109      */

110     public static String JavaDoc USER_ITEMS_ATTRIBUTE = "items";
111
112     /**
113      * Struts' action perform().
114      * Process the specified HTTP request, and create the corresponding HTTP
115      * response (or forward to another web component that will create it).
116      * Return an <code>ActionForward</code> instance describing where and how
117      * control should be forwarded, or <code>null</code> if the response has
118      * already been completed.
119      *
120      * @param context The current Tile context, containing Tile attributes.
121      * @param mapping The ActionMapping used to select this instance.
122      * @param form The optional ActionForm bean for this request (if any).
123      * @param request The HTTP request we are processing.
124      * @param response The HTTP response we are creating.
125      *
126      * @exception Exception if the application business logic throws
127      * an exception
128      * @since Struts 1.1
129      */

130     public ActionForward execute(
131         ComponentContext context,
132         ActionMapping mapping,
133         ActionForm form,
134         HttpServletRequest JavaDoc request,
135         HttpServletResponse JavaDoc response)
136         throws Exception JavaDoc {
137
138         this.execute(
139             context,
140             request,
141             response,
142             getServlet().getServletContext());
143
144         return null;
145     }
146
147     /**
148      * Method associated to a tile and called immediately before tile is included.
149      * @param tileContext Current tile context.
150      * @param request Current request
151      * @param response Current response
152      * @param servletContext Current servlet context
153      */

154     public void perform(
155         ComponentContext context,
156         HttpServletRequest JavaDoc request,
157         HttpServletResponse JavaDoc response,
158         ServletContext JavaDoc servletContext)
159         throws ServletException JavaDoc, IOException JavaDoc {
160
161         log.debug("Enter action UserMenuAction");
162
163         // Load user settings from user context
164
MenuSettings settings = getUserSettings(request, context);
165
166         // Set parameters for rendering page
167
context.putAttribute(USER_ITEMS_ATTRIBUTE, settings.getItems());
168
169         log.debug("settings=" + settings);
170         log.debug("Exit action UserMenuAction");
171
172     }
173
174     /**
175      * Load user setting.
176      * This implementation load setting from user context.
177      * If settings are not found, initialized them from default items defined
178      * in Tile's context.
179      * If settings are not found, initialized them.
180      */

181     public static MenuSettings getUserSettings(
182         HttpServletRequest JavaDoc request,
183         ComponentContext context)
184         throws ServletException JavaDoc {
185
186         // Get current session.
187
HttpSession JavaDoc session = request.getSession();
188
189         // Retrieve attribute name used to store settings.
190
String JavaDoc userSettingsName =
191             (String JavaDoc) context.getAttribute(USER_SETTINGS_NAME_ATTRIBUTE);
192
193         if (userSettingsName == null) {
194             userSettingsName = DEFAULT_USER_SETTINGS_NAME;
195         }
196
197         // Get user list from user context
198
MenuSettings settings =
199             (MenuSettings) session.getAttribute(userSettingsName);
200
201         // If settings don't exist, create and initialize them
202
// Initialization is done from context attribute denoted by ITEMS
203
if (settings == null) {
204             // List doesn't exist, create it and initialize it from Tiles parameters
205
settings = new MenuSettings();
206             try {
207                 settings.addItems(
208                     (List JavaDoc) context.getAttribute(USER_ITEMS_ATTRIBUTE));
209             } catch (ClassCastException JavaDoc ex) {
210                 throw new ServletException JavaDoc("Can't initialize user menu : default items must be a list of items");
211             }
212
213             // Save user settings in session
214
session.setAttribute(userSettingsName, settings);
215         }
216
217         return settings;
218     }
219
220     /**
221      * Get catalog of available menu entries.
222      * This implementation creates catalog list from the provided menu bar
223      * entries.
224      */

225     public static List JavaDoc getCatalog(
226         ComponentContext context,
227         HttpServletRequest JavaDoc request,
228         ServletContext JavaDoc servletContext)
229         throws ServletException JavaDoc {
230
231         // Retrieve name used to store catalog in application context.
232
// If not found, use default name
233
String JavaDoc catalogName =
234             (String JavaDoc) context.getAttribute(MENU_CATALOG_NAME_ATTRIBUTE);
235
236         if (catalogName == null) {
237             catalogName = DEFAULT_MENU_CATALOG_NAME;
238         }
239
240         // Get catalog from context
241
List JavaDoc catalog = (List JavaDoc) servletContext.getAttribute(catalogName);
242
243         // If not found, initialize it from provided default menu
244
if (catalog == null) {
245             Object JavaDoc menuBar = context.getAttribute(CATALOG_SETTING_ATTRIBUTE);
246             if (menuBar == null) {
247                 throw new ServletException JavaDoc(
248                     "Attribute '"
249                         + CATALOG_SETTING_ATTRIBUTE
250                         + "' must be set. It define entries used in catalog");
251             }
252
253             catalog = new ArrayList JavaDoc();
254             extractItems(catalog, menuBar, request, servletContext);
255             if (catalog.size() == 0) {
256                 throw new ServletException JavaDoc("Can't initialize menu items catalog");
257             }
258
259             // save it for future use
260
servletContext.setAttribute(catalogName, catalog);
261         }
262
263         return catalog;
264     }
265
266     /**
267      * Extract menu items from passed object. Items are stored in
268      * <code>result</code> parameter.
269      * This method allows to create a list of menu entries from existing menus.
270      * Check object type class :
271      * <li>
272      * <ul>MenuItems : add it</ul>
273      * <ul>ComponentDefinition : get attribute items, or list if not found.
274      * Call ExtractItems with resulting attribute.
275      * </ul>
276      * <ul>List : iterate on list, and call ExtractItems for each element.
277      * </li>
278      * @param result result list (should be initialized)
279      * @param object object to add (MenuItems, Definition, ...)
280      * @param request current request
281      * @param servletContext current servlet context.
282      */

283     private static void extractItems(
284         List JavaDoc result,
285         Object JavaDoc object,
286         HttpServletRequest JavaDoc request,
287         ServletContext JavaDoc servletContext) {
288
289         log.debug("Extract menu item from '" + object + "'");
290
291         if (object instanceof String JavaDoc) { // definition name
292
try {
293                 ComponentDefinition def =
294                     DefinitionsUtil.getDefinition(
295                         (String JavaDoc) object,
296                         request,
297                         servletContext);
298
299                 extractItems(result, def, request, servletContext);
300
301             } catch (Exception JavaDoc ex) { // silently fail
302
}
303
304         } else if (object instanceof List JavaDoc) {
305             List JavaDoc list = (List JavaDoc) object;
306             Iterator JavaDoc iter = list.iterator();
307             while (iter.hasNext()) {
308                 extractItems(result, iter.next(), request, servletContext);
309             }
310
311         } else if (object instanceof ComponentDefinition) {
312             ComponentDefinition definition = (ComponentDefinition) object;
313             Object JavaDoc attribute = definition.getAttribute("items");
314             if (attribute == null) {
315                 attribute = definition.getAttribute("list");
316             }
317
318             if (attribute == null) {
319                 return;
320             }
321
322             extractItems(result, attribute, request, servletContext);
323
324         } else if (object instanceof MenuItem) {
325             result.add(object);
326         }
327     }
328
329     /**
330      * @see org.apache.struts.tiles.Controller#execute(org.apache.struts.tiles.ComponentContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, javax.servlet.ServletContext)
331      */

332     public void execute(
333         ComponentContext tileContext,
334         HttpServletRequest JavaDoc request,
335         HttpServletResponse JavaDoc response,
336         ServletContext JavaDoc servletContext)
337         throws Exception JavaDoc {
338             
339         log.debug("Enter action UserMenuAction");
340
341         // Load user settings from user context
342
MenuSettings settings = getUserSettings(request, tileContext);
343
344         // Set parameters for rendering page
345
tileContext.putAttribute(USER_ITEMS_ATTRIBUTE, settings.getItems());
346
347         log.debug("settings=" + settings);
348         log.debug("Exit action UserMenuAction");
349
350     }
351
352 }
353
Popular Tags