KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > blandware > atleap > webapp > util > core > MenuUtil


1 /*
2  * Copyright 2004 Blandware (http://www.blandware.com)
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 com.blandware.atleap.webapp.util.core;
17
18 import com.blandware.atleap.common.Constants;
19 import com.blandware.atleap.common.util.QueryInfo;
20 import com.blandware.atleap.common.util.ConvertUtil;
21 import com.blandware.atleap.model.core.*;
22 import com.blandware.atleap.service.core.LayoutManager;
23 import com.blandware.atleap.service.core.MenuManager;
24 import com.blandware.atleap.service.core.PageManager;
25 import com.blandware.atleap.service.core.RoleManager;
26 import com.blandware.atleap.service.exception.BeanNotFoundException;
27 import com.blandware.atleap.webapp.exception.MenuUtilException;
28 import com.blandware.atleap.webapp.menu.MenuComponent;
29 import com.blandware.atleap.webapp.menu.MenuRepository;
30 import com.blandware.atleap.webapp.menu.LoadableResourceException;
31 import com.blandware.atleap.webapp.struts.HeritableComponentDefinition;
32 import org.apache.commons.logging.Log;
33 import org.apache.commons.logging.LogFactory;
34 import org.apache.commons.beanutils.Converter;
35 import org.apache.commons.beanutils.ConvertUtils;
36 import org.apache.commons.validator.GenericValidator;
37 import org.apache.struts.tiles.TilesUtil;
38 import org.springframework.context.ApplicationContext;
39 import org.springframework.web.context.support.WebApplicationContextUtils;
40
41 import javax.servlet.ServletContext JavaDoc;
42 import javax.servlet.http.HttpServletRequest JavaDoc;
43 import java.io.PrintWriter JavaDoc;
44 import java.io.StringWriter JavaDoc;
45 import java.net.MalformedURLException JavaDoc;
46 import java.util.ArrayList JavaDoc;
47 import java.util.HashMap JavaDoc;
48 import java.util.Iterator JavaDoc;
49 import java.util.LinkedList JavaDoc;
50 import java.util.List JavaDoc;
51 import java.util.ListIterator JavaDoc;
52 import java.util.Map JavaDoc;
53
54 /**
55  * <p>Provides some methods to work with menus</p>
56  * <p><a HREF="MenuUtil.java.htm"><i>View Source</i></a></p>
57  *
58  * @author Sergey Zubtcovskii <a HREF="mailto:sergey.zubtcovskii@blandware.com">&lt;sergey.zubtcovskii@blandware.com&gt;</a>
59  * @version $Revision: 1.23 $ $Date: 2006/03/16 11:09:43 $
60  */

61 public final class MenuUtil {
62
63     protected transient final Log log = LogFactory.getLog(MenuUtil.class);
64
65     protected transient HttpServletRequest JavaDoc request;
66
67     protected transient ServletContext JavaDoc servletContext;
68
69     protected transient ApplicationContext applicationContext;
70
71     protected transient String JavaDoc contextPath;
72
73     /**
74      * Menu manager to work with
75      */

76     protected transient MenuManager menuManager;
77
78     /**
79      * Creates new instance of MenuUtil
80      *
81      * @param request HttpServletRequest instance
82      */

83     public MenuUtil(HttpServletRequest JavaDoc request) {
84         this.request = request;
85         this.servletContext = request.getSession().getServletContext();
86         this.contextPath = request.getContextPath();
87         this.applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
88         this.menuManager = (MenuManager) applicationContext.getBean(Constants.MENU_MANAGER_BEAN);
89     }
90
91     /**
92      * Creates menu util for initialization purposes
93      *
94      * @param servletContext Servlet context
95      * @param contextPath Context path
96      */

97     public MenuUtil(ServletContext JavaDoc servletContext, String JavaDoc contextPath) {
98         this.request = null;
99         this.servletContext = servletContext;
100         this.contextPath = contextPath;
101         this.applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
102         this.menuManager = (MenuManager) applicationContext.getBean(Constants.MENU_MANAGER_BEAN);
103     }
104
105
106     public List JavaDoc getMenuItems(Long JavaDoc parentItemId, String JavaDoc layoutDefinition, String JavaDoc pageUri, boolean deleteInvisible) throws MenuUtilException {
107
108         List JavaDoc owners = lookupOwners(layoutDefinition, pageUri);
109         List JavaDoc menuItems = lookupItems(owners, parentItemId, deleteInvisible);
110
111         // set location
112
try {
113             for ( ListIterator JavaDoc iterator = menuItems.listIterator(); iterator.hasNext(); ) {
114                 MenuItem menuItem = (MenuItem) iterator.next();
115                 menuItem.setLocation(getLocation(menuItem, WebappConstants.URL_TYPE_CONTEXT_RELATIVE));
116             }
117         } catch ( MalformedURLException JavaDoc e ) {
118             if ( log.isFatalEnabled() ) {
119                 StringWriter JavaDoc sw = new StringWriter JavaDoc();
120                 e.printStackTrace(new PrintWriter JavaDoc(sw));
121                 log.fatal("Setting location failed. See the stack trace for details.");
122                 log.fatal(sw.toString());
123             }
124         }
125         return menuItems;
126     }
127
128     public MenuComponent getMenuComponent(String JavaDoc itemIdentifier, String JavaDoc localeIdentifier, String JavaDoc layoutDefinition, String JavaDoc pageUri, boolean deleteInvisible) throws MenuUtilException {
129
130         LinkedList JavaDoc owners = lookupOwners(layoutDefinition, pageUri);
131
132         int i = 0;
133         MenuItem menuItem = null;
134         for ( i = 0; i < owners.size(); i++ ) {
135             Localizable owner = (Localizable) owners.get(i);
136             Long JavaDoc ownerId = null;
137             if ( owner != null ) {
138                 ownerId = owner.getId();
139             }
140             menuItem = menuManager.findMenuItemByIdentifierAndParentAndOwner(itemIdentifier, null, ownerId);
141             if ( menuItem != null ) {
142                 break;
143             }
144         }
145
146         if ( menuItem == null ) {
147             // nothing found
148
return null;
149         }
150
151         Byte JavaDoc visibility = menuItem.getVisibility();
152
153         if ( menuItem.isVisibilityHeritable() ) {
154             visibility = new Byte JavaDoc(MenuItem.VISIBILITY_VISIBLE);
155         }
156
157         // search for redefinition of this item from the another side of list (starting from page)
158
// i - number of layer, on which we have found the item
159

160         int j;
161         MenuItem redefinitionItem = null;
162         for ( j = owners.size() - 1; j > i; j-- ) {
163             Localizable owner = (Localizable) owners.get(j);
164             Long JavaDoc ownerId = null;
165             if ( owner != null ) {
166                 ownerId = owner.getId();
167             }
168             redefinitionItem = menuManager.findRedefinitionItem(menuItem.getId(), ownerId);
169             if ( redefinitionItem != null ) {
170                 menuItem.setVisibility(redefinitionItem.getVisibility());
171             }
172         }
173
174         if ( redefinitionItem == null && menuItem.isVisibilityHeritable() ) {
175             menuItem.setVisibility(visibility);
176         } else if ( redefinitionItem != null && menuItem.isVisibilityHeritable() ) {
177             if ( j > i + 1 ) {
178                 for ( int k = j - 1; k > i; k-- ) {
179                     Localizable owner = (Localizable) owners.get(j);
180                     Long JavaDoc ownerId = null;
181                     if ( owner != null ) {
182                         ownerId = owner.getId();
183                     }
184                     redefinitionItem = menuManager.findRedefinitionItem(menuItem.getId(), ownerId);
185                     if ( redefinitionItem != null && !redefinitionItem.isVisibilityHeritable() ) {
186                         menuItem.setVisibility(redefinitionItem.getVisibility());
187                         break;
188                     }
189
190                 }
191             }
192             if ( menuItem.isVisibilityHeritable() ) {
193                 menuItem.setVisibility(visibility);
194             }
195         }
196
197         // check visibility
198
if ( menuItem.isInvisible() && deleteInvisible ) {
199             return null;
200         }
201
202         return convertToMenuComponent(owners, menuItem, localeIdentifier, deleteInvisible);
203     }
204
205     /**
206      * Processes list of menu components and completes it from elements acquired from persistence layer
207      *
208      * @param owners List of owners from which to get items
209      * @param parentItemId ID of parent component
210      * @param deleteInvisible Whether or not to delete components if they are invisible
211      * @throws MenuUtilException wraps any catched exception
212      */

213     protected List JavaDoc lookupItems(List JavaDoc owners, Long JavaDoc parentItemId, boolean deleteInvisible) throws MenuUtilException {
214
215         List JavaDoc items = new ArrayList JavaDoc();
216         try {
217
218             // iterate over list of owners
219
for ( Iterator JavaDoc i = owners.iterator(); i.hasNext(); ) {
220                 Localizable owner = (Localizable) i.next();
221                 QueryInfo queryInfo = new QueryInfo();
222                 Map JavaDoc queryParameters = new HashMap JavaDoc();
223
224                 if ( owner != null ) {
225                     queryParameters.put("ownerId", owner.getId());
226                 }
227                 queryParameters.put("parentItemId", parentItemId);
228
229                 queryInfo.setQueryParameters(queryParameters);
230
231                 List JavaDoc menuItems = menuManager.listMenuItems(queryInfo).asList();
232
233                 for ( Iterator JavaDoc j = menuItems.iterator(); j.hasNext(); ) {
234
235                     MenuItem menuItem = (MenuItem) j.next();
236
237                     // find menu item for which current one is redifinition
238
MenuItem oldItem = null;
239                     if ( menuItem.isRedefinition() ) {
240                         oldItem = findMenuItem(items, menuItem.getOrigItem().getId());
241                     }
242
243                     // modifiedOldItem is that item that is a result of 'addition'
244
// of oldItem (which is redefined) and redifinition
245
MenuItem modifiedOldItem = null;
246                     if ( oldItem != null ) {
247                         modifiedOldItem = new MenuItem();
248                         // copy properties
249
WebappUtil.copyProperties(modifiedOldItem, oldItem, request);
250                     }
251
252                     if ( menuItem.getPosition() != null && modifiedOldItem != null ) {
253                         // position is specified and that's redifinition:
254
// put it to specified position and put item that was
255
// in that position to position of redefined item
256
int pos = menuItem.getPosition().intValue();
257                         if ( pos >= items.size() ) {
258                             pos = items.size() - 1;
259                         }
260                         int oldPos = items.indexOf(oldItem);
261
262                         modifiedOldItem.setVisibility(menuItem.getVisibility());
263
264                         MenuItem tmp = (MenuItem) items.get(pos);
265                         items.set(oldPos, tmp);
266                         items.set(pos, modifiedOldItem);
267                     } else if ( menuItem.getPosition() != null && modifiedOldItem == null ) {
268                         // position is specified and that's not redifinition:
269
// just add to list in specified position
270
int pos = menuItem.getPosition().intValue();
271                         if ( pos < items.size() ) {
272                             items.add(pos, menuItem);
273                         } else {
274                             items.add(menuItem);
275                         }
276                     } else if ( menuItem.getPosition() == null && modifiedOldItem == null ) {
277                         // position is not specified and that's not redifinition:
278
// just add to the end of list
279
items.add(menuItem);
280                     } else if ( menuItem.getPosition() == null && modifiedOldItem != null ) {
281                         // position is not specified and that's redifinition:
282
// position is inherited from old item
283
int tmpPos = items.indexOf(oldItem);
284                         modifiedOldItem.setVisibility(menuItem.getVisibility());
285                         items.set(tmpPos, modifiedOldItem);
286                     }
287                 }
288             }
289
290             // delete invisible elements
291
for ( Iterator JavaDoc i = items.iterator(); i.hasNext(); ) {
292                 MenuItem menuItem = (MenuItem) i.next();
293                 if ( menuItem.isInvisible() && deleteInvisible ) {
294                     i.remove();
295                 }
296             }
297
298         } catch ( Exception JavaDoc e ) {
299             throw new MenuUtilException(e);
300         }
301         return items;
302     }
303
304
305     /**
306      * Creates hierarchy of menu components
307      *
308      * @param owners List of owners (layers)
309      * @param menuItem Menu item to convert
310      * @param deleteInvisible Whether or not to delete invisible elements
311      * @return Menu component with all childs components, with their child components and so on
312      * @throws MenuUtilException if something wrong happens
313      */

314     protected MenuComponent convertToMenuComponent(List JavaDoc owners, MenuItem menuItem, String JavaDoc localeIdentifier, boolean deleteInvisible) throws MenuUtilException {
315         MenuComponent menuComponent = new MenuComponent();
316
317         // convert item to component
318
try {
319             WebappUtil.copyProperties(menuComponent, menuItem, request);
320             menuComponent.setName(menuItem.getIdentifier());
321
322             // set roles
323
StringBuffer JavaDoc roles = null;
324             if ( menuItem.getRoles() != null && !menuItem.getRoles().isEmpty() ) {
325                 roles = new StringBuffer JavaDoc();
326                 for ( Iterator JavaDoc i = menuItem.getRoles().iterator(); i.hasNext(); ) {
327                     Role role = (Role) i.next();
328                     roles.append(role.getName());
329                     if ( i.hasNext() ) {
330                         roles.append(",");
331                     }
332                 }
333             }
334             if ( roles != null ) {
335                 menuComponent.setRoles(roles.toString());
336             } else {
337                 menuComponent.setRoles(null);
338             }
339             menuComponent.setTitle(WebappUtil.getFieldValue(menuItem.getTitle(), localeIdentifier, request, true));
340             menuComponent.setToolTip(WebappUtil.getFieldValue(menuItem.getToolTip(), localeIdentifier, request, true));
341
342             // recursive call of this method on child items
343

344             List JavaDoc childItems = lookupItems(owners, menuItem.getId(), deleteInvisible);
345
346             for ( Iterator JavaDoc i = childItems.iterator(); i.hasNext(); ) {
347                 MenuItem childItem = (MenuItem) i.next();
348                 menuComponent.addMenuComponent(convertToMenuComponent(owners, childItem, localeIdentifier, deleteInvisible));
349             }
350
351         } catch ( Exception JavaDoc e ) {
352             if ( !(e instanceof MenuUtilException) ) {
353                 throw new MenuUtilException(e);
354             } else {
355                 throw (MenuUtilException) e;
356             }
357         }
358
359         return menuComponent;
360     }
361
362     /**
363      * Looks up owners. This list contains all parent layouts of layout that
364      * have specified definition (and the given layout himself), and in the end
365      * of list there is a page with specified URI.
366      * Each owner represents a layer. Menu items can be moved or modified
367      * separately on each layer from the first parent layout to some page.
368      *
369      * @param layoutDefinition Definition of layout to lookup parents for
370      * @param pageUri URI of page.
371      * @return List of owners
372      * @throws MenuUtilException if something wrong happens while looking up owners
373      */

374     protected LinkedList JavaDoc lookupOwners(String JavaDoc layoutDefinition, String JavaDoc pageUri) throws MenuUtilException {
375         LinkedList JavaDoc owners = new LinkedList JavaDoc();
376         try {
377             if ( pageUri != null ) {
378                 // page must be in the end of list
379
PageManager pageManager = (PageManager) applicationContext.getBean(Constants.PAGE_MANAGER_BEAN);
380                 Page page = pageManager.findPageByUri(pageUri);
381                 if ( page != null ) {
382                     owners.add(page);
383                 }
384             }
385
386             // get all parent layouts for specified definition
387
LayoutManager layoutManager = (LayoutManager) applicationContext.getBean(Constants.LAYOUT_MANAGER_BEAN);
388             do {
389                 Layout layout = layoutManager.findLayoutByDefinition(layoutDefinition);
390                 if ( layout != null ) {
391                     owners.addFirst(layout);
392                 }
393                 layoutDefinition = ((HeritableComponentDefinition) TilesUtil.getDefinition(layoutDefinition, request, servletContext)).getExtends();
394             } while ( layoutDefinition != null );
395         } catch ( Exception JavaDoc e ) {
396             throw new MenuUtilException(e);
397         }
398
399         // add null as first element.
400
// null is the layer which hardcoded items belong to
401
owners.addFirst(null);
402
403         return owners;
404     }
405
406     /**
407      * Performs recursive copy of menu component
408      *
409      * @param menuComponent Menu component to get copy of
410      * @return Copy of menu component
411      */

412     public MenuComponent recursiveCopy(MenuComponent menuComponent) {
413         MenuComponent menu = new MenuComponent();
414         try {
415             MenuComponent parentMenu = menuComponent.getParent();
416             menuComponent.setParent(null);
417             WebappUtil.copyProperties(menu, menuComponent, request);
418             menuComponent.setParent(parentMenu);
419         } catch ( Exception JavaDoc e ) {
420             if ( log.isErrorEnabled() ) {
421                 log.error("Failed to perform recursive copy of menu component.");
422                 StringWriter JavaDoc sw = new StringWriter JavaDoc();
423                 e.printStackTrace(new PrintWriter JavaDoc(sw));
424                 log.error(sw.toString());
425             }
426             return null;
427         }
428         MenuComponent[] childComponents = menuComponent.getMenuComponents();
429         for ( int i = 0; i < childComponents.length; i++ ) {
430             MenuComponent component = (MenuComponent) childComponents[i];
431             MenuComponent copy = recursiveCopy(component);
432
433             // check for null in order to correctly handle cases, when copying of properties failed
434
if ( copy != null ) {
435                 menu.addMenuComponent(copy);
436             }
437         }
438
439         return menu;
440     }
441
442     /**
443      * Searches for menu item with specified ID in list
444      *
445      * @param menuItems List of menu items to search in
446      * @param id ID to search by
447      * @return Menu item or null if nothing found
448      */

449     protected MenuItem findMenuItem(List JavaDoc menuItems, Long JavaDoc id) {
450         MenuItem menuItem = null;
451         for ( Iterator JavaDoc i = menuItems.iterator(); i.hasNext(); ) {
452             menuItem = (MenuItem) i.next();
453             if ( menuItem.getId().equals(id) ) {
454                 break;
455             }
456             menuItem = null;
457         }
458         return menuItem;
459     }
460
461     /**
462      * Searches for menu component with specified name in array of menu components.
463      * If nothing is found, returns null.
464      *
465      * @param menuComponents Array of menu components to search in
466      * @param name Name to search by
467      * @return Menu component or null if none is found
468      */

469     public static MenuComponent findMenuComponent(MenuComponent[] menuComponents, String JavaDoc name) {
470         MenuComponent menuComponent = null;
471         for ( int i = 0; i < menuComponents.length; i++ ) {
472             if ( menuComponents[i].getName().equals(name) ) {
473                 menuComponent = menuComponents[i];
474                 break;
475             }
476         }
477         return menuComponent;
478     }
479
480     /**
481      * Gets appropriate value for the menu location if location is <code>null</code>.
482      * If location is <code>null</code>, and the <code>page</code> attribute
483      * exists, it's value will be set to the the value for page prepended with
484      * the context path of the application.
485      * If the <code>page</code> is <code>null</code>, and the <code>forward</code>
486      * attribute exists, it's value will be looked up in struts-config.xml.
487      * <p/>
488      * <p>This method can be applied only to dynamic elements. It sets <code>location</code>
489      * attribute of MenuItem and does not process children.
490      * </p>
491      *
492      * @param menu Menu item to set location for
493      * @throws java.net.MalformedURLException
494      */

495     public String JavaDoc getLocation(MenuItem menu, int urlType)
496             throws MalformedURLException JavaDoc {
497
498         String JavaDoc location = null;
499
500         // if the location attribute is null,
501
// then set it with a context relative page
502
// attribute if it exists
503
if ( menu.getLocation() == null ) {
504             if ( menu.getAnchor() != null ) {
505                 location = new String JavaDoc();
506                 if ( urlType == WebappConstants.URL_TYPE_DOMAIN_RELATIVE ) {
507                     location = contextPath;
508                 }
509                 location += getAnchor(menu.getAnchor());
510             } else if ( menu.getForward() != null ) {
511                 location = WebappUtil.getActionForwardURL(menu.getForward(), null, request, urlType);
512             } else if ( menu.getAction() != null ) {
513                 location = WebappUtil.getActionMappingURL(menu.getAction(), null, request, urlType, false);
514             }
515         } else {
516             location = menu.getLocation();
517             if (!WebappUtil.isAbsoluteURL(location) && !menu.getExternalLocation().booleanValue() ) {
518                 if ( !location.startsWith("/") ) {
519                     location = "/" + location;
520                 }
521             }
522         }
523
524         return location;
525     }
526
527     /**
528      * Returns the value with anchor prepended with a "/"
529      * if it is not already.
530      *
531      * @param anchor The value for the anchor.
532      */

533     protected String JavaDoc getAnchor(String JavaDoc anchor) {
534         if ( anchor.startsWith("/") ) {
535             return anchor;
536         } else {
537             anchor = "/" + anchor;
538         }
539
540         return anchor;
541     }
542
543
544     /**
545      * Initializes menu repisitory
546      */

547     public MenuRepository initializeMenuRepository() {
548         String JavaDoc menuConfig = servletContext.getInitParameter("menuConfigLocation");
549         if ( menuConfig == null ) {
550             menuConfig = "/WEB-INF/menu-config.xml";
551         }
552
553         MenuRepository menuRepository = new MenuRepository();
554         menuRepository.setLoadParam(menuConfig);
555         menuRepository.setServletContext(servletContext);
556         try {
557             menuRepository.load();
558
559             if ( log.isDebugEnabled() ) {
560                 log.debug("struts-menu initialization successfull");
561             }
562         } catch ( LoadableResourceException lre ) {
563             if ( log.isFatalEnabled() ) {
564                 log.fatal("Failure initializing struts-menu: " + lre.getMessage());
565             }
566         }
567
568         // get top-level menus from repository
569
List JavaDoc menuComponents = menuRepository.getTopMenus();
570
571         // create or update redifinitions for menu components
572
final ContentLocale defaultLocale = LocaleUtil.getInstance(servletContext).getDefaultLocale();
573         final RoleManager roleManager = (RoleManager) applicationContext.getBean(Constants.ROLE_MANAGER_BEAN);
574
575         // the following converter implementation is used to copy 'title', 'toolTip' and 'roles' properties
576
Converter structuredPropertiesConverter = new Converter() {
577             public Object JavaDoc convert(Class JavaDoc type, Object JavaDoc value) {
578
579                 if ( type == Map JavaDoc.class ) {
580                     // converting title and tooltip
581
Map JavaDoc result = new HashMap JavaDoc();
582                     result.put(defaultLocale.getIdentifier(), value);
583                     return result;
584                 }
585                 if ( type == List JavaDoc.class ) {
586                     // converting roles
587
List JavaDoc result = new ArrayList JavaDoc();
588                     if ( value != null ) {
589                         List JavaDoc roleNames = ConvertUtil.convertStringToList((String JavaDoc) value, ",", true);
590                         for ( Iterator JavaDoc j = roleNames.iterator(); j.hasNext(); ) {
591                             String JavaDoc roleName = (String JavaDoc) j.next();
592                             Role role = roleManager.retrieveRole(roleName);
593                             if ( role == null ) {
594                                 if ( log.isWarnEnabled() ) {
595                                     log.warn("Role with name '" + roleName + " not found.");
596                                 }
597                             } else {
598                                 result.add(role);
599                             }
600                         }
601                     }
602                     return result;
603                 } else {
604
605                     // we don't know how to convert into unknown class
606
return null;
607                 }
608             }
609         };
610
611         // register converter
612
ConvertUtils.register(structuredPropertiesConverter, Map JavaDoc.class);
613         ConvertUtils.register(structuredPropertiesConverter, List JavaDoc.class);
614
615         processRedifinitions(menuComponents, null);
616
617         // deregister converter
618
ConvertUtils.deregister(Map JavaDoc.class);
619         ConvertUtils.deregister(List JavaDoc.class);
620
621         if ( log.isInfoEnabled() ) {
622             log.info("Menu items from file " + menuConfig + " synchronized with database");
623         }
624
625         return menuRepository;
626     }
627
628     /**
629      * Creates references to internal pages and resources, specified in 'action', 'location', 'image' and 'altImage' attributes in
630      * menu config file. If links are external, empty list will be set.
631      *
632      * @param menuItem Menu item to set references
633      * @param menuComponent Menu component to get values of attributes from
634      */

635     protected void setLinkedObjects(MenuItem menuItem, MenuComponent menuComponent) {
636         // create refs
637
List JavaDoc linkedPages = new ArrayList JavaDoc();
638         List JavaDoc linkedResources = new ArrayList JavaDoc();
639         String JavaDoc image = menuComponent.getImage();
640         BaseObject linkedObject = WebappUtil.lookupObject(image, servletContext, contextPath);
641         if ( linkedObject != null && linkedObject instanceof ContentImage ) {
642             linkedResources.add(linkedObject);
643         }
644
645         String JavaDoc altImage = menuComponent.getAltImage();
646         if ( !GenericValidator.isBlankOrNull(altImage) && !altImage.equals(image) ) {
647             linkedObject = WebappUtil.lookupObject(menuComponent.getAltImage(), servletContext, contextPath);
648             if ( linkedObject != null && linkedObject instanceof ContentImage ) {
649                 linkedResources.add(linkedObject);
650             }
651         }
652
653         // only 'location' and 'action' attributes are checked (I have no idea how to check 'forward' attribute from the listener)
654
String JavaDoc uri = menuComponent.getLocation();
655
656         if ( uri == null || uri.length() == 0 ) {
657             uri = menuComponent.getAction();
658         }
659
660         if ( uri != null && uri.length() > 0 ) {
661             linkedObject = WebappUtil.lookupObject(uri, servletContext, contextPath);
662             if ( linkedObject != null ) {
663                 if ( linkedObject instanceof ContentResource ) {
664                     linkedResources.add(linkedObject);
665                 } else if ( linkedObject instanceof Page ) {
666                     linkedPages.add(linkedObject);
667                 }
668             }
669         }
670
671         menuItem.setLinkedResources(linkedResources);
672         menuItem.setLinkedPages(linkedPages);
673     }
674
675     /**
676      * Creates redifinitions of hardcoded menu components in database
677      *
678      * @param menuComponents List of components
679      * @param parentId ID of parent menu item
680      */

681     protected void processRedifinitions(List JavaDoc menuComponents, final Long JavaDoc parentId) {
682         MenuManager menuManager = (MenuManager) applicationContext.getBean(Constants.MENU_MANAGER_BEAN);
683
684         // delete redifinitions which do not exist in repository
685
List JavaDoc menuItems = menuManager.findMenuItemsByParentAndOwner(parentId, null);
686         if ( menuItems != null ) {
687             for ( Iterator JavaDoc i = menuItems.iterator(); i.hasNext(); ) {
688                 MenuItem menuItem = (MenuItem) i.next();
689                 MenuComponent menuComponent = MenuUtil.findMenuComponent((MenuComponent[]) menuComponents.toArray(new MenuComponent[0]), menuItem.getIdentifier());
690                 if ( menuComponent == null ) {
691                     // component does not exist in repository, so we must delete it
692
try {
693                         menuManager.deleteMenuItem(menuItem.getId());
694                     } catch ( BeanNotFoundException e ) {
695                         // bean not found - normally will never occur
696
if ( log.isErrorEnabled() ) {
697                             StringWriter JavaDoc sw = new StringWriter JavaDoc();
698                             e.printStackTrace(new PrintWriter JavaDoc(sw));
699                             log.error(sw.toString());
700                         }
701                     }
702                 }
703             }
704         }
705
706         // create non-existent redefinitions and update existent
707
int k = 0;
708         for ( Iterator JavaDoc i = menuComponents.iterator(); i.hasNext(); k++ ) {
709             MenuComponent menuComponent = (MenuComponent) i.next();
710             MenuItem menuItem = menuManager.findMenuItemByIdentifierAndParentAndOwner(menuComponent.getName(), parentId, null);
711
712             Long JavaDoc parentItemId = null;
713
714             if ( menuItem != null ) {
715                 // menu item already exists: update it
716
try {
717                     WebappUtil.copyProperties(menuItem, menuComponent);
718                 } catch ( Exception JavaDoc e ) {
719                     if ( log.isFatalEnabled() ) {
720                         StringWriter JavaDoc sw = new StringWriter JavaDoc();
721                         e.printStackTrace(new PrintWriter JavaDoc(sw));
722                         log.fatal("Failed to copy properties. Creation of redifinition skipped.");
723                         log.fatal(sw.toString());
724                     }
725                     continue;
726                 }
727
728                 menuItem.setPosition(new Integer JavaDoc(k));
729                 parentItemId = menuItem.getId();
730                 try {
731                     menuManager.updateMenuItem(menuItem, parentId, null);
732
733                     // create references
734
setLinkedObjects(menuItem, menuComponent);
735                 } catch ( Exception JavaDoc e ) {
736                     // normally this code should never be reached during normal execution of application
737
if ( log.isFatalEnabled() ) {
738                         StringWriter JavaDoc sw = new StringWriter JavaDoc();
739                         e.printStackTrace(new PrintWriter JavaDoc(sw));
740                         log.fatal("Failed to update redifinition for component: " + menuComponent.getName() + ". Skipped.");
741                         log.fatal(sw.toString());
742                     }
743                     continue;
744                 }
745             } else {
746                 // create redifinition
747
menuItem = new MenuItem();
748
749                 try {
750                     WebappUtil.copyProperties(menuItem, menuComponent);
751                 } catch ( Exception JavaDoc e ) {
752                     if ( log.isFatalEnabled() ) {
753                         StringWriter JavaDoc sw = new StringWriter JavaDoc();
754                         e.printStackTrace(new PrintWriter JavaDoc(sw));
755                         log.fatal("Failed to copy properties. Creation of redifinition skipped.");
756                         log.fatal(sw.toString());
757                     }
758                     continue;
759                 }
760
761                 menuItem.setPosition(new Integer JavaDoc(k));
762                 menuItem.setIdentifier(menuComponent.getName());
763                 menuItem.setVisibility(new Byte JavaDoc(MenuItem.VISIBILITY_VISIBLE));
764
765                 // create references
766
setLinkedObjects(menuItem, menuComponent);
767
768                 try {
769                     parentItemId = menuManager.createMenuItem(menuItem, parentId, null);
770                 } catch ( Exception JavaDoc e ) {
771                     // normally this code should never be reached during normal execution of application
772
if ( log.isFatalEnabled() ) {
773                         StringWriter JavaDoc sw = new StringWriter JavaDoc();
774                         e.printStackTrace(new PrintWriter JavaDoc(sw));
775                         log.fatal("Failed to create redifinition for component: " + menuComponent.getName() + ". Skipped.");
776                         log.fatal(sw.toString());
777                     }
778                     continue;
779                 }
780             }
781
782             // recursive call of this method to process childs
783
processRedifinitions(menuComponent.getComponents(), parentItemId);
784         }
785
786     }
787
788
789 }
790
Popular Tags