KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > pentaho > repository > filebased > solution > SolutionRepository


1 /*
2  * Copyright 2006 Pentaho Corporation. All rights reserved.
3  * This software was developed by Pentaho Corporation and is provided under the terms
4  * of the Mozilla Public License, Version 1.1, or any later version. You may not use
5  * this file except in compliance with the license. If you need a copy of the license,
6  * please go to http://www.mozilla.org/MPL/MPL-1.1.txt. The Original Code is the Pentaho
7  * BI Platform. The Initial Developer is Pentaho Corporation.
8  *
9  * Software distributed under the Mozilla Public License is distributed on an "AS IS"
10  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
11  * the license for the specific language governing your rights and limitations.
12  */

13 /*
14  * Created on Jun 21, 2005
15  *
16  * TODO To change the template for this generated file go to
17  * Window - Preferences - Java - Code Style - Code Templates
18  */

19 package org.pentaho.repository.filebased.solution;
20
21 import java.io.File JavaDoc;
22 import java.io.FileInputStream JavaDoc;
23 import java.io.FileNotFoundException JavaDoc;
24 import java.io.FileOutputStream JavaDoc;
25 import java.io.FilenameFilter JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.io.InputStream JavaDoc;
28 import java.io.InputStreamReader JavaDoc;
29 import java.io.Reader JavaDoc;
30 import java.net.URL JavaDoc;
31 import java.net.URLClassLoader JavaDoc;
32 import java.nio.channels.FileChannel JavaDoc;
33 import java.util.ArrayList JavaDoc;
34 import java.util.HashMap JavaDoc;
35 import java.util.Iterator JavaDoc;
36 import java.util.List JavaDoc;
37 import java.util.Locale JavaDoc;
38 import java.util.Properties JavaDoc;
39 import java.util.StringTokenizer JavaDoc;
40 import javax.activation.DataSource JavaDoc;
41 import javax.activation.FileDataSource JavaDoc;
42 import javax.activation.URLDataSource JavaDoc;
43 import org.apache.commons.collections.buffer.BoundedFifoBuffer;
44 import org.apache.commons.fileupload.FileItem;
45 import org.apache.commons.logging.Log;
46 import org.apache.commons.logging.LogFactory;
47 import org.dom4j.Document;
48 import org.dom4j.DocumentHelper;
49 import org.dom4j.Element;
50 import org.dom4j.Node;
51 import org.pentaho.core.repository.ISolutionRepository;
52 import org.pentaho.core.runtime.IRuntimeContext;
53 import org.pentaho.core.session.IPentahoSession;
54 import org.pentaho.core.solution.ActionResource;
55 import org.pentaho.core.solution.IActionResource;
56 import org.pentaho.core.solution.IActionSequence;
57 import org.pentaho.core.solution.SequenceDefinition;
58 import org.pentaho.core.solution.SolutionReposUtil;
59 import org.pentaho.core.system.PentahoMessenger;
60 import org.pentaho.core.system.PentahoSystem;
61 import org.pentaho.core.util.XmlHelper;
62 import org.pentaho.messages.Messages;
63 import org.pentaho.messages.util.LocaleHelper;
64 import org.pentaho.util.FileHelper;
65 import org.pentaho.util.HttpUtil;
66
67 /**
68  * @author James Dixon
69  *
70  * TODO To change the template for this generated type comment go to Window - Preferences - Java - Code Style - Code Templates
71  */

72 public class SolutionRepository extends PentahoMessenger implements ISolutionRepository {
73     /**
74      *
75      */

76     private static final long serialVersionUID = -8270135463210017284L;
77
78     private static final String JavaDoc ROOT_NODE_NAME = "repositiory"; //$NON-NLS-1$
79

80     private static final String JavaDoc LOCATION_ATTR_NAME = "location"; //$NON-NLS-1$
81

82     private static final String JavaDoc ENTRY_NODE_NAME = "entry"; //$NON-NLS-1$
83

84     private static final String JavaDoc TYPE_ATTR_NAME = "type"; //$NON-NLS-1$
85

86     private static final String JavaDoc NAME_ATTR_NAME = "name"; //$NON-NLS-1$
87

88     private static final String JavaDoc DIRECTORY_ATTR = "directory"; //$NON-NLS-1$
89

90     private static final String JavaDoc FILE_ATTR = "file"; //$NON-NLS-1$
91

92     private static final String JavaDoc EMPTY_STR = ""; //$NON-NLS-1$
93

94     private String JavaDoc rootPath;
95
96     private Document repository;
97
98     private static final boolean debug = PentahoSystem.debug;
99
100     private static SolutionRepository solutionRepository;
101
102     private IPentahoSession session;
103
104     private BoundedFifoBuffer cache;
105
106     private HashMap JavaDoc cacheMap;
107
108     private int cacheSize = 0;
109
110     private Locale JavaDoc locale;
111
112     private static String JavaDoc LOG_NAME = "SOLUTION-REPOSITORY"; //$NON-NLS-1$
113

114     private File JavaDoc rootFile;
115
116     private static final Log logger = LogFactory.getLog(SolutionRepository.class);
117
118     private static HashMap JavaDoc propertyMap = new HashMap JavaDoc();
119
120     public Log getLogger() {
121         return logger;
122     }
123
124     public SolutionRepository() {
125         locale = LocaleHelper.getLocale();
126         init();
127     }
128
129     private void init() {
130         repository = null;
131         cacheSize = 0;
132         try {
133             cacheSize = Integer.parseInt(PentahoSystem.getSystemSetting("solution-repository/cache-size", "0")); //$NON-NLS-1$ //$NON-NLS-2$;
134
} catch (NumberFormatException JavaDoc e) {
135         }
136         if (cacheSize > 0) {
137             cacheMap = new HashMap JavaDoc();
138             cache = new BoundedFifoBuffer(cacheSize);
139         }
140     }
141
142     public void setLocale(Locale JavaDoc locale) {
143         if (!this.locale.equals(locale)) {
144             init();
145         }
146         this.locale = locale;
147     }
148
149     public ClassLoader JavaDoc getClassLoader(String JavaDoc path) {
150         File JavaDoc localeDir = new File JavaDoc(PentahoSystem.getApplicationContext().getSolutionPath(path));
151         try {
152             URL JavaDoc localeDirUrl = localeDir.toURL();
153             URLClassLoader JavaDoc loader = new URLClassLoader JavaDoc(new URL JavaDoc[] { localeDirUrl });
154             return loader;
155         } catch (Exception JavaDoc e) {
156         }
157         return null;
158     }
159
160     public void setSession(IPentahoSession session) {
161         this.session = session;
162     }
163
164     public static SolutionRepository getInstance(IPentahoSession session) {
165         if (solutionRepository == null) {
166             solutionRepository = new SolutionRepository();
167             solutionRepository.init(session);
168         }
169         return solutionRepository;
170     }
171
172     public IActionSequence getActionSequence(String JavaDoc solutionName, String JavaDoc actionPath, String JavaDoc sequenceName, int localLoggingLevel, int actionOperation) {
173         String JavaDoc action;
174         if (actionPath != null && !"".equals(actionPath)) { //$NON-NLS-1$
175
action = solutionName + File.separator + actionPath + File.separator + sequenceName;
176         } else {
177             action = solutionName + File.separator + sequenceName;
178         }
179         IActionSequence actionSequence;
180         if (cacheSize > 0) {
181             actionSequence = (IActionSequence) cacheMap.get(action);
182             if (actionSequence != null) {
183                 // add this back into the end of the cache
184
cache.remove(actionSequence);
185                 cache.add(actionSequence);
186                 return actionSequence;
187             }
188         }
189         Document actionSequenceDocument = getSolutionDocument(action);
190         if (actionSequenceDocument == null) {
191             return null;
192         }
193         actionSequence = SequenceDefinition.ActionSequenceFactory(actionSequenceDocument, sequenceName, actionPath, solutionName, this, PentahoSystem.getApplicationContext(), localLoggingLevel);
194         if (actionSequence == null) {
195             return null;
196         }
197         if (cacheSize > 0) {
198             // add to the cacheMap
199
cacheMap.put(action, actionSequence);
200             if (cache.size() >= cacheSize) {
201                 IActionSequence removed = (IActionSequence) cache.remove();
202                 String JavaDoc removedName = removed.getSolutionName() + File.separator + removed.getSolutionPath() + File.separator + removed.getSequenceName();
203                 cacheMap.remove(removedName);
204             }
205             cache.add(actionSequence);
206         }
207         return actionSequence;
208     }
209
210     public Document getSolutionDocument(String JavaDoc solutionName, String JavaDoc actionPath, String JavaDoc actionName) {
211         return getSolutionDocument(solutionName + File.separator + actionPath + File.separator + actionName);
212     }
213
214     public Document getSolutionDocument(String JavaDoc documentPath) {
215         // TODO: caching
216
File JavaDoc file = getFile(documentPath, false);
217         if (file == null) {
218             return null;
219         }
220         Document document = XmlHelper.getDocFromFile(file);
221         if (document == null && file.exists()) {
222             // the document exists but cannot be parsed
223
error(Messages.getString("SolutionRepository.ERROR_0009_INVALID_DOCUMENT", documentPath)); //$NON-NLS-1$
224
return null;
225         }
226         localizeDoc(document, file);
227         return document;
228     }
229
230     private File JavaDoc getFile(String JavaDoc path, boolean create) {
231         File JavaDoc f = new File JavaDoc(PentahoSystem.getApplicationContext().getSolutionPath(path));
232         if (!f.exists() && !create) {
233             error(Messages.getErrorString("SolutionRepository.ERROR_0001_FILE_DOES_NOT_EXIST", path)); //$NON-NLS-1$
234
return null;
235         }
236         if (!f.exists()) {
237             f.mkdirs();
238         }
239         // TODO: caching
240
if (debug)
241             debug(Messages.getErrorString("SolutionRepository.DEBUG_FILE_PATH", f.getAbsolutePath())); //$NON-NLS-1$
242
return f;
243     }
244
245     public void init(IPentahoSession pentahoSession) {
246         this.session = pentahoSession;
247         rootFile = getFile("", false); //$NON-NLS-1$
248
rootPath = rootFile.getAbsolutePath() + File.separator;
249         setLogId(LOG_NAME + ": "); //$NON-NLS-1$
250
}
251
252     private File JavaDoc getFile(IRuntimeContext runtimeContext, String JavaDoc path) {
253         if (runtimeContext == null) {
254             error(Messages.getErrorString("SolutionRepository.ERROR_0002_NULL_RUNTIME_CONTEXT")); //$NON-NLS-1$
255
return null;
256         }
257         File JavaDoc f = getFile(runtimeContext.getSolutionName() + File.separator + path, false);
258         if (!f.exists()) {
259             error(Messages.getErrorString("SolutionRepository.ERROR_0003_NULL_SOLUTION_FILE", path)); //$NON-NLS-1$
260
return null;
261         }
262         // TODO: caching
263
if (debug)
264             debug(Messages.getString("SolutionRepository.DEBUG_FILE_PATH", f.getAbsolutePath())); //$NON-NLS-1$
265
return f;
266     }
267
268     public String JavaDoc getAbsolutePath(IRuntimeContext runtimeContext, String JavaDoc path) {
269         // TODO: make this private... currently we need it for BIRT
270
return rootPath + File.separator + runtimeContext.getSolutionName() + File.separator + path;
271     }
272
273     public String JavaDoc getActionDefinition(IRuntimeContext runtimeContext, String JavaDoc actionPath) {
274         // TODO: caching
275
if ((runtimeContext == null) || (runtimeContext.getInstanceId() == null) || (runtimeContext.getActionName() == null)) {
276             error(Messages.getErrorString("SolutionRepository.ERROR_0004_INVALID_CONTEXT")); //$NON-NLS-1$
277
}
278         genLogIdFromInfo(runtimeContext.getInstanceId(), LOG_NAME, runtimeContext.getActionName());
279         File JavaDoc f = getFile(runtimeContext, actionPath);
280         if (f == null) {
281             error(Messages.getErrorString("SolutionRepository.ERROR_0005_INVALID_SOLUTION_FILE") + actionPath); //$NON-NLS-1$
282
}
283         return FileHelper.getStringFromFile(f);
284     }
285
286     public Document getActionDefinitionDocument(IRuntimeContext runtimeContext, String JavaDoc actionPath) {
287         // TODO: caching
288
genLogIdFromInfo(runtimeContext.getInstanceId(), LOG_NAME, runtimeContext.getActionName());
289         File JavaDoc f = getFile(runtimeContext, actionPath);
290         if (f == null) {
291             return null;
292         }
293         return XmlHelper.getDocFromFile(f);
294     }
295
296     // Old prototype code that needs to be redone somehow...
297
public void publish(IPentahoSession localSession, int localLoggingLevel) {
298         // update the respistory
299
this.loggingLevel = localLoggingLevel;
300         File JavaDoc rootDir = getFile("", false); //$NON-NLS-1$
301
repository = DocumentHelper.createDocument();
302         Element rootNode = repository.addElement("repository"); //$NON-NLS-1$
303
processDir(rootNode, rootDir, null, 0, ISolutionRepository.ACTION_ADMIN);
304     }
305
306     private void processDir(Element parentNode, File JavaDoc parentDir, String JavaDoc solutionId, int pathIdx, int actionOperation) {
307         File JavaDoc files[] = parentDir.listFiles();
308         // first process the directories
309
for (int idx = 0; idx < files.length; idx++) {
310             if (!files[idx].isDirectory()) {
311                 String JavaDoc fileName = files[idx].getName();
312                 if (fileName.equals("Entries") || fileName.equals("Repository") || fileName.equals("Root")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
313
// ignore any CVS files
314
continue;
315                 }
316                 String JavaDoc solutionPath = files[idx].getAbsolutePath().substring(rootPath.length());
317                 if (fileName.toLowerCase().endsWith(".url")) { //$NON-NLS-1$
318
addUrlToRepository(files[idx], parentNode, solutionPath);
319                 }
320                 if (!fileName.toLowerCase().endsWith(".xaction") && !fileName.toLowerCase().endsWith(".xml")) { //$NON-NLS-1$ //$NON-NLS-2$
321
// ignore any non-XML files
322
continue;
323                 }
324                 if (fileName.toLowerCase().equals("index.xml")) { //$NON-NLS-1$
325
// index.xml files are handled in the directory loop below
326
continue;
327                 }
328                 String JavaDoc path = files[idx].getAbsolutePath().substring(pathIdx);
329                 if (!path.equals(fileName)) {
330                     path = path.substring(0, path.length() - fileName.length() - 1);
331                     // windows \ characters in the path gets messy in urls, so
332
// switch them to /
333
path = path.replace('\\', '/');
334                 } else {
335                     path = ""; //$NON-NLS-1$
336
}
337                 if (fileName.toLowerCase().endsWith(".xaction")) { //$NON-NLS-1$
338
// create an action sequence document from this
339
info(Messages.getString("SolutionRepository.DEBUG_ADDING_ACTION", fileName)); //$NON-NLS-1$
340
IActionSequence actionSequence = getActionSequence(solutionId, path, fileName, loggingLevel, actionOperation);
341                     if (actionSequence == null) {
342                         error(Messages.getErrorString("SolutionRepository.ERROR_0006_INVALID_SEQUENCE_DOCUMENT", fileName)); //$NON-NLS-1$
343
} else {
344                         addToRepository(actionSequence, parentNode, files[idx]);
345                     }
346                 }
347             }
348         }
349         for (int idx = 0; idx < files.length; idx++) {
350             if (files[idx].isDirectory() && (!files[idx].getName().equalsIgnoreCase("system")) && (!files[idx].getName().equalsIgnoreCase("CVS")) && (!files[idx].getName().equalsIgnoreCase(".svn"))) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
351
Element dirNode = parentNode.addElement("file"); //$NON-NLS-1$
352
dirNode.addAttribute("type", FileInfo.FILE_TYPE_FOLDER); //$NON-NLS-1$
353
// TODO read this from the directory index file
354
String JavaDoc thisSolution;
355                 String JavaDoc path = ""; //$NON-NLS-1$
356
if (solutionId == null) {
357                     thisSolution = files[idx].getName();
358                     pathIdx = rootPath.length() + File.separator.length() + thisSolution.length();
359                 } else {
360                     thisSolution = solutionId;
361                     path = files[idx].getAbsolutePath().substring(pathIdx);
362                     // windows \ characters in the path gets messy in urls, so
363
// switch them to /
364
path = path.replace('\\', '/');
365                     dirNode.addElement("path").setText(path); //$NON-NLS-1$
366
}
367                 File JavaDoc indexFile = new File JavaDoc(files[idx], "index.xml"); //$NON-NLS-1$
368
Document indexDoc = null;
369                 if (indexFile.exists()) {
370                     indexDoc = getSolutionDocument(thisSolution, path, "index.xml"); //$NON-NLS-1$
371
}
372                 if (indexDoc != null) {
373                     addIndexToRepository(indexDoc, files[idx], dirNode, path, thisSolution);
374                 } else {
375                     dirNode.addAttribute("visible", "false"); //$NON-NLS-1$ //$NON-NLS-2$
376
String JavaDoc dirName = files[idx].getName();
377                     dirNode.addAttribute("name", dirName); //$NON-NLS-1$
378
dirNode.addElement("title").setText(dirName); //$NON-NLS-1$
379
}
380                 processDir(dirNode, files[idx], thisSolution, pathIdx, actionOperation);
381             } else if (solutionId == null && files[idx].getName().equalsIgnoreCase("index.xml")) { //$NON-NLS-1$
382
Document indexDoc = null;
383                 indexDoc = getSolutionDocument("", "", "index.xml"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
384
if (indexDoc != null) {
385                     addIndexToRepository(indexDoc, files[idx], parentNode, "", ""); //$NON-NLS-1$ //$NON-NLS-2$
386
}
387             }
388         }
389     }
390
391     private void localizeDoc(Node document, File JavaDoc file) {
392         String JavaDoc fileName = file.getName();
393         int dotIndex = fileName.indexOf('.');
394         String JavaDoc baseName = fileName.substring(0, dotIndex);
395         // TODO read in nodes from the locale file and use them to override the
396
// ones in the main document
397
try {
398             List JavaDoc nodes = document.selectNodes("descendant::*"); //$NON-NLS-1$
399
Iterator JavaDoc nodeIterator = nodes.iterator();
400             while (nodeIterator.hasNext()) {
401                 Node node = (Node) nodeIterator.next();
402                 String JavaDoc name = node.getText();
403                 if (name.startsWith("%") && !node.getPath().endsWith("/text()")) { //$NON-NLS-1$ //$NON-NLS-2$
404
try {
405                         String JavaDoc localeText = getLocaleString(name, baseName, file);
406                         if (localeText != null) {
407                             node.setText(localeText);
408                         }
409                     } catch (Exception JavaDoc e) {
410                         warn(Messages.getString("SolutionRepository.WARN_MISSING_RESOURCE_PROPERTY", name.substring(1), baseName, locale.toString())); //$NON-NLS-1$
411
}
412                 }
413             }
414         } catch (Exception JavaDoc e) {
415             error(Messages.getErrorString("SolutionRepository.ERROR_0007_COULD_NOT_READ_PROPERTIES", file.getAbsolutePath()), e); //$NON-NLS-1$
416
}
417     }
418
419     private String JavaDoc getLocaleString(String JavaDoc key, String JavaDoc baseName, File JavaDoc baseFile) {
420         File JavaDoc searchDir = baseFile.getParentFile();
421         try {
422             boolean searching = true;
423             while (searching) {
424                 // look to see if this exists
425
File JavaDoc test = new File JavaDoc(searchDir, baseName + '_' + locale.getLanguage() + '_' + locale.getCountry() + '_' + locale.getVariant() + ".properties"); //$NON-NLS-1$
426
if (!test.exists()) {
427                     test = new File JavaDoc(searchDir, baseName + '_' + locale.getLanguage() + '_' + locale.getCountry() + ".properties"); //$NON-NLS-1$
428
}
429                 if (!test.exists()) {
430                     test = new File JavaDoc(searchDir, baseName + '_' + locale.getLanguage() + ".properties"); //$NON-NLS-1$
431
}
432                 if (!test.exists()) {
433                     test = new File JavaDoc(searchDir, baseName + ".properties"); //$NON-NLS-1$
434
}
435                 if (test.exists()) {
436
437                     Properties JavaDoc p = (Properties JavaDoc) propertyMap.get(test.getCanonicalPath());
438                     if (p == null) {
439                         p = new Properties JavaDoc();
440                         p.load(new FileInputStream JavaDoc(test));
441                         propertyMap.put(test.getCanonicalPath(), p);
442                     }
443
444                     String JavaDoc localeText = p.getProperty(key.substring(1));
445                     if (localeText != null) {
446                         return localeText;
447                     }
448                 }
449                 if (searching) {
450                     if (!baseName.equals("messages")) { //$NON-NLS-1$
451
baseName = "messages"; //$NON-NLS-1$
452
} else {
453                         if (searchDir.equals(rootFile)) {
454                             searching = false;
455                         } else {
456                             searchDir = searchDir.getParentFile();
457                         }
458                     }
459                 }
460             }
461             return null;
462         } catch (Exception JavaDoc e) {
463             error(Messages.getErrorString("SolutionRepository.ERROR_0007_COULD_NOT_READ_PROPERTIES", baseFile.getAbsolutePath()), e); //$NON-NLS-1$
464
}
465         return null;
466     }
467
468     private void addIndexToRepository(Document indexDoc, File JavaDoc directoryFile, Element directoryNode, String JavaDoc path, String JavaDoc solution) {
469         // TODO see if there is a localized attribute file for the current
470
// locale
471
String JavaDoc dirName = getValue(indexDoc, "/index/name", directoryFile.getName().replace('_', ' ')); //$NON-NLS-1$
472
String JavaDoc description = getValue(indexDoc, "/index/description", ""); //$NON-NLS-1$ //$NON-NLS-2$
473
String JavaDoc iconPath = getValue(indexDoc, "/index/icon", ""); //$NON-NLS-1$ //$NON-NLS-2$
474
String JavaDoc displayType = getValue(indexDoc, "/index/display-type", "icons"); //$NON-NLS-1$ //$NON-NLS-2$
475
boolean visible = getValue(indexDoc, "/index/visible", "false").equalsIgnoreCase("true"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
476
if (solution == null) {
477             directoryNode.addAttribute("name", solution); //$NON-NLS-1$
478
} else {
479             directoryNode.addAttribute("name", directoryFile.getName()); //$NON-NLS-1$
480
}
481         directoryNode.addElement("title").setText(dirName); //$NON-NLS-1$
482
// directoryNode.addElement( "path" ).setText( path ); //$NON-NLS-1$
483
directoryNode.addAttribute("path", path); //$NON-NLS-1$
484
directoryNode.addElement("description").setText(description); //$NON-NLS-1$
485
if (iconPath != null && !iconPath.equals("")) { //$NON-NLS-1$
486
String JavaDoc rolloverIconPath = null;
487             int rolloverIndex = iconPath.indexOf("|"); //$NON-NLS-1$
488
if (rolloverIndex > -1) {
489                 rolloverIconPath = iconPath.substring(rolloverIndex + 1);
490                 iconPath = iconPath.substring(0, rolloverIndex);
491             }
492             if (publishIcon(PentahoSystem.getApplicationContext().getSolutionPath(solution + File.separator + path), iconPath)) {
493                 directoryNode.addElement("icon").setText("getImage?image=icons/" + iconPath); //$NON-NLS-1$ //$NON-NLS-2$
494
} else {
495                 directoryNode.addElement("icon").setText(iconPath); //$NON-NLS-1$
496
}
497             if (rolloverIconPath != null) {
498                 if (publishIcon(PentahoSystem.getApplicationContext().getSolutionPath(solution + File.separator + path), rolloverIconPath)) {
499                     directoryNode.addElement("rollovericon").setText("getImage?image=icons/" + rolloverIconPath); //$NON-NLS-1$ //$NON-NLS-2$
500
} else {
501                     directoryNode.addElement("rollovericon").setText(rolloverIconPath); //$NON-NLS-1$
502
}
503             }
504         }
505         directoryNode.addAttribute("visible", Boolean.toString(visible)); //$NON-NLS-1$
506
directoryNode.addAttribute("displaytype", displayType); //$NON-NLS-1$
507
directoryNode.addElement("solution").setText(solution); //$NON-NLS-1$
508
}
509
510     private void addUrlToRepository(File JavaDoc file, Element parentNode, String JavaDoc solutionPath) {
511         // parse the .url file to get the contents
512
ActionResource urlResource = new ActionResource(file.getName(), IActionResource.SOLUTION_FILE_RESOURCE, "text/url", solutionPath); //$NON-NLS-1$
513
try {
514             String JavaDoc urlContent = getResourceAsString(urlResource);
515             StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(urlContent, "\n"); //$NON-NLS-1$
516
String JavaDoc url = null;
517             String JavaDoc title = file.getName();
518             String JavaDoc description = null;
519             String JavaDoc iconPath = null;
520             String JavaDoc target = null;
521             while (tokenizer.hasMoreTokens()) {
522                 String JavaDoc line = tokenizer.nextToken();
523                 int pos = line.indexOf('=');
524                 if (pos > 0) {
525                     String JavaDoc name = line.substring(0, pos);
526                     String JavaDoc value = line.substring(pos + 1);
527                     if ((value != null) && (value.length() > 0) && (value.charAt(value.length() - 1) == '\r')) {
528                         value = value.substring(0, value.length() - 1);
529                     }
530                     if ("URL".equalsIgnoreCase(name)) { //$NON-NLS-1$
531
url = value;
532                     }
533                     if ("name".equalsIgnoreCase(name)) { //$NON-NLS-1$
534
title = value;
535                     }
536                     if ("description".equalsIgnoreCase(name)) { //$NON-NLS-1$
537
description = value;
538                     }
539                     if ("icon".equalsIgnoreCase(name)) { //$NON-NLS-1$
540
iconPath = value;
541                     }
542                     if ("target".equalsIgnoreCase(name)) { //$NON-NLS-1$
543
target = value;
544                     }
545                 }
546             }
547             if (url != null) {
548                 // now create an entry for the database
549
Element dirNode = parentNode.addElement("file"); //$NON-NLS-1$
550
dirNode.addAttribute("type", FileInfo.FILE_TYPE_URL); //$NON-NLS-1$
551
dirNode.addElement("filename").setText(file.getName()); //$NON-NLS-1$
552
dirNode.addElement("title").setText(title); //$NON-NLS-1$
553
if (target != null) {
554                     dirNode.addElement("target").setText(target); //$NON-NLS-1$
555
}
556                 if (description != null) {
557                     dirNode.addElement("description").setText(description); //$NON-NLS-1$
558
}
559                 if (iconPath != null && !iconPath.equals("")) { //$NON-NLS-1$
560
String JavaDoc rolloverIconPath = null;
561                     int rolloverIndex = iconPath.indexOf("|"); //$NON-NLS-1$
562
if (rolloverIndex > -1) {
563                         rolloverIconPath = iconPath.substring(rolloverIndex + 1);
564                         iconPath = iconPath.substring(0, rolloverIndex);
565                     }
566                     if (publishIcon(file.getParentFile().getAbsolutePath(), iconPath)) {
567                         dirNode.addElement("icon").setText("getImage?image=icons/" + iconPath); //$NON-NLS-1$ //$NON-NLS-2$
568
} else {
569                         dirNode.addElement("icon").setText(iconPath); //$NON-NLS-1$
570
}
571                     if (rolloverIconPath != null) {
572                         if (publishIcon(PentahoSystem.getApplicationContext().getSolutionPath(solutionPath), rolloverIconPath)) {
573                             dirNode.addElement("rollovericon").setText("getImage?image=icons/" + rolloverIconPath); //$NON-NLS-1$ //$NON-NLS-2$
574
} else {
575                             dirNode.addElement("rollovericon").setText(rolloverIconPath); //$NON-NLS-1$
576
}
577                     }
578                 }
579                 dirNode.addElement("url").setText(url); //$NON-NLS-1$
580
dirNode.addAttribute("visible", "true"); //$NON-NLS-1$ //$NON-NLS-2$
581
dirNode.addAttribute("displaytype", FileInfo.FILE_DISPLAY_TYPE_URL); //$NON-NLS-1$
582
localizeDoc(dirNode, file);
583             }
584         } catch (IOException JavaDoc e) {
585         }
586     }
587
588     private void addToRepository(IActionSequence actionSequence, Element parentNode, File JavaDoc file) {
589         Element dirNode = parentNode.addElement("file"); //$NON-NLS-1$
590
dirNode.addAttribute("type", FileInfo.FILE_TYPE_ACTIVITY); //$NON-NLS-1$
591
if (actionSequence.getSequenceName() == null || actionSequence.getSolutionPath() == null || actionSequence.getSolutionName() == null) {
592             error(Messages.getString("SolutionRepository.ERROR_0008_ACTION_SEQUENCE_NAME_INVALID")); //$NON-NLS-1$
593
return;
594         }
595         dirNode.addElement("filename").setText(actionSequence.getSequenceName()); //$NON-NLS-1$
596
dirNode.addElement("path").setText(actionSequence.getSolutionPath()); //$NON-NLS-1$
597
dirNode.addElement("solution").setText(actionSequence.getSolutionName()); //$NON-NLS-1$
598
String JavaDoc title = actionSequence.getTitle();
599         if (title == null) {
600             dirNode.addElement("title").setText(actionSequence.getSequenceName()); //$NON-NLS-1$
601
} else {
602             dirNode.addElement("title").setText(title); //$NON-NLS-1$
603
}
604         String JavaDoc description = actionSequence.getDescription();
605         if (description == null) {
606             dirNode.addElement("description"); //$NON-NLS-1$
607
} else {
608             dirNode.addElement("description").setText(description); //$NON-NLS-1$
609
}
610         String JavaDoc author = actionSequence.getAuthor();
611         if (author == null) {
612             dirNode.addElement("author"); //$NON-NLS-1$
613
} else {
614             dirNode.addElement("author").setText(author); //$NON-NLS-1$
615
}
616         String JavaDoc iconPath = actionSequence.getIcon();
617         if (iconPath != null && !iconPath.equals("")) { //$NON-NLS-1$
618
String JavaDoc rolloverIconPath = null;
619             int rolloverIndex = iconPath.indexOf("|"); //$NON-NLS-1$
620
if (rolloverIndex > -1) {
621                 rolloverIconPath = iconPath.substring(rolloverIndex + 1);
622                 iconPath = iconPath.substring(0, rolloverIndex);
623             }
624             if (publishIcon(file.getParentFile().getAbsolutePath(), iconPath)) {
625                 dirNode.addElement("icon").setText("getImage?image=icons/" + iconPath); //$NON-NLS-1$ //$NON-NLS-2$
626
} else {
627                 dirNode.addElement("icon").setText(actionSequence.getIcon()); //$NON-NLS-1$
628
}
629             if (rolloverIconPath != null) {
630                 if (publishIcon(PentahoSystem.getApplicationContext().getSolutionPath(actionSequence.getSolutionName() + File.separator + actionSequence.getSolutionPath()), rolloverIconPath)) {
631                     dirNode.addElement("rollovericon").setText("getImage?image=icons/" + rolloverIconPath); //$NON-NLS-1$ //$NON-NLS-2$
632
} else {
633                     dirNode.addElement("rollovericon").setText(rolloverIconPath); //$NON-NLS-1$
634
}
635             }
636         }
637         String JavaDoc displayType = actionSequence.getResultType();
638         if ((displayType == null) || ("none".equalsIgnoreCase(displayType))) { //$NON-NLS-1$
639
// this should be hidden from users
640
dirNode.addAttribute("visible", "false"); //$NON-NLS-1$ //$NON-NLS-2$
641
} else {
642             dirNode.addAttribute("visible", "true"); //$NON-NLS-1$ //$NON-NLS-2$
643
dirNode.addAttribute("displaytype", displayType); //$NON-NLS-1$
644
}
645     }
646
647     private boolean publishIcon(String JavaDoc dirPath, String JavaDoc iconPath) {
648         File JavaDoc iconSource = new File JavaDoc(dirPath + File.separator + iconPath);
649         if (iconSource.exists()) {
650             File JavaDoc tmpDir = getFile("system/tmp/icons", true); //$NON-NLS-1$
651
tmpDir.mkdirs();
652             File JavaDoc iconDestintation = new File JavaDoc(tmpDir.getAbsoluteFile() + File.separator + iconPath);
653             if (iconDestintation.exists()) {
654                 iconDestintation.delete();
655             }
656             try {
657                 // create a byte array to hold the bits and nibbles
658
long size = iconSource.length();
659                 byte bytes[] = new byte[(int) size];
660                 // read the file into the byte array
661
FileInputStream JavaDoc stream = new FileInputStream JavaDoc(iconSource);
662                 try {
663                     FileOutputStream JavaDoc outputStream = new FileOutputStream JavaDoc(iconDestintation);
664                     try {
665                         stream.read(bytes);
666                         outputStream.write(bytes);
667                         outputStream.flush();
668                     } finally {
669                         outputStream.close();
670                     }
671                 } finally {
672                     stream.close();
673                 }
674             } catch (FileNotFoundException JavaDoc e) {
675                 // this one is not very likey
676
} catch (IOException JavaDoc e) {
677             }
678             return true;
679         } else {
680             return false;
681         }
682     }
683
684     public Document getSolutions(int actionOperation) {
685         if (repository == null) {
686             publish(session, loggingLevel);
687         }
688         return repository;
689     }
690
691     public Document getActionSequences(String JavaDoc solution, String JavaDoc path, boolean subDirectories, boolean visibleOnly, int actionOperation) {
692         List JavaDoc nodes;
693         if (solution == null) {
694             nodes = getSolutionNames();
695         } else {
696             nodes = getFileListIterator(solution, path, subDirectories, visibleOnly);
697         }
698         Document document = DocumentHelper.createDocument();
699         Element root = document.addElement("files"); //$NON-NLS-1$
700
Element pathNames = root.addElement("location"); //$NON-NLS-1$
701

702         pathNames.setText(getPathNames(solution, path));
703
704         Iterator JavaDoc nodeIterator = nodes.iterator();
705         while (nodeIterator.hasNext()) {
706             Node node = (Node) nodeIterator.next();
707             root.add((Node) node.clone());
708         }
709         return document;
710     }
711
712     public List JavaDoc getSolutionNames() {
713         String JavaDoc xPath = "/repository/file"; //$NON-NLS-1$
714
// String xPath =
715
// "/repository/file[@type='"+FileInfo.FILE_TYPE_FOLDER+"']";
716
// //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
717
if (repository == null) {
718             publish(session, loggingLevel);
719         }
720         return repository.selectNodes(xPath);
721     }
722
723     private String JavaDoc getPathNames(String JavaDoc solutionId, String JavaDoc path) {
724         if (repository == null) {
725             publish(session, loggingLevel);
726         }
727         if (solutionId == null) {
728             return ""; //$NON-NLS-1$
729
}
730
731         String JavaDoc xPath = "/repository/file[@type='" + FileInfo.FILE_TYPE_FOLDER + "'][@name='" + solutionId + "']"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
732

733         if (path != null) {
734             String JavaDoc folders[] = path.split("/"); //$NON-NLS-1$
735
if (folders != null) {
736                 for (int idx = 0; idx < folders.length; idx++) {
737                     xPath += "/file[@type='" + FileInfo.FILE_TYPE_FOLDER + "'][@name='" + folders[idx] + "']"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
738
xPath += "[@visible='true']"; //$NON-NLS-1$
739
}
740             }
741         }
742
743         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
744         List JavaDoc list = repository.selectNodes(xPath);
745         if (list != null && list.size() > 0) {
746             // grab the first one
747
Element node = (Element) list.get(0);
748             // walk up the ancestors
749
boolean done = false;
750             while (node != null && !done) {
751                 Node titleNode = node.selectSingleNode("title"); //$NON-NLS-1$
752
if (titleNode != null) {
753                     String JavaDoc name = titleNode.getText();
754                     sb.insert(0, name + "/"); //$NON-NLS-1$
755
} else {
756                     // if we don't have a title node then there is nothing more we can do to construct the path
757
done = true;
758                 }
759                 node = node.getParent();
760             }
761         }
762         return sb.toString();
763
764     }
765
766     private List JavaDoc getFileListIterator(String JavaDoc solutionId, String JavaDoc path, boolean subDirectories, boolean visibleOnly) {
767         if (repository == null) {
768             publish(session, loggingLevel);
769         }
770         String JavaDoc xPath;
771         if (solutionId == null) {
772             xPath = "/repository/file[@type='" + FileInfo.FILE_TYPE_FOLDER + "']"; //$NON-NLS-1$ //$NON-NLS-2$
773
} else {
774             xPath = "/repository/file[@type='" + FileInfo.FILE_TYPE_FOLDER + "'][@name='" + solutionId + "']"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
775
}
776         if (path != null) {
777             String JavaDoc folders[] = path.split("/"); //$NON-NLS-1$
778
if (folders != null) {
779                 for (int idx = 0; idx < folders.length; idx++) {
780                     xPath += "/file[@type='" + FileInfo.FILE_TYPE_FOLDER + "'][@name='" + folders[idx] + "']"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
781
if (visibleOnly) {
782                         xPath += "[@visible='true']"; //$NON-NLS-1$
783
}
784                 }
785             }
786         }
787         if (subDirectories) {
788             xPath = "descendant-or-self::" + xPath; //$NON-NLS-1$
789
}
790         if (debug)
791             debug(Messages.getString("SolutionRepository.DEBUG_FILE_LIST_XPATH", xPath)); //$NON-NLS-1$
792
return repository.selectNodes(xPath);
793     }
794
795     public String JavaDoc getValue(Document doc, String JavaDoc xPath, String JavaDoc defaultValue) {
796         if (doc != null) {
797             Node node = doc.selectSingleNode(xPath);
798             if (node == null) {
799                 return defaultValue;
800             }
801             return node.getText();
802         }
803         return defaultValue;
804     }
805
806     public Document getSolutionStructure(int actionOperation) {
807         Document document = DocumentHelper.createDocument();
808         File JavaDoc rootDir = getFile(EMPTY_STR, false);
809         Element root = document.addElement(ROOT_NODE_NAME).addAttribute(LOCATION_ATTR_NAME, rootDir.getAbsolutePath());
810         processSolutionTree(root, rootDir);
811         return document;
812     }
813
814     public Document getSolutionTree(int actionOperation) {
815         return (SolutionReposUtil.getActionSequences(new FileSolutionFile(rootFile, rootFile), actionOperation));
816     }
817
818     private void processSolutionTree(Element parentNode, File JavaDoc targetFile) {
819         if (targetFile.isDirectory()) {
820             if (!SolutionReposUtil.ignoreDirectory(targetFile.getName())) {
821                 Element childNode = parentNode.addElement(ENTRY_NODE_NAME).addAttribute(TYPE_ATTR_NAME, DIRECTORY_ATTR).addAttribute(NAME_ATTR_NAME, targetFile.getName());
822                 File JavaDoc files[] = targetFile.listFiles();
823                 for (int i = 0; i < files.length; i++) {
824                     File JavaDoc file = files[i];
825                     processSolutionTree(childNode, file);
826                 }
827             }
828         } else {
829             if (!targetFile.isHidden() && !SolutionReposUtil.ignoreFile(targetFile.getName())) {
830                 parentNode.addElement(ENTRY_NODE_NAME).addAttribute(TYPE_ATTR_NAME, FILE_ATTR).addAttribute(NAME_ATTR_NAME, targetFile.getName());
831             }
832         }
833     }
834
835     public InputStream JavaDoc getSolutionFileData(String JavaDoc repositoryRoot, String JavaDoc solutionName, String JavaDoc filePath, String JavaDoc fileName) {
836         File JavaDoc solutionFile = new File JavaDoc(repositoryRoot + File.pathSeparator + solutionName + File.pathSeparator + filePath + File.pathSeparator + fileName);
837         if (solutionFile.exists()) {
838             try {
839                 InputStream JavaDoc is = new FileInputStream JavaDoc(solutionFile);
840                 return is;
841             } catch (FileNotFoundException JavaDoc e) {
842                 // TODO Auto-generated catch block
843
e.printStackTrace();
844             }
845         }
846         return null;
847     }
848
849     // -----------------------------------------------------------------------
850
// Methods from PentahoSystem
851
public boolean resourceExists(String JavaDoc solutionPath) {
852         String JavaDoc filePath = PentahoSystem.getApplicationContext().getSolutionPath(solutionPath);
853         File JavaDoc file = new File JavaDoc(filePath);
854         return file.exists();
855     }
856
857     public long resourceSize(String JavaDoc solutionPath) {
858         if (!resourceExists(solutionPath)) {
859             return -1;
860         }
861         String JavaDoc filePath = PentahoSystem.getApplicationContext().getSolutionPath(solutionPath);
862         File JavaDoc file = new File JavaDoc(filePath);
863         return file.length();
864     }
865
866     public InputStream JavaDoc getResourceInputStream(IActionResource actionResource) {
867         int resourceSource = actionResource.getSourceType();
868         String JavaDoc realPath = null;
869         if (resourceSource == IActionResource.URL_RESOURCE) {
870             return HttpUtil.getURLInputStream(actionResource.getAddress());
871         } else if (resourceSource == IActionResource.UNKNOWN_RESOURCE) {
872             return null;
873         } else if (resourceSource == IActionResource.SOLUTION_FILE_RESOURCE) {
874             realPath = PentahoSystem.getApplicationContext().getSolutionPath(actionResource.getAddress());
875         } else if (resourceSource == IActionResource.FILE_RESOURCE) {
876             realPath = actionResource.getAddress();
877         }
878         File JavaDoc file = new File JavaDoc(realPath);
879         file = getLocalizedFile(file);
880         if (!file.exists()) {
881             error(Messages.getErrorString("SOLREPO.ERROR_0006_MISSING_RESOURCE", realPath)); //$NON-NLS-1$
882
return null;
883         }
884         try {
885             FileInputStream JavaDoc inputStream = new FileInputStream JavaDoc(file);
886             return inputStream;
887         } catch (FileNotFoundException JavaDoc e) {
888             error(Messages.getErrorString("SOLREPO.ERROR_0006_MISSING_RESOURCE", realPath)); //$NON-NLS-1$
889
}
890         return null;
891     }
892
893     public InputStream JavaDoc getResourceInputStream(String JavaDoc solutionPath) {
894         ActionResource resource = new ActionResource("", IActionResource.SOLUTION_FILE_RESOURCE, "text/xml", //$NON-NLS-1$ //$NON-NLS-2$
895
solutionPath);
896         return getResourceInputStream(resource);
897     }
898
899     public Reader JavaDoc getResourceReader(IActionResource actionResource) throws FileNotFoundException JavaDoc, IOException JavaDoc {
900         // TODO support locales here
901
int resourceSource = actionResource.getSourceType();
902         String JavaDoc realPath = null;
903         if (resourceSource == IActionResource.URL_RESOURCE) {
904             return HttpUtil.getURLReader(actionResource.getAddress());
905         } else if (resourceSource == IActionResource.UNKNOWN_RESOURCE) {
906             return null;
907         } else if (resourceSource == IActionResource.SOLUTION_FILE_RESOURCE) {
908             realPath = PentahoSystem.getApplicationContext().getSolutionPath(actionResource.getAddress());
909         } else if (resourceSource == IActionResource.FILE_RESOURCE) {
910             realPath = actionResource.getAddress();
911         }
912         File JavaDoc file = new File JavaDoc(realPath);
913         file = getLocalizedFile(file);
914         if (!file.exists()) {
915             error(Messages.getErrorString("SOLREPO.ERROR_0006_MISSING_RESOURCE", realPath)); //$NON-NLS-1$
916
return null;
917         }
918         // FileReader reader = new FileReader( file );
919
FileInputStream JavaDoc fin = new FileInputStream JavaDoc(file);
920         InputStreamReader JavaDoc reader = new InputStreamReader JavaDoc(fin, LocaleHelper.getSystemEncoding());
921         return reader;
922     }
923
924     public Reader JavaDoc getResourceReader(String JavaDoc solutionPath) throws FileNotFoundException JavaDoc, IOException JavaDoc {
925         ActionResource resource = new ActionResource("", IActionResource.SOLUTION_FILE_RESOURCE, "text/xml", //$NON-NLS-1$ //$NON-NLS-2$
926
solutionPath);
927         return getResourceReader(resource);
928     }
929
930     public String JavaDoc getResourceAsString(IActionResource actionResource) throws IOException JavaDoc {
931         // TODO support locales here
932
StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
933         Reader JavaDoc reader = getResourceReader(actionResource);
934         if (reader == null) {
935             return null;
936         }
937         try {
938             char chars[] = new char[1024];
939             int charsRead = reader.read(chars);
940             while (charsRead > 0) {
941                 buffer.append(chars, 0, charsRead);
942                 charsRead = reader.read(chars);
943             }
944             return buffer.toString();
945         } finally {
946             reader.close();
947         }
948     }
949
950     public String JavaDoc getResourceAsString(String JavaDoc solutionPath) throws IOException JavaDoc {
951         ActionResource resource = new ActionResource("", IActionResource.SOLUTION_FILE_RESOURCE, "text/xml", //$NON-NLS-1$ //$NON-NLS-2$
952
solutionPath);
953         return getResourceAsString(resource);
954     }
955
956     protected File JavaDoc getLocalizedFile(File JavaDoc resourceFile) {
957         // try to find a localized variant of this file
958
String JavaDoc fileName = resourceFile.getName();
959         int idx = fileName.indexOf('.');
960         String JavaDoc baseName = fileName.substring(0, idx);
961         String JavaDoc extension = fileName.substring(idx);
962         File JavaDoc directory = resourceFile.getParentFile();
963         String JavaDoc language = locale.getLanguage();
964         String JavaDoc country = locale.getCountry();
965         String JavaDoc variant = locale.getVariant();
966         File JavaDoc localeFile = null;
967         if (!variant.equals("")) { //$NON-NLS-1$
968
localeFile = new File JavaDoc(directory, baseName + "_" + language + "_" + country + "_" + variant + extension); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
969
}
970         if (localeFile == null || !localeFile.exists()) {
971             localeFile = new File JavaDoc(directory, baseName + "_" + language + "_" + country + extension); //$NON-NLS-1$//$NON-NLS-2$
972
}
973         if (!localeFile.exists()) {
974             localeFile = new File JavaDoc(directory, baseName + "_" + language + extension); //$NON-NLS-1$
975
}
976         if (!localeFile.exists()) {
977             localeFile = new File JavaDoc(directory, baseName + extension);
978         }
979         if (localeFile.exists()) {
980             return localeFile;
981         } else {
982             return resourceFile;
983         }
984     }
985
986     public DataSource JavaDoc getResourceDataSource(String JavaDoc solutionPath) {
987         ActionResource resource = new ActionResource("", IActionResource.SOLUTION_FILE_RESOURCE, "text/xml", //$NON-NLS-1$ //$NON-NLS-2$
988
solutionPath);
989         return getResourceDataSource(resource);
990     }
991
992     public DataSource JavaDoc getResourceDataSource(IActionResource actionResource) {
993         // TODO support locales here
994
int resourceSource = actionResource.getSourceType();
995         String JavaDoc realPath = null;
996         if (resourceSource == IActionResource.URL_RESOURCE) {
997             try {
998                 URL JavaDoc url = new URL JavaDoc(actionResource.getAddress());
999                 return (new URLDataSource JavaDoc(url));
1000            } catch (Throwable JavaDoc t) {
1001                return (null);
1002            }
1003        } else if (resourceSource == IActionResource.UNKNOWN_RESOURCE) {
1004            return null;
1005        } else if (resourceSource == IActionResource.SOLUTION_FILE_RESOURCE) {
1006            realPath = PentahoSystem.getApplicationContext().getSolutionPath(actionResource.getAddress());
1007        } else if (resourceSource == IActionResource.FILE_RESOURCE) {
1008            realPath = actionResource.getAddress();
1009        }
1010        File JavaDoc file = new File JavaDoc(realPath);
1011        file = getLocalizedFile(file);
1012        if (!file.exists()) {
1013            return null;
1014        }
1015        return (new FileDataSource JavaDoc(file));
1016    }
1017
1018    public Document getResourceAsDocument(String JavaDoc solutionPath) throws IOException JavaDoc {
1019        ActionResource resource = new ActionResource("", IActionResource.SOLUTION_FILE_RESOURCE, "text/xml", //$NON-NLS-1$ //$NON-NLS-2$
1020
solutionPath);
1021        return getResourceAsDocument(resource);
1022    }
1023
1024    public Document getResourceAsDocument(IActionResource actionResource) throws IOException JavaDoc {
1025        // TODO support locales here
1026
String JavaDoc xml = getResourceAsString(actionResource);
1027        if (xml == null) {
1028            return null;
1029        } else {
1030            return XmlHelper.getDocFromString(xml);
1031        }
1032    }
1033
1034    public boolean removeSolutionFile(String JavaDoc solution, String JavaDoc path, String JavaDoc fileName) {
1035        String JavaDoc filePath = solution + path + fileName;
1036        File JavaDoc deleteFile = new File JavaDoc(filePath);
1037        if (deleteFile.exists()) {
1038            if (!deleteFile.isDirectory()) {
1039                return deleteFile.delete();
1040            } else { // recursively delete all the files under this directory
1041
// and then delete the directory
1042
return deleteFolder(deleteFile);
1043            }
1044        }
1045        return false;
1046    }
1047
1048    private boolean deleteFolder(File JavaDoc dir) {
1049        if (!dir.isDirectory()) {
1050            logger.warn(Messages.getString("SolutionRepository.USER_DELETE_FOLDER_WARNING")); //$NON-NLS-1$
1051
return false;
1052        }
1053        String JavaDoc[] files = dir.list();
1054        for (int i = 0; i < files.length; i++) {
1055            File JavaDoc file = new File JavaDoc(dir.getAbsolutePath() + File.separator + files[i]);
1056            if (file.isDirectory()) {
1057                deleteFolder(file);
1058            } else {
1059                file.delete();
1060            }
1061        }
1062        return dir.delete();
1063    }
1064
1065    public int addSolutionFile(String JavaDoc baseUrl, String JavaDoc path, String JavaDoc fileName, File JavaDoc f, boolean overwrite) {
1066        File JavaDoc fNew = new File JavaDoc(baseUrl + path + fileName);
1067
1068        int status = ISolutionRepository.FILE_ADD_SUCCESSFUL;
1069
1070        if (fNew.exists() && !overwrite) {
1071            status = ISolutionRepository.FILE_EXISTS;
1072        } else {
1073            FileChannel JavaDoc in = null, out = null;
1074            try {
1075                in = new FileInputStream JavaDoc(f).getChannel();
1076                out = new FileOutputStream JavaDoc(fNew).getChannel();
1077                out.transferFrom(in, 0, in.size());
1078            } catch (Exception JavaDoc e) {
1079                logger.error(e.toString());
1080                status = ISolutionRepository.FILE_ADD_FAILED;
1081            } finally {
1082                try {
1083                    if (in != null)
1084                        in.close();
1085                    if (out != null)
1086                        out.close();
1087                } catch (Exception JavaDoc e) {
1088                }
1089            }
1090        }
1091        return status;
1092    }
1093
1094    public int addSolutionFile(String JavaDoc baseUrl, String JavaDoc path, String JavaDoc fileName, byte[] data, boolean overwrite) {
1095// baseUrl = baseUrl + path;
1096
File JavaDoc fNew = new File JavaDoc(baseUrl + path + fileName);
1097        int status = ISolutionRepository.FILE_ADD_SUCCESSFUL;
1098        if (fNew.exists() && !overwrite) {
1099            status = ISolutionRepository.FILE_EXISTS;
1100        } else {
1101            FileOutputStream JavaDoc fNewOut = null;
1102            try {
1103                fNewOut = new FileOutputStream JavaDoc(fNew);
1104                fNewOut.write(data);
1105            } catch (Exception JavaDoc e) {
1106                status = ISolutionRepository.FILE_ADD_FAILED;
1107                logger.error(e.toString());
1108            } finally {
1109                try {
1110                    fNewOut.close();
1111                } catch (Exception JavaDoc e) {
1112                }
1113            }
1114        }
1115        return status;
1116    }
1117
1118    public Document getSolutions(String JavaDoc solutionName, String JavaDoc pathName, int actionOperation) {
1119        return getSolutions(actionOperation);
1120    }
1121
1122    public String JavaDoc[] getAllActionSequences() {
1123        File JavaDoc rootDir = getFile("", false); //$NON-NLS-1$
1124
List JavaDoc files = new ArrayList JavaDoc();
1125        files = getAllActionSequences(rootDir, files);
1126        String JavaDoc[] value = new String JavaDoc[files.size()];
1127        Iterator JavaDoc iter = files.iterator();
1128        int i = 0;
1129        int solutionPathOffset = PentahoSystem.getApplicationContext().getSolutionPath("").length(); //$NON-NLS-1$
1130
while (iter.hasNext()) {
1131            File JavaDoc file = (File JavaDoc) iter.next();
1132            String JavaDoc filePath = file.getAbsolutePath();
1133            filePath = filePath.substring(solutionPathOffset);
1134            filePath = filePath.replace('\\', '/');
1135            value[i++] = filePath;
1136        }
1137        return value;
1138    }
1139
1140    private List JavaDoc getAllActionSequences(File JavaDoc rootDir, List JavaDoc files) {
1141        if (!rootDir.isDirectory()) {
1142            return files;
1143        }
1144        File JavaDoc[] fileArray = rootDir.listFiles(new xActionFileFilter());
1145        for (int i = 0; i < fileArray.length; i++) {
1146            files.add(fileArray[i]);
1147        }
1148        fileArray = rootDir.listFiles();
1149        for (int i = 0; i < fileArray.length; i++) {
1150            if (fileArray[i].isDirectory()) {
1151                getAllActionSequences(fileArray[i], files);
1152            }
1153        }
1154        return files;
1155    }
1156
1157    public long getSolutionFileLastModified(String JavaDoc path) {
1158        File JavaDoc file = getFile(path, false);
1159        long mod = -1;
1160        if (file != null) {
1161            mod = file.lastModified();
1162        }
1163        return mod;
1164    }
1165
1166    class xActionFileFilter implements FilenameFilter JavaDoc {
1167        public boolean accept(File JavaDoc dir, String JavaDoc name) {
1168            int seperatorIndex = name.lastIndexOf('.');
1169            if (seperatorIndex != -1) {
1170                return name.substring(name.lastIndexOf('.')).equalsIgnoreCase(".xaction"); //$NON-NLS-1$
1171
}
1172            return false;
1173        }
1174    }
1175
1176}
1177
Popular Tags