KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openi > project > ProjectContext


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.project;
21
22 import org.apache.log4j.*;
23
24 import org.openi.analysis.Analysis;
25 import org.openi.analysis.AnalysisGenerator;
26 import org.openi.analysis.ChangeLog;
27 import org.openi.analysis.Datasource;
28 import org.openi.analysis.LogEntry;
29
30 import org.openi.application.Application;
31
32 import org.openi.menu.*;
33
34 import org.openi.security.Permission;
35
36 import org.openi.util.NameValue;
37 import org.openi.util.Util;
38
39 import org.openi.xml.BeanStorage;
40
41 import java.io.File JavaDoc;
42 import java.io.FileInputStream JavaDoc;
43 import java.io.IOException JavaDoc;
44
45 import java.util.AbstractList JavaDoc;
46 import java.util.Date 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.Map JavaDoc;
52 import java.util.Properties JavaDoc;
53 import java.util.zip.ZipEntry JavaDoc;
54 import java.util.zip.ZipOutputStream JavaDoc;
55 import java.io.FileOutputStream JavaDoc;
56 import java.io.FileNotFoundException JavaDoc;
57 import org.openi.stat.r.*;
58
59 import com.tonbeller.jpivot.olap.model.OlapException;
60 /**
61  * @author plucas
62  *
63  * TODO To change the template for this generated type comment go to
64  * Window - Preferences - Java - Code Style - Code Templates
65  */

66 public class ProjectContext {
67     public static final String JavaDoc ALL_USERS = "public";
68     private static Logger logger = LogManager.getLogger(ProjectContext.class);
69
70     /**
71      * this is the base directory for all projects
72      */

73     private String JavaDoc baseDirectory; // XXX: should be a file?
74
private String JavaDoc username;
75     private Project project;
76
77     /**
78      * @param project
79      * @param baseDirectory
80      * @param username
81      */

82     public ProjectContext(Project project, String JavaDoc baseDirectory,
83                           String JavaDoc username) {
84         this.baseDirectory = baseDirectory;
85         this.username = username;
86         this.project = project;
87     }
88
89     /**
90      * @return Returns the baseDirectory.
91      */

92     public String JavaDoc getBaseDirectory() {
93         return baseDirectory;
94     }
95
96     /**
97      * @param baseDirectory The baseDirectory to set.
98      */

99     public void setBaseDirectory(String JavaDoc baseDirectory) {
100         this.baseDirectory = baseDirectory;
101     }
102
103     public String JavaDoc getProjectDirectory() {
104         return this.getBaseDirectory() + "/" +
105                 this.getProject().getProjectId();
106     }
107
108     /**
109      * @return Returns the project.
110      */

111     public Project getProject() {
112         return project;
113     }
114
115     /**
116      * @param project The project to set.
117      */

118     public void setProject(Project project) {
119         this.project = project;
120     }
121
122     /**
123      * @return Returns the username.
124      */

125     public String JavaDoc getUsername() {
126         return username;
127     }
128
129     /**
130      * @param username The username to set.
131      */

132     public void setUsername(String JavaDoc username) {
133         this.username = username;
134     }
135
136     /**
137      * returns datasource object from datasource name
138      * @param datasourceName String
139      * @return Datasource
140      */

141     public Object JavaDoc getDatasourceObject(String JavaDoc datasourceName) {
142         return project.getDataSourceMap().get(datasourceName);
143     }
144
145     /**
146      * returns datasource object from datasource name
147      * @param datasourceName String
148      * @return Datasource
149      */

150     public Datasource getDatasource(String JavaDoc datasourceName) {
151         return (Datasource) project.getDataSourceMap().get(datasourceName);
152     }
153
154     /**
155      *
156      * @param datasourceKey String
157      * @param dataSource Datasource
158      */

159     public void setDatasource(String JavaDoc datasourceKey, Object JavaDoc dataSource) {
160         synchronized (this) {
161             this.project.getDataSourceMap().put(datasourceKey, dataSource);
162         }
163     }
164
165     /**
166      * returns all available JdbcDatasource
167      * @return Map
168      */

169     public Map JavaDoc getJdbcDatasourceMap() {
170         Map JavaDoc map = new HashMap JavaDoc();
171         Iterator JavaDoc iter = project.getDataSourceMap().keySet().iterator();
172
173         while (iter.hasNext()) {
174             String JavaDoc key = (String JavaDoc) iter.next();
175             Object JavaDoc obj = project.getDataSourceMap().get(key);
176
177             if ((obj != null) && obj instanceof JdbcDatasource) {
178                 map.put(key, obj);
179             }
180         }
181
182         return map;
183     }
184
185     /**
186      * returns all available xmla datasource
187      * @return Map
188      */

189     public Map JavaDoc getXmlaDatasourceMap() {
190         Map JavaDoc map = new HashMap JavaDoc();
191         Iterator JavaDoc iter = project.getDataSourceMap().keySet().iterator();
192
193         while (iter.hasNext()) {
194             String JavaDoc key = (String JavaDoc) iter.next();
195             Object JavaDoc obj = project.getDataSourceMap().get(key);
196
197             if ((obj != null) && obj instanceof Datasource) {
198                 map.put(key, obj);
199             }
200         }
201
202         return map;
203     }
204
205     /**
206      * returns jdbc connection properties of specified analysis. returns default one if datasource is not
207      * specified for analysis
208      * @return Properties
209      */

210     public Properties JavaDoc getJdbcDataSourceProperties(Analysis analysis) {
211         JdbcDatasource jdbcSource = getJdbcDatasource(analysis.getDrillthroughDatasource());
212         if(jdbcSource == null) {
213             throw new NullPointerException JavaDoc("There is no configuration for jdbc datasource in project");
214         }
215         Properties JavaDoc properties = new Properties JavaDoc();
216
217         properties.put("driver", jdbcSource.getDriverClassName());
218         properties.put("url", jdbcSource.getUrl());
219         properties.put("user", jdbcSource.getUsername());
220         properties.put("password", jdbcSource.getPassword());
221
222         return properties;
223     }
224     
225     /**
226      * returns jdbc connection properties. returns default one if datasourcename is not
227      * specified explicity
228      * @return Properties
229      */

230     public Properties JavaDoc getJdbcDataSourceProperties(String JavaDoc dataSourceName) {
231         JdbcDatasource jdbcSource = getJdbcDatasource(dataSourceName);
232         if(jdbcSource == null) {
233             throw new NullPointerException JavaDoc("There is no configuration for jdbc datasource in project");
234         }
235         Properties JavaDoc properties = new Properties JavaDoc();
236
237         properties.put("driver", jdbcSource.getDriverClassName());
238         properties.put("url", jdbcSource.getUrl());
239         properties.put("user", jdbcSource.getUsername());
240         properties.put("password", jdbcSource.getPassword());
241
242         return properties;
243     }
244     /**
245      * returns jdbc datasource. Returns default one, if dataSourceName is not specified
246      * @param analysis Analysis
247      * @return JdbcDatasource
248      */

249     public JdbcDatasource getJdbcDatasource(String JavaDoc dataSourceName) {
250         
251         if (dataSourceName != null && !"".equals(dataSourceName)) {
252             Object JavaDoc datasource = getDatasourceObject(dataSourceName);
253             if(datasource instanceof JdbcDatasource)
254                 return (JdbcDatasource)datasource;
255             else
256                 throw new ClassCastException JavaDoc("Not a valid jdbc datasource name");
257
258         } else {
259             Map JavaDoc dsMap = getJdbcDatasourceMap();
260             if (dsMap != null && dsMap.size() > 0)
261                 return (JdbcDatasource) dsMap.values().iterator().next();
262         }
263         return null;
264
265     }
266
267     /**
268      * To remove datasource from project
269      * @param datasourceName String
270      * @return boolean
271      */

272     public void deleteDatasource(String JavaDoc datasourceName) {
273         try {
274             this.project.getDataSourceMap().remove(datasourceName);
275             this.saveProject();
276         } catch (Exception JavaDoc e) {
277         }
278     }
279
280     /**
281      * return JdbcDatasource object of specified template-i.e .jrxml file
282      * @param template String
283      * @return JdbcDatasource
284      */

285     public JdbcDatasource getJasperDatasource(String JavaDoc template) {
286         if (project.getJdbcMap() == null) {
287             return null;
288         }
289
290         Iterator JavaDoc iter = project.getJdbcMap().keySet().iterator();
291
292         while (iter.hasNext()) {
293             String JavaDoc key = (String JavaDoc) iter.next();
294
295             if (key.equalsIgnoreCase(template)) {
296                 String JavaDoc datasource = (String JavaDoc) project.getJdbcMap().get(key);
297
298                 if ((datasource != null) && !datasource.equals("")) {
299                     Object JavaDoc obj = getDatasourceObject(datasource);
300
301                     if ((obj != null) && obj instanceof JdbcDatasource) {
302                         return (JdbcDatasource) obj;
303                     }
304                 }
305             }
306         }
307
308         return null;
309     }
310
311     /**
312      * Determines appropriate base project directory, and which directories to include in menu
313      * delegates all menu building to the MenuBuilder
314      *
315      * @return menu appropriate for the given project context
316      * (project context implies user context)
317      *
318      * @throws IOException for a bad project directory
319      */

320     public Menu buildMenu() throws IOException JavaDoc {
321         List JavaDoc modules = getProjectModules(false, true);
322
323         // personal list will always be done in here (not configurable):
324
// modules.add("/" + username);
325
List JavaDoc tmp = new LinkedList JavaDoc(modules);
326         tmp.add("/" + username.toLowerCase());
327
328         MenuBuilder builder = new MenuBuilder();
329         Menu menu = builder.build(this.getProjectDirectory(), tmp);
330
331         menu.addSubMenu(createAdminMenu());
332
333         return menu;
334     }
335
336     /**
337      * Method which creates admin menu.
338      * Refactored to create admin submenu based on project.xml configuration.
339      *
340      * @return Menu
341      */

342     private Menu createAdminMenu() {
343         logger.debug("creating admin menu");
344
345         // refactor so that project.xml can configure other submenu's, in addition to Admin
346
Menu adminMenu = new Menu("Administration");
347         Map JavaDoc config = this.getProject().getMenuConfig();
348
349         // notice permissions are heirarchical and inclusive:
350
// app admins have all permissions of all users
351
// project admins have permissions + all lower users
352
// project users only have permissions of project users
353
if (Util.isItemInList(this.getUsername(),
354                               Application.getInstance().getApplicationAdmins())) {
355             this.addItemList(adminMenu, (List JavaDoc) config.get("appAdminList"));
356             this.addItemList(adminMenu, (List JavaDoc) config.get("projectAdminList"));
357             this.addItemList(adminMenu, (List JavaDoc) config.get("projectUserList"));
358         }
359
360         if (Util.isItemInList(this.getUsername(),
361                               this.getProject().getProjectAdmins())) {
362             this.addItemList(adminMenu, (List JavaDoc) config.get("projectAdminList"));
363             this.addItemList(adminMenu, (List JavaDoc) config.get("projectUserList"));
364         }
365
366         if (Util.isItemInList(this.getUsername(),
367                               this.getProject().getProjectUsers())) {
368             this.addItemList(adminMenu, (List JavaDoc) config.get("projectUserList"));
369         }
370
371         return adminMenu;
372     }
373
374     private void addItemList(Menu menu, List JavaDoc list) {
375         Iterator JavaDoc items = list.iterator();
376
377         while (items.hasNext()) {
378             MenuItem item = (MenuItem) items.next();
379             menu.addMenuItem(item);
380         }
381
382         // return menu;
383
}
384
385     public void savePublic(String JavaDoc relativeUrl, Analysis analysis,
386                            String JavaDoc comment) throws IOException JavaDoc {
387         logger.debug("trying to save public analysis for: " +
388                      this.getProject().getProjectId());
389
390         String JavaDoc filename = ALL_USERS + "/" + relativeUrl;
391         save(filename, analysis, comment);
392     }
393
394     public void savePersonal(String JavaDoc relativeUrl, Analysis analysis,
395                              String JavaDoc comment) throws IOException JavaDoc {
396         logger.debug("trying to save personal analysis for user: " +
397                      this.getUsername().toLowerCase());
398
399         String JavaDoc relativeFilename = this.getUsername().toLowerCase() + "/" +
400                                   relativeUrl;
401         save(relativeFilename, analysis, comment);
402     }
403
404     public void save(String JavaDoc relativeFilename, Analysis analysis, String JavaDoc comment) throws
405             IOException JavaDoc {
406         String JavaDoc filename = this.getProjectDirectory() + "/" + relativeFilename;
407         logger.info("saving: " + filename);
408
409         BeanStorage storage = new BeanStorage();
410         storage.saveBeanToFile(filename, analysis);
411
412         ChangeLog changelog = this.getChangeLog();
413         changelog.addLogEntry(new LogEntry(relativeFilename, new Date JavaDoc(),
414                                            this.getUsername(), comment));
415         storage.saveBeanToFile(this.getChangeLogFilename(), changelog);
416     }
417
418     /**
419      * @param relativeUrl
420      */

421     public void deleteAnalysis(String JavaDoc relativeUrl) {
422         //create filename
423
// String filename = createFilename(baseDir, analysisConfigName);
424
String JavaDoc filename = this.getProjectDirectory() + "/" + relativeUrl;
425         logger.debug("trying to delete analysis using filename: " + filename);
426
427         BeanStorage storage = new BeanStorage();
428         storage.deleteFile(filename);
429     }
430
431     public Analysis restoreAnalysis(String JavaDoc analysisConfigName) throws
432             IOException JavaDoc {
433         //create filename
434
String JavaDoc filename = this.getProjectDirectory() + "/" +
435                           analysisConfigName;
436         logger.debug("trying to restore analysis using filename: " + filename);
437
438         BeanStorage storage = new BeanStorage();
439
440         //Analysis as = new Analysis();
441
Analysis analysis = (Analysis) storage.restoreBeanFromFile(filename,
442                 new Analysis());
443         analysis.setAnalysisTitle(MenuBuilder.constructDisplayName(
444                 new File JavaDoc(filename)));
445
446         return analysis;
447     }
448
449     /**
450      * Save project
451      * @throws IOException
452      */

453     public void saveProject() {
454         String JavaDoc filename = this.getProjectDirectory() + "/project.xml";
455         logger.info("saving: " + filename);
456
457         BeanStorage storage = new BeanStorage();
458
459         try {
460             storage.saveBeanToFile(filename, this.project);
461         } catch (IOException JavaDoc e) {
462             logger.error(e);
463         }
464     }
465
466     /**
467      * for getChangeLog - need to trap IOException, this is non critical
468      *
469      * @return
470      */

471     public ChangeLog getChangeLog() {
472         ChangeLog changelog = null;
473         String JavaDoc filename = this.getChangeLogFilename();
474         logger.debug("trying to restore changelog using filename: " + filename);
475
476         BeanStorage storage = new BeanStorage();
477
478         try {
479             changelog = (ChangeLog) storage.restoreBeanFromFile(filename);
480         } catch (IOException JavaDoc e) {
481             logger.info(e);
482             changelog = new ChangeLog();
483         }
484
485         return changelog;
486     }
487
488     private String JavaDoc getChangeLogFilename() {
489         return this.getProjectDirectory() + "/changelog.xml";
490     }
491
492     /**
493      * Method to check user's permission
494      *
495      * @param permission Permission
496      * @return boolean
497      */

498     public boolean hasPermission(Permission permission) {
499         boolean granted = false;
500
501         //if application admin
502
if (Util.isItemInList(username,
503                               Application.getInstance().getApplicationAdmins())) {
504             //if has permission
505
if (Util.isItemInList(permission.toString(),
506                                   Application.getInstance()
507                                   .getApplicationAdminPermissions())) {
508                 granted = true;
509             }
510         }
511         //if project admin
512
else if (Util.isItemInList(username, project.getProjectAdmins())) {
513             //if has permission
514
if (Util.isItemInList(permission.toString(),
515                                   Application.getInstance().
516                                   getProjectAdminPermissions())) {
517                 granted = true;
518             }
519         }
520         //if project user
521
else if (Util.isItemInList(username, project.getProjectUsers())) {
522             //if has permission
523
if (Util.isItemInList(permission.toString(),
524                                   Application.getInstance().
525                                   getProjectUserPermissions())) {
526                 granted = true;
527             }
528         }
529         // if project read only user
530
else if (Util.isItemInList(username, project.getProjectReadOnlyUsers())) {
531            
532             //Read Only users always have Read_Only right
533
if(permission == Permission.READ_ONLY) {
534                 granted = true;
535             }
536             else if (Util.isItemInList(permission.toString(),
537                                   Application.getInstance().
538                                   getProjectUserPermissions())) {
539                 granted = true;
540             }
541             
542         }
543         
544         return granted;
545     }
546
547     /**
548      * Creates a directory below this project context's projectDirectory. Will not attempt
549      * to create a directory that already exists.
550      * @param relativeDirectoryName
551      */

552     public synchronized void createDirectory(String JavaDoc relativeDirectoryName) {
553         File JavaDoc newDir = new File JavaDoc(this.getProjectDirectory() + "/" +
554                                relativeDirectoryName);
555
556         if (!newDir.exists()) {
557             try {
558                 logger.info("creating new subdirectory: " +
559                             newDir.getCanonicalPath());
560             } catch (IOException JavaDoc e) {
561                 logger.error(e);
562             }
563
564             boolean result = newDir.mkdir();
565             logger.debug("directory create result: " + result);
566         }
567     }
568
569     /**
570      * return list of accessible modules(folders) for the project user
571      * @return List module list
572      */

573     public List JavaDoc getProjectModules(boolean includePrivate, boolean includePublic) {
574         List JavaDoc modules = new LinkedList JavaDoc();
575         Iterator JavaDoc iterator = this.project.getModules().iterator();
576
577         while (iterator.hasNext()) {
578             Module module = (Module) iterator.next();
579             String JavaDoc folderName = module.getFolderName().toLowerCase();
580
581             if (!includePublic &&
582                 (folderName.startsWith("public") ||
583                  folderName.startsWith("/public"))) {
584                 continue;
585             }
586
587             if (isModuleAllowed(module)) {
588                 modules.add(module.getFolderName());
589             }
590         }
591
592         if (includePrivate) {
593             modules.add(this.username);
594         }
595
596         return modules;
597     }
598
599     /**
600      * test whether path is allowed or not based on folder security
601      * @param path String
602      * @return boolean
603      */

604     public boolean isPathAllowed(String JavaDoc path) {
605         path = extractModulePath(path);
606
607         // need mdoules to check folder security
608
Iterator JavaDoc iterator = project.getModules().iterator();
609
610         //iterate and test whether the path starts with module's folder or not
611
// and test for permission if it is
612
while (iterator.hasNext()) {
613             Module module = (Module) iterator.next();
614
615             if (path.startsWith(module.getFolderName())) {
616                 // not permitted means path is not allowed
617
if (!isModuleAllowed(module)) {
618                     return false;
619                 }
620             }
621         }
622
623         return true;
624     }
625
626     /**
627      * test whether path is allowed or not based on folder security and user's permission.
628      * returns true if it is allowed
629      * @param path String
630      * @param permission Permission
631      * @return boolean
632      */

633     public boolean isPathAllowed(String JavaDoc path, Permission permission) {
634         //test folder security
635
if (!isPathAllowed(path)) {
636             return false;
637         }
638
639         path = extractModulePath(path);
640
641         //ok folder is permitted.
642
// test whether user roles have any public restriction
643
if (path.toLowerCase().startsWith("public")) {
644             if (permission.equals(Permission.DELETE_PUBLIC) ||
645                 permission.equals(Permission.SAVE_PUBLIC)) {
646                 if (!hasPermission(permission)) {
647                     return false;
648                 }
649             }
650         }
651
652         // test whether user roles have any private restriction
653
if (path.startsWith(getUsername())) {
654             if (permission.equals(Permission.DELETE_PRIVATE) ||
655                 permission.equals(Permission.SAVE_PRIVATE)) {
656                 if (!hasPermission(permission)) {
657                     return false;
658                 }
659             }
660         }
661
662         return true;
663     }
664
665     /**
666      * extracts path from base directory
667      * @param path String
668      * @return String
669      */

670     public String JavaDoc extractModulePath(String JavaDoc path) {
671         if (path.toLowerCase().startsWith(getProjectDirectory().toLowerCase())) {
672             path = path.substring(getProjectDirectory().length());
673         }
674
675         return path;
676     }
677
678     private boolean isModuleAllowed(Module module) {
679         String JavaDoc users = module.getAllowedUsers();
680
681         //allow everyone if allowed users is empty
682
if ((users == null) || users.trim().equals("")) {
683             return true;
684         }
685
686         if (module != null) {
687             String JavaDoc[] allowedUsers;
688             allowedUsers = users.trim().split(",");
689
690             for (int i = 0; i < allowedUsers.length; i++) {
691                 String JavaDoc user = allowedUsers[i].trim();
692
693                 if ((user != null) && !user.equals("") &&
694                     user.equals(this.username)) {
695                     return true;
696                 }
697             }
698         }
699
700         return false;
701     }
702
703     /**
704      * creates specified folder to the base path . base should be either absolute or
705      * relative to the project dir
706      * @param base String
707      * @param folderName String
708      * @return boolean
709      */

710     public boolean addSubFolder(String JavaDoc base, String JavaDoc folderName) throws
711             Exception JavaDoc {
712         String JavaDoc path = constructPathWithProjectDir(base);
713         File JavaDoc file = new File JavaDoc(path);
714
715         if (!isPathBeneathProjectDir(path)) {
716             throw new SecurityException JavaDoc(
717                     "Folder creation is not allowed outside project directory. Base path is:" +
718                     file.getCanonicalPath());
719         }
720
721         if (!file.exists()) {
722             throw new java.io.FileNotFoundException JavaDoc("Specified path '" + path +
723                     "' does not exists");
724         }
725
726         if (!file.isDirectory()) {
727             throw new java.io.IOException JavaDoc("Specified path'" + path +
728                                           "' is not a directory");
729         }
730
731         String JavaDoc newfilepath = file.getPath() + "/" + folderName;
732         newfilepath = new File JavaDoc(newfilepath).getCanonicalPath();
733
734         File JavaDoc newfile = new File JavaDoc(newfilepath);
735
736         if (newfile.exists()) {
737             throw new java.io.IOException JavaDoc("Specified path '" + newfilepath +
738                                           "' already exists");
739         }
740
741         return newfile.mkdir();
742     }
743
744     /**
745      * tests whether the path starts with project dir or not
746      * @param path String
747      * @return boolean
748      */

749     public boolean isPathBeneathProjectDir(String JavaDoc path) throws Exception JavaDoc {
750         File JavaDoc file = new File JavaDoc(path);
751         String JavaDoc fullpath = file.getCanonicalPath();
752         File JavaDoc prjdir = new File JavaDoc(getProjectDirectory());
753
754         return fullpath.startsWith(prjdir.getCanonicalPath());
755     }
756
757     /**
758      * renames existing file or dir. path should either be absolute or relative to
759      * the project dir
760      * @param existing String
761      * @param newname String
762      * @return boolean
763      * @throws Exception
764      */

765     public boolean renameFileFolder(String JavaDoc existing, String JavaDoc newname) throws
766             Exception JavaDoc {
767         String JavaDoc path = constructPathWithProjectDir(existing);
768         File JavaDoc file = new File JavaDoc(path);
769
770         if (!isPathBeneathProjectDir(path)) {
771             throw new SecurityException JavaDoc(
772                     "Rename is not allowed outside project directory");
773         }
774
775         if (!file.exists()) {
776             throw new java.io.FileNotFoundException JavaDoc("Specified path '" + path +
777                     "' does not exists");
778         }
779
780         String JavaDoc newpath = file.getParentFile().getPath() + "/" + newname;
781         File JavaDoc newfile = new File JavaDoc(newpath);
782
783         if (newfile.exists()) {
784             throw new java.io.IOException JavaDoc("Specified path '" + newpath +
785                                           "' already exists");
786         }
787
788         return file.renameTo(newfile);
789     }
790
791     /**
792      *
793      * @param path String
794      * @return boolean
795      * @throws Exception
796      */

797     public boolean removeFileFolder(String JavaDoc pathname) throws Exception JavaDoc {
798         String JavaDoc path = constructPathWithProjectDir(pathname);
799         File JavaDoc file = new File JavaDoc(path);
800
801         if (!file.exists()) {
802             throw new java.io.FileNotFoundException JavaDoc("Specified path '" + path +
803                     "' does not exists");
804         }
805
806         if (!isPathBeneathProjectDir(path)) {
807             throw new SecurityException JavaDoc(
808                     "Delete is not allowed outside project directory");
809         }
810
811         return deleteDir(file);
812     }
813
814     private String JavaDoc constructPathWithProjectDir(String JavaDoc path) {
815         String JavaDoc actualpath = "";
816
817         if (path.startsWith("/") || path.startsWith("\\")) {
818             actualpath = getProjectDirectory() + path;
819         } else {
820             actualpath = path;
821         }
822
823         return actualpath;
824     }
825
826     private boolean deleteDir(File JavaDoc dir) {
827         if (dir.isDirectory()) {
828             String JavaDoc[] children = dir.list();
829
830             for (int i = 0; i < children.length; i++) {
831                 boolean success = deleteDir(new File JavaDoc(dir, children[i]));
832
833                 if (!success) {
834                     return false;
835                 }
836             }
837         }
838
839         return dir.delete();
840     }
841
842     /**
843      * construct absoulute path with project dir
844      * @param path String
845      * @return String
846      */

847     public String JavaDoc resolvePathWithProjectDir(String JavaDoc path) {
848         if (!(path.startsWith("\\") || path.startsWith("/"))) {
849             path = "/" + path;
850         }
851
852         return getProjectDirectory() + path;
853     }
854
855     /**
856      *
857      * @return List
858      */

859     public List JavaDoc getProjectSubDirs() {
860         return DirectoryLister.buildProjectRootSubDirList(getProjectDirectory());
861     }
862
863     /**
864      * returns all files available under project dir filtered with extension
865      * @param extension String
866      * @return List
867      */

868     public List JavaDoc getFilesByExtension(String JavaDoc extension) {
869         return DirectoryLister.buildFileListByExtension(getProjectDirectory(),
870                 getProjectModules(true, true), extension);
871     }
872
873     /**
874      * Zips the contents of project directory, for this project context.
875      *
876      * @param zos zos zip output stream, caller permitted to wrap various stream
877      * in the zip os (file, servlet, etc)
878      * @throws IOException
879      */

880     public void zipProjectContents(ZipOutputStream JavaDoc zos) throws IOException JavaDoc {
881         logger.debug("zipping project directory: " + this.getProjectDirectory());
882         if (this.hasPermission(Permission.APP_ADMINISTRATION)) {
883             zipDir(this.getBaseDirectory(), this.getProjectDirectory(), zos);
884         } else {
885             throw new SecurityException JavaDoc("user does not have this permission");
886         }
887     }
888
889     /**
890      *
891      * @param baseDir absolute file path to base directory, used to trim zip entry name
892      * so that it does not contain the full path names on the server
893      * @param dir2zip absolute file path to the project directory
894      * @param zos zip output stream, caller permitted to wrap various stream
895      * in the zip os (file, servlet, etc)
896      * @throws IOException
897      */

898     private void zipDir(String JavaDoc baseDir, String JavaDoc dir2zip, ZipOutputStream JavaDoc zos) throws
899             IOException JavaDoc {
900         // logger.debug("zipping directory: " + dir2zip);
901

902         //create a new File object based on the directory we have to zip File
903
File JavaDoc zipDir = new File JavaDoc(dir2zip);
904
905         //get a listing of the directory content
906
String JavaDoc[] dirList = zipDir.list();
907        
908
909         //loop through dirList, and zip the files
910
for (int i = 0; i < dirList.length; i++) {
911             File JavaDoc f = new File JavaDoc(zipDir, dirList[i]);
912
913             if (f.isDirectory()) {
914                 //if the File object is a directory, call this
915
//function again to add its content recursively
916
String JavaDoc filePath = f.getPath();
917                 zipDir(baseDir, filePath, zos);
918             } else {
919                 //if we reached here, the File object f was not a directory
920
//create a FileInputStream on top of f
921
FileInputStream JavaDoc fis = new FileInputStream JavaDoc(f);
922
923                 // create a new zip entry
924
String JavaDoc basePath = new File JavaDoc(baseDir).getCanonicalPath();
925                 String JavaDoc entryName = f.getCanonicalPath();
926                 
927                 if(entryName.length() > basePath.length())
928                     entryName = entryName.substring(basePath.length()+1);
929                 
930                 //String entryName = extractModulePath(f.getCanonicalPath());//f.getAbsolutePath().replaceAll(baseDir, "");
931
ZipEntry JavaDoc anEntry = new ZipEntry JavaDoc(entryName);
932                 //place the zip entry in the ZipOutputStream object
933
zos.putNextEntry(anEntry);
934                 
935                 byte[] readBuffer = new byte[512];
936                 int bytesIn = 0;
937                 //now write the content of the file to the ZipOutputStream
938
while ((bytesIn = fis.read(readBuffer)) != -1) {
939                     zos.write(readBuffer, 0, bytesIn);
940                 }
941
942                 //close the Stream
943
fis.close();
944             }
945         }
946     }
947
948     /**
949      * save text content to the specified file
950      * @param file String relative path of the file
951      * @param content String text content
952      * @throws Exception
953      */

954     public void saveTextFileContent(String JavaDoc file, String JavaDoc content) throws
955             Exception JavaDoc {
956         logger.info("saving text content to file :" + file);
957         File JavaDoc fileToSave = new File JavaDoc(resolvePathWithProjectDir(file));
958         if (!fileToSave.exists())
959             throw new java.io.FileNotFoundException JavaDoc("Specified path '" + file +
960                     "' does not exists");
961         if (!fileToSave.isFile())
962             throw new java.io.FileNotFoundException JavaDoc("Specified path '" + file +
963                     "' is not a file");
964
965         if (!isPathBeneathProjectDir(fileToSave.getCanonicalPath())) {
966             throw new SecurityException JavaDoc(
967                     "save is not allowed outside project directory");
968         }
969
970         if (!isPathAllowed(file)) {
971             throw new SecurityException JavaDoc("user does not have this permission");
972         }
973         FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(fileToSave);
974         out.write(content.getBytes());
975         out.close();
976     }
977
978     /**
979      * returns RFunctionList bean restored from rfunction.xml.
980      * returns new instance of RFunctionList if rfunction.xml file not found
981      * @return RFunctionList
982      * @throws Exception
983      */

984     public RFunctionList getRFunctionList() throws Exception JavaDoc {
985         String JavaDoc xmlFile = this.getProjectDirectory() + "/" + "rfunction.xml";
986         RFunctionList rFunctionList;
987         if(!new File JavaDoc(xmlFile).exists()) {
988             logger.error("R Function file 'rfunction.xml' in project dir is not defined");
989             rFunctionList = new RFunctionList();
990         } else {
991             BeanStorage bean = new BeanStorage();
992             rFunctionList = (RFunctionList) bean.restoreBeanFromFile(xmlFile);
993         }
994         return rFunctionList;
995     }
996
997     /**
998      * serialize RFunctionList object into rfunction.xml file
999      * @param object RFunctionList
1000     * @throws Exception
1001     */

1002    public void saveRFunctionListBean(RFunctionList object) throws Exception JavaDoc {
1003        BeanStorage bean = new BeanStorage();
1004        String JavaDoc xmlFile = this.getProjectDirectory() + "/" + "rfunction.xml";
1005        bean.saveBeanToFile(xmlFile, object);
1006    }
1007
1008    /**
1009     * @param uri
1010     * @param catalog
1011     * @param cube
1012     * @param relativeDir
1013     */

1014    public void autogenerate(String JavaDoc datasourceName, String JavaDoc cube, String JavaDoc relativeDir) throws OlapException, IOException JavaDoc{
1015
1016        this.createDirectory(relativeDir);
1017        AnalysisGenerator gen = new AnalysisGenerator();
1018        Datasource ds = this.getDatasource(datasourceName);
1019        Map JavaDoc mdx = gen.generateMdxForDimensions(ds.getServer(), ds.getCatalog(), cube);
1020        Iterator JavaDoc keys = mdx.keySet().iterator();
1021        while(keys.hasNext()){
1022            String JavaDoc key = (String JavaDoc)keys.next();
1023            Analysis analysis = new Analysis();
1024            analysis.setAnalysisTitle(key);
1025            analysis.setChartType(1);
1026            analysis.setMdxQuery( (String JavaDoc)mdx.get(key) );
1027            analysis.setDescription("automatically generated on: " + new java.util.Date JavaDoc());
1028            analysis.setDataSourceName(datasourceName);
1029            //create analysis
1030
String JavaDoc filename = relativeDir + "/" + key + ".analysis";
1031            savePublic(filename.replaceAll(" ", "_"), analysis, null);
1032        }
1033    }
1034    
1035    /**
1036     *
1037     * @return a non-null list of menu names, under "Auto Generated"
1038     */

1039    public List JavaDoc getAutoGeneratedMenuNames(){
1040        List JavaDoc displayNames = new LinkedList JavaDoc();
1041        try {
1042            Menu subMenu = this.buildMenu().getSubMenu("Auto Generated");
1043            if(subMenu !=null){
1044                displayNames = subMenu.getMenuDisplayNames();
1045            }
1046            
1047        } catch (IOException JavaDoc e) {
1048            logger.error(e);
1049        }
1050        return displayNames;
1051    }
1052}
1053
Popular Tags