KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openi > menu > MenuBuilder


1 /*********************************************************************************
2  * The contents of this file are subject to the OpenI Public License Version 1.0
3  * ("License"); You may not use this file except in compliance with the
4  * License. You may obtain a copy of the License at
5  * http://www.openi.org/docs/LICENSE.txt
6  *
7  * Software distributed under the License is distributed on an "AS IS" basis,
8  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
9  * the specific language governing rights and limitations under the License.
10  *
11  * The Original Code is: OpenI Open Source
12  *
13  * The Initial Developer of the Original Code is Loyalty Matrix, Inc.
14  * Portions created by Loyalty Matrix, Inc. are
15  * Copyright (C) 2005 Loyalty Matrix, Inc.; All Rights Reserved.
16  *
17  * Contributor(s): ______________________________________.
18  *
19  ********************************************************************************/

20 package org.openi.menu;
21
22 import org.apache.log4j.*;
23 import java.io.*;
24 import java.util.*;
25
26
27 /**
28  * @author plucas
29  * @version $Revision: 1.6.2.1 $ $Date: 2006/05/25 19:01:35 $
30  *
31  * Generates menu tree by recursing a list of directories. It is the responsibility of the caller
32  * to properly pass in the list of directories. MenuBuilder does not do this, it only builds
33  * menu's. Web layer should not make calls to this class.
34  *
35  */

36 public class MenuBuilder {
37     private static Logger logger = LogManager.getLogger(MenuBuilder.class);
38
39     // private String baseDir;
40
// TODO: make configurable (project level)
41

42     public MenuBuilder() {
43         try {
44             jbInit();
45         } catch (Exception JavaDoc ex) {
46             ex.printStackTrace();
47         }
48     }
49
50     /**
51      *
52      * Generates menu tree by recursing a list of directories. It is the responsibility of
53      * the caller to properly pass in the list of directories. This list of directories is relative to
54      * the baseDirName. The baseDirName and the relative subDirName are needed to create
55      * the url.
56      *
57      * When the menu is generated, the top level directories will remain in the list order.
58      * All subdirectories will be in the order they are found in the file system.
59      * (TODO: configure order? Pass in a sorter param?)
60      *
61      * @return Menu tree structure
62      * @throws IOException for a bad base directory
63      */

64     public Menu build(String JavaDoc baseDirName, List menuSubDirs)
65         throws IOException {
66         long start = System.currentTimeMillis();
67         logger.debug("attempting to build menu using baseDir=" + baseDirName);
68
69         Menu root = new Menu();
70
71         if ((baseDirName == null) || (menuSubDirs == null)) {
72             logger.error("baseDirName is null");
73         }
74
75         File baseDir = new File(baseDirName);
76
77         if ((baseDir == null) || !baseDir.exists() || !baseDir.isDirectory()) {
78             throw new IOException(
79                 "baseDir is null, or does not exist, or is not a directory: "
80                 + baseDir);
81         }
82
83         // logger.debug("dir exists: " + baseDir.getCanonicalPath());
84
Iterator dirs = menuSubDirs.iterator();
85         logger.debug("building menu using: " + menuSubDirs);
86
87         while (dirs.hasNext()) {
88             String JavaDoc currentSubDir = (String JavaDoc) dirs.next();
89
90             // logger.debug("recursing: " + currentSubDir);
91
recurse(root, baseDir, new File(baseDir, currentSubDir));
92         }
93
94         logger.info("created menu tree in "
95             + String.valueOf(System.currentTimeMillis() - start) + "ms");
96
97         return root;
98     }
99
100     /**
101      * Recursively adds directory as menu and file as menu item into
102      * parent menu.
103      *
104      * @param parent Menu
105      * @param baseDir - root directory
106      * @param module Directory to be traversed
107      */

108     private void recurse(Menu parent, File baseDir, File module) {
109         try {
110             // logger.debug("recursing: " + module.getCanonicalPath());
111
if (module.isDirectory()) {
112                 // System.out.println("found a dir: " + file.getCanonicalPath());
113
// create a directory node and add to parent
114
Menu menu = new Menu();
115                 menu.setDisplayName(constructDisplayName(module));
116                 parent.addSubMenu(menu);
117
118                 File[] children = module.listFiles();
119                 java.util.Arrays.sort(children);
120
121                 for (int i = 0; i < children.length; i++) {
122                     recurse(menu, baseDir, children[i]);
123                 }
124             } else {
125                 handleFile(parent, baseDir, module);
126             }
127         } catch (IOException e) {
128             logger.error("trouble creating menu", e);
129         }
130     }
131
132     /**
133      * Adds file as menu item into parent
134      * @param parent Menu
135      * @param file File
136      * @throws IOException
137      */

138     private void handleFile(Menu parent, File baseDir, File file)
139         throws IOException {
140         // System.out.println(file.getCanonicalPath());
141
if (file.exists()) {
142             MenuItem menuItem = new MenuItem();
143             menuItem.setDisplayName(constructDisplayName(file));
144             menuItem.setUrl(constructUrl(baseDir, file));
145             parent.addMenuItem(menuItem);
146         }
147     }
148
149     /**
150      * Constructs display name for Directory/file
151      * @param file File
152      * @return String
153      * @throws IOException
154      */

155     public static String JavaDoc constructDisplayName(File file)
156         throws IOException {
157         return constructDisplayName(file.getName());
158     }
159     
160     /**
161      * Overloaded to just take a string, parse out the directory name. Initial
162      * usage for constructing display names for missing analysis.
163      *
164      * @param filename
165      * @return
166      * @throws IOException
167      */

168     public static String JavaDoc constructDisplayName(String JavaDoc filename)
169         throws IOException {
170         // logger.debug("constructDisplayName using file: " + file.getCanonicalPath());
171
String JavaDoc displayName = filename;
172         String JavaDoc extension = "";
173
174         //remove extension
175
int dot = displayName.lastIndexOf(".");
176
177         if (dot >= 0) {
178             //if (displayName.length() <= (dot + 1)) {
179
extension = displayName.substring(dot + 1);
180             //}
181
displayName = displayName.substring(0, dot);
182         }
183
184         //not displaying extension of analysis, html and jsp files.
185
if ((extension.length() > 0)
186                 && (!(extension.equalsIgnoreCase("analysis")
187                 || extension.equalsIgnoreCase("html")
188                 || extension.equalsIgnoreCase("htm")
189                 || extension.equalsIgnoreCase("jsp")))) {
190             displayName = displayName + " (" + extension + ")";
191         }
192         
193         int lastSlash = displayName.lastIndexOf('/');
194         if(lastSlash >=0 && lastSlash < (displayName.length()-1) ){
195             displayName = displayName.substring(lastSlash+1, displayName.length());
196         }
197
198         //remove underscores
199
return displayName.replace('_', ' ');
200     }
201
202     /**
203      * Constructs analysis url for menu item of file.
204      * @param file File
205      * @return String
206      * @throws IOException
207      */

208     private String JavaDoc constructUrl(File baseDir, File file)
209         throws IOException {
210         String JavaDoc relativeUrl = "";
211         String JavaDoc extension = "";
212         String JavaDoc url = "";
213
214         //get extension
215
int dot = file.getName().lastIndexOf(".");
216
217         if (dot >= 0) {
218             extension = file.getName().substring(dot + 1);
219         }
220
221
222         // strip the baseDir text
223
int len = baseDir.getCanonicalPath().length();
224         relativeUrl = file.getCanonicalPath().substring(len);
225
226         // remove starting slash, if it has one
227
if ((relativeUrl.charAt(0) == '/') || (relativeUrl.charAt(0) == '\\')) {
228             relativeUrl = relativeUrl.substring(1);
229         }
230
231         // replace slashes
232
relativeUrl = relativeUrl.replace('\\', '/');
233
234         // logger.debug("result relativeUrl: " + relativeUrl);
235
return relativeUrl;
236     }
237
238     private void jbInit() throws Exception JavaDoc {
239     }
240 }
241
Popular Tags