KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > util > Utils


1 /*
2  * @version 1.0.0.0
3  * @since Enhydra5.1
4  * @author Sasa Bojanic
5  * @author Nenad Stefanovic
6  * @author Zoran Milakovic
7  * @author Sinisa Milosevic
8  */

9
10 package org.enhydra.util;
11
12
13 import java.io.File JavaDoc;
14 import java.io.FileFilter JavaDoc;
15 import java.io.InputStream JavaDoc;
16 import java.lang.reflect.Method JavaDoc;
17 import java.util.ArrayList JavaDoc;
18 import java.util.Collection JavaDoc;
19 import java.util.Enumeration JavaDoc;
20 import java.util.HashSet JavaDoc;
21 import java.util.Iterator JavaDoc;
22 import java.util.List JavaDoc;
23 import java.util.Set JavaDoc;
24 import java.util.jar.JarFile JavaDoc;
25 import java.util.zip.ZipEntry JavaDoc;
26
27 import javax.xml.parsers.DocumentBuilder JavaDoc;
28 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
29
30 import org.w3c.dom.Document JavaDoc;
31 import org.w3c.dom.Element JavaDoc;
32 import org.w3c.dom.NodeList JavaDoc;
33
34 import com.lutris.appserver.server.Enhydra;
35 import com.lutris.logging.Logger;
36 import com.lutris.util.Config;
37
38 /**
39 * Utility methods.
40 */

41 public class Utils {
42
43
44     /**
45     * Returns a List of DODS classes that represents the Database tables which are
46     * used by application given by it's name, and are cached.
47     */

48     public static List JavaDoc getCachedDOClassesForApplication(Config cfg, ClassLoader JavaDoc cl) {
49         List JavaDoc retVal = new ArrayList JavaDoc();
50         boolean loaded = false;
51
52       String JavaDoc[] databaseNames;
53         //get classes from doml file
54
try {
55             databaseNames = cfg.getStrings("DatabaseManager.Databases");
56             for (int i = 0; i < databaseNames.length; i++) {
57                 String JavaDoc databaseName = databaseNames[i];
58                 Object JavaDoc domlPath =
59                     cfg.get("DatabaseManager.DB." + databaseName + ".domlFile");
60                 if (domlPath != null)
61                     retVal.addAll(
62                         getCachedDOClassesFromDoml(
63                             domlPath.toString(), cl, databaseName));
64             }
65             if (retVal.isEmpty())
66                 loaded = false;
67             else
68                 loaded = true;
69         } catch (Throwable JavaDoc e) {
70             retVal.clear();
71             loaded = false;
72         }
73
74
75         //get classes from doml on class path
76
if(!loaded) {
77             try {
78                 databaseNames = cfg.getStrings("DatabaseManager.Databases");
79
80                 for (int i = 0; i < databaseNames.length; i++) {
81                         String JavaDoc databaseName = databaseNames[i];
82                         Object JavaDoc domlPath = cfg.get("DatabaseManager.DB." + databaseName + ".DomlClasspath");
83                         String JavaDoc domlClassPathName = domlPath.toString();
84                         InputStream JavaDoc domlStream =cl.getResourceAsStream(domlClassPathName);
85                         if (domlStream != null) {
86                             retVal.addAll(
87                                 getCachedDOClassesFromDoml(
88                                     domlStream,
89                                     cl,databaseName));
90                         } else {
91                             Enhydra.getLogChannel().write(
92                                 Logger.DEBUG,
93                                 "Resource " +domlClassPathName+" don't exist on application classpath!");
94                         }
95                     }
96
97                     if (retVal.isEmpty())
98                         loaded = false;
99                     else
100                         loaded = true;
101
102             }catch(Throwable JavaDoc e) {
103                 retVal.clear();
104               loaded = false;
105 //e.printStackTrace();
106
}
107
108         }
109
110         //get classes from list in xml file
111
if (!loaded) {
112             try {
113                 databaseNames = cfg.getStrings("DatabaseManager.Databases");
114                 for (int i = 0; i < databaseNames.length; i++) {
115                     String JavaDoc databaseName = databaseNames[i];
116 // System.out.println("databaseName "+databaseName);
117
Object JavaDoc classList =
118                         cfg.get(
119                             "DatabaseManager.DB." + databaseName + ".ClassList");
120                     if (classList != null) {
121                         retVal.addAll(
122                             getCachedDOClassesFromClassList(
123                                 new File JavaDoc(classList.toString()),cl,databaseName));
124                     }
125                 }
126                 if (retVal.isEmpty())
127                     loaded = false;
128                 else
129                     loaded = true;
130             } catch (Throwable JavaDoc e) {
131                 retVal.clear();
132                 loaded = false;
133             }
134         }
135
136         //get classes from list in xml file, when xml file is in classpath
137
if (!loaded) {
138             try {
139             databaseNames = cfg.getStrings("DatabaseManager.Databases");
140                 InputStream JavaDoc classListStream =
141                     cl.getResourceAsStream(
142                         "org/enhydra/dods/DODSClassList.xml");
143                 if (classListStream != null) {
144                     retVal.addAll(getCachedDOClassesFromClassListAsResource(classListStream,cl,databaseNames[0]));
145                 } else {
146                     Enhydra.getLogChannel().write(
147                         Logger.DEBUG,
148                         "Resource org/enhydra/dods/DODSClassList.xml don't exist !");
149                 }
150                 if (retVal.isEmpty())
151                     loaded = false;
152                 else
153                     loaded = true;
154             } catch (Throwable JavaDoc e) {
155                 retVal.clear();
156                 loaded = false;
157             }
158         }
159
160         //get classes from classpath
161
if (!loaded) {
162             //Get the classpath from the config file.
163
String JavaDoc[] classPath = new String JavaDoc[0];
164           String JavaDoc cpKey = "Server.ClassPath";
165             if (cfg.containsKey(cpKey)) {
166                 try {
167                     classPath = cfg.getStrings(cpKey);
168                     return getCachedDOClassesForPath(
169                         classPath[0],
170                         cl,"");
171                 } catch (Throwable JavaDoc ex) {
172 // ex.printStackTrace();
173
}
174             }
175         }
176         return retVal;
177     }
178
179
180
181     /**
182      * Find class names in specified doml file and add this classes in cache.
183      * @param domlPath path to doml file
184      * @param cl class loader
185      * @return list with loaded classes
186      */

187    public static List JavaDoc getCachedDOClassesFromDoml(InputStream JavaDoc doml,ClassLoader JavaDoc cl,String JavaDoc databaseName) {
188      List JavaDoc retVal = new ArrayList JavaDoc();
189      try {
190
191 // File domlFile = new File(domlPath);
192
DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
193      DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
194 // if( domlFile.exists() ) {
195
Document JavaDoc doc = builder.parse(doml);
196        NodeList JavaDoc tableNodes = doc.getElementsByTagName("table");
197        for(int i = 0;i < tableNodes.getLength();i++) {
198          String JavaDoc tableName = ((Element JavaDoc)tableNodes.item(i)).getAttribute("id");
199          if( tableName.startsWith("root.") )
200             tableName = tableName.substring(5, tableName.length());
201          String JavaDoc tableClassName = tableName + "DO";
202          //System.out.println("Trying to load class "+tableClassName);
203
Class JavaDoc cls=cl.loadClass(tableClassName);
204          // if this is a cached DO class,
205
// must contain methods getCacheDodsTableName() and refreshCache()
206
// I am searching for these methods, and if there are no
207
// such methods, exception will be thrown, and className
208
// won't be added to the list
209
Method JavaDoc mth;
210          mth=cls.getMethod("refreshCache",new Class JavaDoc[] {});
211          mth=cls.getMethod("getConfigurationAdministration",new Class JavaDoc[] {});
212          retVal.add(new DOTable(databaseName,cls));
213          //retVal.add(cls);
214
}
215 // } else {
216
// Enhydra.getLogChannel().write(Logger.DEBUG,
217
// "Doml file "+domlPath+" don't exist !");
218
// }
219

220      }catch(Throwable JavaDoc e) {
221         e.printStackTrace();
222      }
223      return retVal;
224    }
225
226
227     /**
228      * Find class names in specified doml file and add this classes in cache.
229      * @param domlPath path to doml file
230      * @param cl class loader
231      * @return list with loaded classes
232      */

233    public static List JavaDoc getCachedDOClassesFromDoml(String JavaDoc domlPath,ClassLoader JavaDoc cl, String JavaDoc databaseName) {
234      List JavaDoc retVal = new ArrayList JavaDoc();
235      try {
236
237      File JavaDoc domlFile = new File JavaDoc(domlPath);
238      DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
239      DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
240      if( domlFile.exists() ) {
241        Document JavaDoc doc = builder.parse(domlFile);
242        NodeList JavaDoc tableNodes = doc.getElementsByTagName("table");
243        for(int i = 0;i < tableNodes.getLength();i++) {
244          String JavaDoc tableName = ((Element JavaDoc)tableNodes.item(i)).getAttribute("id");
245          if( tableName.startsWith("root.") )
246             tableName = tableName.substring(5, tableName.length());
247          String JavaDoc tableClassName = tableName + "DO";
248          //System.out.println("Trying to load class "+tableClassName);
249
Class JavaDoc cls=cl.loadClass(tableClassName);
250          // if this is a cached DO class,
251
// must contain methods getCacheDodsTableName() and refreshCache()
252
// I am searching for these methods, and if there are no
253
// such methods, exception will be thrown, and className
254
// won't be added to the list
255
Method JavaDoc mth;
256          mth=cls.getMethod("refreshCache",new Class JavaDoc[] {});
257          mth=cls.getMethod("getConfigurationAdministration",new Class JavaDoc[] {});
258          retVal.add(new DOTable(databaseName, cls));
259        }
260      } else {
261         Enhydra.getLogChannel().write(Logger.DEBUG,
262                                           "Doml file "+domlPath+" don't exist !");
263      }
264
265      }catch(Throwable JavaDoc e) {
266 // e.printStackTrace();
267
Enhydra.getLogChannel().write(Logger.DEBUG,
268                                              "Loading DO classes from doml file was unsuccessful!");
269      }
270      return retVal;
271    }
272
273    /**
274     * Find class names in specified ClassList file and add this classes in cache.
275     * @param classListPath path to ClassList file
276     * @param cl class loader
277     * @return list with loaded classes
278     */

279    public static List JavaDoc getCachedDOClassesFromClassList(File JavaDoc classListFile,ClassLoader JavaDoc cl, String JavaDoc databaseName) {
280         List JavaDoc retVal = new ArrayList JavaDoc();
281         try {
282
283         DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
284         DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
285         if( classListFile.exists() ) {
286           Document JavaDoc doc = builder.parse(classListFile);
287           NodeList JavaDoc classesNodes = doc.getElementsByTagName("CLASSES");
288           for(int j=0; j<classesNodes.getLength(); j++) {
289          Element JavaDoc docClasses = (Element JavaDoc)classesNodes.item(j);
290         String JavaDoc dbName = ((Element JavaDoc)classesNodes.item(j)).getAttribute("databaseName");
291         if(dbName==null || dbName.equals(""))
292            dbName = databaseName;
293
294           NodeList JavaDoc tableNodes = doc.getElementsByTagName("CLASS");
295           for(int i = 0;i < tableNodes.getLength();i++) {
296             String JavaDoc tableName = ((Element JavaDoc)tableNodes.item(i)).getAttribute("name");
297             if( tableName.startsWith("root.") )
298                tableName = tableName.substring(5, tableName.length());
299             String JavaDoc tableClassName = tableName;
300             //System.out.println("Trying to load class "+tableClassName);
301
Class JavaDoc cls=cl.loadClass(tableClassName);
302             // if this is a cached DO class,
303
// must contain methods getCacheDodsTableName() and refreshCache()
304
// I am searching for these methods, and if there are no
305
// such methods, exception will be thrown, and className
306
// won't be added to the list
307
Method JavaDoc mth;
308             mth=cls.getMethod("refreshCache",new Class JavaDoc[] {});
309             mth=cls.getMethod("getConfigurationAdministration",new Class JavaDoc[] {});
310             retVal.add(new DOTable(databaseName,cls));
311           }
312          }
313         } else {
314            Enhydra.getLogChannel().write(Logger.DEBUG,
315                                              "ClassList file "+classListFile.getAbsolutePath()+" don't exist !");
316         }
317
318         }catch(Throwable JavaDoc e) {
319 // e.printStackTrace();
320
Enhydra.getLogChannel().write(Logger.DEBUG,
321                                              "Loading DO classes from class list was unsuccessful!");
322         }
323         return retVal;
324       }
325
326     /**
327         * Find class names in specified ClassList file and add this classes in cache.
328         * @param classListPath path to ClassList file
329         * @param cl class loader
330         * @return list with loaded classes
331         */

332        public static List JavaDoc getCachedDOClassesFromClassListAsResource(InputStream JavaDoc classListInputStream,ClassLoader JavaDoc cl,String JavaDoc databaseName) {
333             List JavaDoc retVal = new ArrayList JavaDoc();
334             try {
335           DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
336           DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
337           Document JavaDoc doc = builder.parse(classListInputStream);
338           NodeList JavaDoc classesNodes = doc.getElementsByTagName("CLASSES");
339           for(int j=0; j<classesNodes.getLength(); j++) {
340          Element JavaDoc docClasses = (Element JavaDoc)classesNodes.item(j);
341         String JavaDoc dbName = ((Element JavaDoc)classesNodes.item(j)).getAttribute("databaseName");
342         if(dbName==null || dbName.equals(""))
343            dbName = databaseName;
344          NodeList JavaDoc tableNodes = docClasses.getElementsByTagName("CLASS");
345            for(int i = 0;i < tableNodes.getLength();i++) {
346                String JavaDoc tableName = ((Element JavaDoc)tableNodes.item(i)).getAttribute("name");
347                if( tableName.startsWith("root.") )
348                   tableName = tableName.substring(5, tableName.length());
349                String JavaDoc tableClassName = tableName;
350                Class JavaDoc cls=cl.loadClass(tableClassName);
351                // if this is a cached DO class,
352
// must contain methods getCacheDodsTableName() and refreshCache()
353
// I am searching for these methods, and if there are no
354
// such methods, exception will be thrown, and className
355
// won't be added to the list
356
Method JavaDoc mth;
357                mth=cls.getMethod("refreshCache",new Class JavaDoc[] {});
358                mth=cls.getMethod("getConfigurationAdministration",new Class JavaDoc[] {});
359               retVal.add(new DOTable(dbName,cls));
360               }
361             }
362             }catch(Throwable JavaDoc e) {
363 // e.printStackTrace();
364
Enhydra.getLogChannel().write(Logger.DEBUG,
365                                              "Loading DO classes from class list was unsuccessful!");
366             }
367             return retVal;
368           }
369
370    /**
371    * Returns a List of DODS classes that are cached and are located on given path.
372    */

373    private static List JavaDoc getCachedDOClassesForPath (String JavaDoc classPath,ClassLoader JavaDoc cl, String JavaDoc databaseName) {
374       List JavaDoc cachedDOClasses=new ArrayList JavaDoc();
375       // case of a package contained in a jar file.
376
if (classPath.endsWith(".jar")) {
377          JarFile JavaDoc jfile=null;
378          try {
379             jfile=new JarFile JavaDoc(classPath,false);
380          } catch (Throwable JavaDoc ex) {
381             return cachedDOClasses;
382          }
383          // get all entries
384
Enumeration JavaDoc e = jfile.entries();
385          // loop through entries and find appropriate ones
386
while (e.hasMoreElements()) {
387             try {
388                ZipEntry JavaDoc entry = (ZipEntry JavaDoc)e.nextElement();
389                String JavaDoc entryname = entry.getName();
390                // entry must end with DO.class
391
if (entryname.endsWith("DO.class")) {
392                   // removes the .class extension
393
String JavaDoc className = entryname.substring(0,entryname.length()-6);
394                   // removes starting '/'
395
if (className.startsWith("/")) className = className.substring(1);
396                   // replacing '/' with '.' (prepearing for loading class)
397
className = className.replace('/','.');
398
399                   // loading the class
400
//System.out.println("Loading class.."+className);
401
Class JavaDoc cls=cl.loadClass(className);
402 //System.out.println("Class "+cls+" loaded..");
403
// if this is a cached DO class,
404
// must contain methods getCacheDodsTableName() and refreshCache()
405
// I am searching for these methods, and if there are no
406
// such methods, exception will be thrown, and className
407
// won't be added to the list
408
Method JavaDoc mth;
409 //System.out.println("Getting method rc..");
410
mth=cls.getMethod("refreshCache",new Class JavaDoc[] {});
411 //System.out.println("Method rc get..");
412
mth=cls.getMethod("getConfigurationAdministration",new Class JavaDoc[] {});
413                   cachedDOClasses.add(new DOTable(databaseName,cls));
414                }
415             } catch (Throwable JavaDoc thr) {
416             }
417          }
418       } else { // if it is not .jar file, but directory
419
// getting the package folder
420
File JavaDoc startingFolder=new File JavaDoc(classPath);
421             // if folder exists and realy is a folder but not file
422
if (startingFolder.exists() && startingFolder.isDirectory()) {
423             // getting all DO class files within folder
424
Set JavaDoc allDOClassFiles=new HashSet JavaDoc();
425             traverseDOClasses(startingFolder,allDOClassFiles);
426             Iterator JavaDoc files=allDOClassFiles.iterator();
427             while (files.hasNext()) {
428                try {
429                   File JavaDoc f=(File JavaDoc)files.next();
430                   String JavaDoc fullFileName=f.getAbsolutePath();
431                   // removes the .class extension
432
String JavaDoc className=fullFileName.substring(0,fullFileName.length()-6);
433                   // removes the starting folder full name
434
className=className.substring(classPath.length()+1,className.length());
435                   // replacing path separator with '.'
436
className = className.replace(File.separatorChar,'.');
437                   // loading the class
438
Class JavaDoc cls=cl.loadClass(className);
439                   // if this is a cached DO class,
440
// must contain methods getCacheDodsTableName() and refreshCache()
441
// I am searching for these methods, and if there are no
442
// such methods, exception will be thrown, and className
443
// won't be added to the list
444
Method JavaDoc mth;
445                   mth=cls.getMethod("refreshCache",new Class JavaDoc[] {});
446                   mth=cls.getMethod("getConfigurationAdministration",new Class JavaDoc[] {});
447                   cachedDOClasses.add(cls);
448                } catch (Throwable JavaDoc thr) {}
449             }
450          }
451       }
452       return cachedDOClasses;
453    }
454
455    /**
456    * Returns a list of files which names ends with 'DO.class'.
457    * This is a recursive implementation, and search starts from
458    * given folder represented by f.
459    */

460    private static void traverseDOClasses(File JavaDoc f,Collection JavaDoc c) {
461       if (!f.exists()) {
462          // File f doesn't exist");
463
return;
464       }
465       if (f.isDirectory()) {
466          File JavaDoc[] children = f.listFiles(doClassFileFilter);
467          for (int i=0; i<children.length; i++) {
468             traverseDOClasses(children[i],c);
469          }
470       } else {
471          c.add(f);
472       }
473    }
474
475    /**
476    * The filter for search on DO classes-searchs for
477    * files ending with 'DO.class'.
478    */

479    private static DOClassFileFilter doClassFileFilter=new DOClassFileFilter();
480
481
482 }
483
484 /**
485 * Class that implements filter that filters folders and
486 * files ending with 'DO.class'.
487 */

488 class DOClassFileFilter implements FileFilter JavaDoc {
489    public boolean accept (File JavaDoc pathname) {
490       return (pathname.isDirectory() || pathname.getName().endsWith("DO.class"));
491    }
492 }
493
Popular Tags