KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openi > web > controller > admin > ManageFilesFormController


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.web.controller.admin;
21
22 import org.apache.log4j.Logger;
23 import org.openi.project.DirectoryLister;
24 import org.openi.project.ProjectContext;
25 import org.openi.security.Permission;
26 import org.openi.util.*;
27 import org.openi.xml.*;
28 import org.openi.xml.BeanStorage;
29 import org.springframework.validation.BindException;
30 import org.springframework.validation.Errors;
31 import org.springframework.web.servlet.ModelAndView;
32 import org.springframework.web.servlet.mvc.SimpleFormController;
33 import java.io.*;
34 import java.util.*;
35 import javax.servlet.http.HttpServletRequest JavaDoc;
36 import javax.servlet.http.HttpServletResponse JavaDoc;
37 import javax.servlet.http.HttpSession JavaDoc;
38
39
40 /**
41  * @author Uddhab Pant <br>
42  *
43  * Controller to delete files.
44  *
45  */

46 public class ManageFilesFormController extends SimpleFormController {
47     public static final String JavaDoc NEW_FOLDER_VIEW = "newFolderConfirmView";
48     public static final String JavaDoc RENAME_FOLDER_FILE_VIEW = "renameFileConfirmView";
49     public static final String JavaDoc DELETE_FOLDERFILE_VIEW = "manageFilesConfirmView";
50     public static final String JavaDoc MAIN_VIEW = "manageFilesFormView";
51     public static final String JavaDoc EDIT_FILE_VIEW = "editFileFormView";
52
53     private static Logger logger = Logger.getLogger(ManageFilesFormController.class);
54     private ProjectContext context = null;
55     private Folder root = null;
56     private String JavaDoc xslTemplate;
57     private List editableFileTypes;
58
59     /**
60      * This method will create the command object and set it in its initial state.
61      * This method is called before the user is directed to the first page of the wizard
62      *
63      * @param request HttpServletRequest
64      * @return Object
65      * @throws Exception
66      *
67      */

68     protected Object JavaDoc formBackingObject(HttpServletRequest JavaDoc request)
69         throws Exception JavaDoc {
70         context = (ProjectContext) request.getSession()
71                                           .getAttribute("projectContext");
72
73         Map model;
74
75         try {
76             model = new HashMap();
77            
78             List modules;
79             modules = context.getProjectSubDirs();
80
81             /*context.getProjectModules(context.hasPermission(
82                Permission.DELETE_PRIVATE),
83                context.hasPermission(Permission.DELETE_PRIVATE));
84              */

85             Folder folder;
86             folder = DirectoryLister.buildFolderList(context.getProjectDirectory(),
87                     modules, true);
88
89             setupEditableFlag(folder);
90
91             root = folder;
92
93             BeanStorage store = new BeanStorage();
94             String JavaDoc folderXML = store.toXmlString(folder);
95
96             if ((getXslTemplate() == null) || (getXslTemplate() == "")) {
97                 throw new IOException(
98                     "xsl template file is not configured properly");
99             }
100
101             String JavaDoc xsl = Util.getFileContents(this.getServletContext()
102                                                   .getRealPath(getXslTemplate()));
103             String JavaDoc result = XMLTransformer.transform(xsl, folderXML);
104             model.put("FolderXML", result);
105
106             return model;
107         } catch (Exception JavaDoc e) {
108             logger.error("Exception:", e);
109             throw e;
110         }
111     }
112
113     private void setupEditableFlag(Folder folder) {
114         if (folder != null) {
115             Collection children = folder.getChildren();
116             if (children != null) {
117                 Iterator iter = children.iterator();
118                 while (iter.hasNext()) {
119                     Object JavaDoc item = iter.next();
120                     if (item instanceof FileItem) {
121                         FileItem fileItem = (FileItem) item;
122                         fileItem.setType(isEditableFile(fileItem.getPath()) ?
123                                          "text" : "");
124                     } else if (item instanceof Folder)
125                         setupEditableFlag((Folder) item);
126                 }
127             }
128         }
129     }
130
131     private boolean isEditableFile(String JavaDoc name ) {
132         if( editableFileTypes == null || name == null || "".equals(name))
133             return false;
134         int index = name.lastIndexOf(".");
135         if(index <= 0)
136             return false;
137         
138         
139         String JavaDoc extension = name.substring(index);
140         if(editableFileTypes.contains(extension.toLowerCase()))
141           return true;
142         else
143           return false;
144     }
145
146     /**
147      * Submit callback with all parameters. Called in case of submit without
148      * errors reported by the registered validator, or on every submit if no validator.
149      * @param request HttpServletRequest
150      * @param response HttpServletResponse
151      * @param command Object
152      * @param errors BindException
153      * @return ModelAndView
154      * @throws Exception
155      */

156     protected ModelAndView onSubmit(HttpServletRequest JavaDoc request,
157         HttpServletResponse JavaDoc response, Object JavaDoc command, BindException errors)
158         throws Exception JavaDoc {
159         try {
160             String JavaDoc action = request.getParameter("action");
161
162             if ("Rename".equals(action)) {
163                 return handleRename(request, response, command, errors);
164             } else if ("Delete".equals(action)) {
165                 return handleDelete(request, response, command, errors);
166             } else if ("Create".equals(action)) {
167                 return handleCreate(request, response, command, errors);
168             } else if ("Cancel".equals(action)) {
169                 return handleCancel(request, response, command, errors);
170             } else if ("Save".equals(action)) {
171                 return handleSaveFile(request, response, command, errors);
172             } else {
173                 Enumeration params = request.getParameterNames();
174
175                 while (params.hasMoreElements()) {
176                     String JavaDoc param = params.nextElement().toString();
177                     String JavaDoc path = null;
178                     String JavaDoc theaction = null;
179                     String JavaDoc actionpath = null;
180
181                     if (param.startsWith("newaction::")) {
182                         theaction = "new";
183                         actionpath = "newaction::";
184                     } else if (param.startsWith("deleteaction::")) {
185                         theaction = "delete";
186                         actionpath = "deleteaction::";
187                     } else if(param.startsWith("editaction::")) {
188                         theaction = "edit";
189                         actionpath = "editaction::";
190                     } else if (param.startsWith("renameaction::")) {
191                         theaction = "rename";
192                         actionpath = "renameaction::";
193                     }
194
195                     if (theaction != null) {
196                         path = param.substring(actionpath.length());
197
198                         int index = path.endsWith(".x") ? path.lastIndexOf(".x") : -1;
199
200                         if (index == -1) {
201                             index = path.endsWith(".y")? path.lastIndexOf(".y"): -1;
202                         }
203
204                         if (index != -1) {
205                             path = path.substring(0, index);
206                         }
207
208                         return handleClick(theaction, path, request, response,
209                             command, errors);
210                     }
211                 }
212             }
213
214             return super.onSubmit(request, response, command, errors);
215         } catch (Exception JavaDoc e) {
216             logger.error("Exception:", e);
217             throw e;
218         }
219     }
220
221     /**
222      * This method handles submit action requested by clicking icons.
223      * @param action String
224      * @param path String
225      * @param request HttpServletRequest
226      * @param response HttpServletResponse
227      * @param command Object
228      * @param errors BindException
229      * @return ModelAndView
230      * @throws Exception
231      */

232     protected ModelAndView handleClick(String JavaDoc action, String JavaDoc path,
233         HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response,
234         Object JavaDoc command, BindException errors) throws Exception JavaDoc {
235         Map model = (Map) command;
236         String JavaDoc fullpath = context.resolvePathWithProjectDir(path);
237
238         File dir = new File(fullpath);
239         String JavaDoc view = DELETE_FOLDERFILE_VIEW;
240
241         if (!dir.exists()) {
242             logger.info(path + " does not exist");
243             errors.reject("pathdoesnotexist.message");
244         }
245
246         if (!context.isPathBeneathProjectDir(fullpath)) {
247             errors.reject("outsideProjectDirError.message");
248         }
249
250         if ("delete".equals(action)) {
251             view = DELETE_FOLDERFILE_VIEW;
252
253             List files = new LinkedList();
254             List folders = new LinkedList();
255
256             if (dir.isFile()) {
257                 logger.info("File is about to delete");
258                 files.add(path);
259             } else if (dir.isDirectory()) {
260                 folders.add(path);
261
262                 //logger.info("Searching in base:" + root.getDisplayName());
263
Folder folder = Folder.findChildFolder(path, root);
264
265                 if (folder != null) {
266                     logger.info("Found folder:" + folder.getDisplayName());
267
268                     if ((folder.getChildren() != null)
269                             && (folder.getChildren().size() > 0)) {
270                         Folder.buildChildList(folder, folders, files);
271                     } else {
272                         files = null;
273                     }
274                 } else {
275                     //logger.info("Could not create Folder object for path:"
276
// + path);
277
errors.reject("direrror.message");
278                 }
279             }
280
281             model.put("foldersList", folders);
282             model.put("filesList", files);
283             model.put("selectedPath", path);
284         } else if ("new".equals(action)) {
285             view = NEW_FOLDER_VIEW;
286             model.put("selectedPath", path);
287         } else if ("rename".equals(action)) {
288             view = RENAME_FOLDER_FILE_VIEW;
289             model.put("selectedPath", path);
290             path = path.substring(0, path.length() - dir.getName().length() - 1);
291             model.put("parentPath", path);
292             model.put("fileType", dir.isDirectory() ? "dir" : "file");
293             model.put("fileName", dir.getName());
294         } else if ("edit".equals(action)) {
295             File file = new File(fullpath);
296             if(!file.isFile() || ! isEditableFile(path)) {
297                 errors.reject("notAEditableFile.message");
298             } else {
299                 model.put("textContent", Util.getFileContents(fullpath));
300                 model.put("selectedPath", path);
301                 view = EDIT_FILE_VIEW;
302             }
303         }
304
305         if (errors.hasErrors()) {
306             return showForm(request, errors, MAIN_VIEW, model);
307         } else {
308             return new ModelAndView(view, "model", model);
309         }
310     }
311
312     /**
313      * This method handles create action.
314      *
315      * @param request HttpServletRequest
316      * @param response HttpServletResponse
317      * @param command Object
318      * @param errors BindException
319      * @return ModelAndView
320      * @throws Exception
321      */

322     protected ModelAndView handleCreate(HttpServletRequest JavaDoc request,
323         HttpServletResponse JavaDoc response, Object JavaDoc command, BindException errors)
324         throws Exception JavaDoc {
325        
326         Map model = (Map) command;
327
328         String JavaDoc folderName = request.getParameter("folderName");
329         String JavaDoc selectedPath = request.getParameter("selectedPath");
330         logger.info("Creating folder:" + folderName + " on " + selectedPath);
331         model.put("selectedPath", selectedPath);
332
333         if ((selectedPath == null) || (selectedPath == "")) {
334             logger.info("Empty folder name");
335             errors.reject("emptyFolderName.message");
336         } else if (!context.isPathBeneathProjectDir(
337                     context.resolvePathWithProjectDir(selectedPath))) {
338             errors.reject("outsideProjectDirError.message");
339         } else if (!validateName(folderName, true)) {
340             errors.reject("invalidNameError.message");
341         } else {
342             File file = new File(context.resolvePathWithProjectDir(selectedPath + "/" + folderName));
343             if (file.exists()) {
344                 errors.reject("alreadyExists.message");
345             } else if (!context.addSubFolder(selectedPath, folderName)) {
346                 logger.info("Could not create folder:" + folderName);
347                 errors.reject("createError.message");
348             }
349         }
350
351         if (errors.hasErrors()) {
352             model.put("selectedPath", selectedPath);
353             model.put("folderName", folderName);
354
355             return showForm(request, errors, NEW_FOLDER_VIEW, model);
356         } else {
357             return new ModelAndView(getSuccessView());
358         }
359     }
360
361     /**
362      * This method handles delete action.
363      *
364      * @param request HttpServletRequest
365      * @param response HttpServletResponse
366      * @param command Object
367      * @param errors BindException
368      * @return ModelAndView
369      * @throws Exception
370      */

371     protected ModelAndView handleDelete(HttpServletRequest JavaDoc request,
372         HttpServletResponse JavaDoc response, Object JavaDoc command, BindException errors)
373         throws Exception JavaDoc {
374         
375         Map model = (Map) command;
376         String JavaDoc path = request.getParameter("selectedPath");
377         String JavaDoc[] files = request.getParameterValues("filesList");
378
379         if ((path == null) || (path == "")) {
380             errors.reject("selectFile.message");
381         }
382
383         if (!context.isPathBeneathProjectDir(context.resolvePathWithProjectDir(
384                         path))) {
385             errors.reject("outsideProjectDirError.message");
386         } else {
387             if (!context.removeFileFolder(path)) {
388                 errors.reject("fileDeleteError");
389             }
390         }
391
392         if (errors.hasErrors()) {
393             model.put("filesList", files);
394             model.put("foldersList", request.getParameterValues("foldersList"));
395             model.put("selectedPath", path);
396
397             return showForm(request, errors, DELETE_FOLDERFILE_VIEW, model);
398         } else {
399             return new ModelAndView(getSuccessView());
400         }
401     }
402
403     /**
404      * handles rename action
405      * @param request HttpServletRequest
406      * @param response HttpServletResponse
407      * @param command Object
408      * @param errors BindException
409      * @return ModelAndView
410      * @throws Exception
411      */

412     protected ModelAndView handleRename(HttpServletRequest JavaDoc request,
413         HttpServletResponse JavaDoc response, Object JavaDoc command, BindException errors)
414         throws Exception JavaDoc {
415         Map model = (Map) command;
416         String JavaDoc path = request.getParameter("selectedPath");
417         String JavaDoc newname = request.getParameter("folderName");
418
419         if (!context.isPathBeneathProjectDir(context.resolvePathWithProjectDir(
420                         path))) {
421             errors.reject("outsideProjectDirError.message");
422         } else {
423             if ((newname == null) || (newname == "")) {
424                 errors.reject("emptyFolderName.message");
425             } else {
426                 File file = new File(context.resolvePathWithProjectDir(path));
427
428                 if (!file.exists()) {
429                     errors.reject("pathdoesnotexist.message");
430                 } else if (!validateName(newname, file.isDirectory())) {
431                     errors.reject("invalidNameError.message");
432                 } else {
433                     newname = newname.replace(' ', '_');
434                     File newfile = new File(file.getParentFile().getPath()
435                             + "/" + newname);
436                     
437                     if (newfile.exists()) {
438                         errors.reject("alreadyExists.message");
439                     } else if (!context.renameFileFolder(path, newname)) {
440                         errors.reject("renameError.message");
441                     }
442                 }
443             }
444         }
445
446         if (errors.hasErrors()) {
447             model.put("selectedPath", path);
448
449             File dir = new File(path);
450             path = path.substring(0, path.length() - dir.getName().length() - 1);
451             model.put("parentPath", path);
452             model.put("fileType", dir.isDirectory() ? "dir" : "file");
453             model.put("fileName", newname);
454
455             return showForm(request, errors, RENAME_FOLDER_FILE_VIEW, model);
456         } else {
457             return new ModelAndView(getSuccessView());
458         }
459     }
460
461     /**
462      * Saves edited text file
463      * @param request HttpServletRequest
464      * @param response HttpServletResponse
465      * @param command Object
466      * @param errors BindException
467      * @return ModelAndView
468      * @throws Exception
469      */

470     protected ModelAndView handleSaveFile(HttpServletRequest JavaDoc request,
471                                           HttpServletResponse JavaDoc response,
472                                           Object JavaDoc command, BindException errors) throws
473             Exception JavaDoc {
474
475         
476         String JavaDoc path = request.getParameter("selectedPath");
477         String JavaDoc content = request.getParameter("textContent");
478
479         if (!context.isPathBeneathProjectDir(context.resolvePathWithProjectDir(
480                 path))) {
481             errors.reject("outsideProjectDirError.message");
482         } else {
483             if (content == null) {
484                 logger.debug("content is null");
485                 errors.reject("nullFileContent.message");
486             } else {
487                 File file = new File(context.resolvePathWithProjectDir(path));
488
489                 if (!file.exists()) {
490                     logger.debug("path does not exists");
491                     errors.reject("pathdoesnotexist.message");
492                 } else {
493                    context.saveTextFileContent(path, content);
494                 }
495             }
496         }
497         return new ModelAndView(getSuccessView());
498     }
499
500     /**
501      * This method handles cancel action and redirects to manage file page.
502      *
503      * @param request HttpServletRequest
504      * @param response HttpServletResponse
505      * @param command Object
506      * @param errors BindException
507      * @return ModelAndView
508      * @throws Exception
509      */

510     protected ModelAndView handleCancel(HttpServletRequest JavaDoc request,
511         HttpServletResponse JavaDoc response, Object JavaDoc command, BindException errors)
512         throws Exception JavaDoc {
513         //return super.onSubmit(request, response, command, errors);
514
return new ModelAndView(getSuccessView());
515     }
516
517     private boolean validateName(String JavaDoc name, boolean isFolder) {
518         if ((name == null) || ("".equals(name))) {
519             return false;
520         }
521
522         if (name.indexOf("..") != -1) {
523             return false;
524         }
525
526         if (/*
527              * !isFolder &&
528              */
((name.indexOf("/") != -1) || (name.indexOf("\\") != -1))) {
529             return false;
530         }
531         boolean alphaContained = false;
532         for (int i = 0; i < name.length(); i++) {
533             char c = name.charAt(i);
534             if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
535                 alphaContained = true;
536                 break;
537             }
538         }
539
540         return alphaContained;
541     }
542
543     /**
544      * set by spring
545      *
546      * @param xslTemplate
547      * String
548      */

549     public void setXslTemplate(String JavaDoc xslTemplate) {
550         this.xslTemplate = xslTemplate;
551     }
552
553     public void setEditableFileTypes(List editableFileTypes) {
554         this.editableFileTypes = editableFileTypes;
555     }
556
557     public String JavaDoc getXslTemplate() {
558         return xslTemplate;
559     }
560
561     public List getEditableFileTypes() {
562         return editableFileTypes;
563     }
564
565
566     /**
567      * used by test case
568      * @return Folder
569      */

570     public Folder getFolderRoot() {
571         return this.root;
572     }
573 }
574
Popular Tags