KickJava   Java API By Example, From Geeks To Geeks.

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


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.LogManager;
23 import org.apache.log4j.Logger;
24 import org.openi.analysis.Datasource;
25 import org.openi.xml.BeanStorage;
26 import org.openi.xml.XMLTransformer;
27 import org.w3c.dom.*;
28 import java.io.*;
29 import java.util.HashMap JavaDoc;
30 import java.util.Iterator JavaDoc;
31 import java.util.LinkedList JavaDoc;
32 import java.util.List JavaDoc;
33 import java.util.Map JavaDoc;
34 import java.util.TreeMap JavaDoc;
35 import javax.xml.parsers.*;
36 import javax.xml.transform.*;
37 import javax.xml.transform.stream.*;
38
39
40 /**
41  * @author plucas
42  *
43  * TODO - factory needs to cache the projects
44  */

45 public class ProjectFactory {
46     private static Logger logger = LogManager.getLogger(ProjectFactory.class);
47
48     private ProjectFactory() {
49     }
50
51     /*
52        public static Project getProject(String projectDir, String projectId){
53        logger.debug("getting project for: " + projectId + " in project dir: " + projectDir);
54        Project retVal;
55         }
56        private static Project findProjectFile(String baseDir, String projectId){
57            }*/

58
59     /**
60      * Always returns all available projects underneath the baseDirName. The map
61      * does not contain any category grouping. (Although the project object has
62      * a getCategory method). If you need grouping by category use the getProjectsByCategory
63      * method.
64      *
65      * Directories underneath baseDirName are filtered using ProjectDirectoryFilter (filters
66      * WEB-INF, META-INF, CVS directories).
67      *
68      * If a subdirectory does not have a project.xml file, an IOException is trapped, logged,
69      * but processing continues.
70      *
71      * XXX: should this be a private method?
72      *
73      * @return projects key=projectId, value=project
74      */

75     public static Map JavaDoc getProjectMap(String JavaDoc baseDirName) {
76         Map JavaDoc projectMap = new TreeMap JavaDoc();
77         File baseDir = new File(baseDirName);
78
79         // this simply filters out WEB-INF, META-INF, CVS, .. and only accepts directories
80
File[] subDirs = baseDir.listFiles(new ProjectDirectoryFilter());
81
82         for (int i = 0; i < subDirs.length; i++) {
83             try {
84                     Project current = getProject(baseDirName, subDirs[i].getName());
85                 projectMap.put(current.getProjectId(), current);
86             } catch (IOException e) {
87                 logger.warn("could not restore project, but continuing to build map. Is this supposed to be a project? " +
88                     e.getMessage());
89             }
90         }
91
92         return projectMap;
93     }
94
95     /**
96      * @see #getProjectsByCategory(String, String). This signature is intended
97      * to generate maps for application admins only. Acutally, this should probably be eliminated once app
98      * admin configuration is extracted from web.xml
99      *
100      * @param baseDirName
101      * @return
102      */

103     public static Map JavaDoc getProjectsByCategory(String JavaDoc baseDirName) {
104         return getProjectsByCategory(baseDirName, null);
105     }
106
107     /**
108      * Returns map of categories, each category contains a list of projects.
109      * Key=categoryName, value=Category object
110      *
111      * If a project.categoryName is null, it is replaced with "General"
112      *
113      * Categories are included only if the user has access to at least one
114      * project in that category
115      *
116      * Because we have the notion of project maps per user, this means caching (if ever)
117      * will need to be per user - session. Probably best to not cache the map at all.
118      * If caching is needed, cache at getProject.
119      *
120      * @param baseDirName
121      */

122     public static Map JavaDoc getProjectsByCategory(String JavaDoc baseDirName, String JavaDoc username) {
123         long start = System.currentTimeMillis();
124         Map JavaDoc categories = new TreeMap JavaDoc();
125         Map JavaDoc rawProjects = getProjectMap(baseDirName);
126         Iterator JavaDoc projects = rawProjects.values().iterator();
127
128         while (projects.hasNext()) {
129             Project current = (Project) projects.next();
130
131             // finally add project to category
132
if (current != null) {
133                 // add the project to the category list if the user has access to the project
134
// a null username, means we have an application admin, by rule app admins can see all projects
135
if ((username == null) || current.validateAdmin(username)
136                         || current.validateUser(username)) {
137                     // notice categories only get created, if the user has access to the project
138
// this prevents categories with no projects
139
String JavaDoc categoryName = current.getCategory();
140
141                     if (categoryName == null) {
142                         categoryName = "General";
143                     }
144
145                     Category category = (Category) categories.get(categoryName);
146
147                     if (category == null) {
148                         category = new Category(categoryName);
149                         categories.put(categoryName, category);
150                     }
151
152                     category.addProject(current);
153                 }
154             }
155         }
156
157         logger.info("completed creating project by category in: "
158             + (System.currentTimeMillis() - start) + " ms");
159
160         return categories;
161     }
162
163     /**
164      * Currently not cached - loads project from file each time.
165      *
166      * @param baseDirName - base directory that contains all projects
167      * @param projectId - must match the directory name (relative to baseDirName)
168      * @return
169      * @throws IOException
170      */

171     public static Project getProject(String JavaDoc baseDirName, String JavaDoc projectId)
172         throws IOException {
173         // important to give proper feedback to caller
174
if (baseDirName == null) {
175             throw new IOException(
176                 "Project directory name is null. This should be the location for all projects");
177         }
178
179         BeanStorage storage = new BeanStorage();
180
181         String JavaDoc projectFilePath = new File(baseDirName,
182                 projectId + "/project.xml").getCanonicalPath();
183         logger.debug("Trying to restore project: " + projectFilePath);
184         
185         Project retProject = null;
186         try{
187                 retProject = (Project) storage.restoreBeanFromFile(projectFilePath);
188         }catch(Exception JavaDoc e){
189                 logger.debug("trouble restoring project from " + projectFilePath, e);
190                 logger.debug("possibly old format, trying xslt");
191         }
192
193         if(retProject == null){
194             String JavaDoc xsltPath = new File(baseDirName).getParent()
195                 + "/openi/WEB-INF/project/project.xsl";
196             logger.debug(
197                 "transforming project.xml into new format using template "
198                 + xsltPath);
199     
200             try {
201                     String JavaDoc backup = backupOldFile(projectFilePath);
202                     transformProjectToNewFormat(backup, projectFilePath, xsltPath);
203                     //transformed, try to restore again, this time if it doesn't work, throw IOException:
204
retProject = (Project) storage.restoreBeanFromFile(projectFilePath);
205             } catch (Exception JavaDoc ex) {
206                 //logger.error(ex.getStackTrace());
207
throw new IOException(
208                     "An error occured while transforming project.xml into new format\nroot cause:"
209                     + ex.getMessage());
210             }
211         }
212
213         return retProject;
214     }
215
216
217
218     private static String JavaDoc backupOldFile(String JavaDoc oldFileName) {
219         logger.debug("trying to backup filename: " + oldFileName);
220         String JavaDoc newfilename = null;
221         try{
222             File oldFile = new File(oldFileName);
223             // try to backup the file, but don't try forever:
224
for(int i=0; i < 100; i++){
225                 newfilename = oldFile.getCanonicalPath() + "." + i;
226                 File newFile = new File(newfilename);
227                 if(!newFile.exists()){
228                     logger.debug("backing up project to " + newfilename);
229                     oldFile.renameTo(newFile);
230                     break;
231                 }
232             }
233         }catch(Exception JavaDoc e){
234             // trap, but log
235
logger.error(e);
236         }
237         return newfilename;
238     }
239
240     private static void transformProjectToNewFormat(String JavaDoc backup, String JavaDoc projectXml,
241         String JavaDoc xslFile) throws Exception JavaDoc {
242         String JavaDoc result = XMLTransformer.transform(new FileInputStream(xslFile),
243                 new FileInputStream(backup));
244
245         FileOutputStream out = new FileOutputStream(projectXml);
246         out.write(result.getBytes());
247         out.close();
248     }
249
250     /**
251      * Separate from getProject to avoid creating
252      * a project when there just might be a typo, error,
253      * security flaw.
254      * @throws IOException
255      */

256     public static Project createProject(String JavaDoc baseDirName, String JavaDoc projectId)
257         throws IOException {
258         Project project = null;
259
260         //check for valid baseDirName
261
File baseDirTest = new File(baseDirName);
262
263         if (baseDirTest == null) {
264             throw new FileNotFoundException("invalid base directory: "
265                 + baseDirName);
266         } else {
267             if (!baseDirTest.exists()) {
268                 throw new FileNotFoundException("invalid base directory: "
269                     + baseDirName);
270             }
271         }
272
273         // check if project already exists
274
try {
275             project = getProject(baseDirName, projectId);
276         } catch (IOException e) {
277             //trap
278
}
279
280         if (project != null) {
281             throw new IllegalArgumentException JavaDoc(
282                 "Cannot create, project already exists: " + projectId);
283         } else {
284             // create new project
285
project = new Project();
286             project.setProjectId(projectId);
287             project.setProjectName(projectId);
288             project.setLogoUrl("images/logo.gif");
289             project.setSplashImageUrl("images/splash.gif");
290
291             Datasource ds = new Datasource();
292             ds.setServer("");
293
294             Map JavaDoc dsMap = new HashMap JavaDoc();
295             dsMap.put("projectdefault", ds);
296             project.setDataSourceMap(dsMap);
297
298             //populate with some dummy stuff
299
List JavaDoc modules = new LinkedList JavaDoc();
300             modules.add("public");
301             project.setModules(modules);
302
303             //persist
304
BeanStorage storage = new BeanStorage();
305             storage.saveBeanToFile(baseDirName + "/" + projectId
306                 + "/project.xml", project);
307         }
308
309         return project;
310     }
311 }
312
Popular Tags