KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jgap > util > ClassKit


1 /*
2  * This file is part of JGAP.
3  *
4  * JGAP offers a dual license model containing the LGPL as well as the MPL.
5  *
6  * For licencing information please see the file license.txt included with JGAP
7  * or have a look at the top of class org.jgap.Chromosome which representatively
8  * includes the JGAP license policy applicable for any file delivered with JGAP.
9  */

10 package org.jgap.util;
11
12 import java.io.*;
13 import java.net.*;
14 import java.util.*;
15 import java.util.jar.*;
16 import java.util.zip.*;
17
18 public class ClassKit {
19   /** String containing the CVS revision. Read out via reflection!*/
20   private final static String JavaDoc CVS_REVISION = "$Revision: 1.9 $";
21
22   public static void main(String JavaDoc[] args)
23       throws Exception JavaDoc {
24     File f = new File(".");
25 // getPlugins("c:\\java\\jgap\\lib");
26
getPlugins(f.getCanonicalPath() + "\\lib");
27     if (true) {
28       return;
29     }
30     List result = new Vector();
31     result = find("org.jgap.INaturalSelector");
32     for (int i = 0; i < result.size(); i++) {
33       System.err.println(result.get(i));
34     }
35 // URL url = ClassKit.class.getResource("/info/clearthought/layout/");
36
URL url = ClassKit.class.getResource("/org/jgap/impl/");
37     findInJar(result, url, Class.forName("java.io.Serializable"));
38   }
39
40   /**
41    * Display all the classes inheriting or implementing a given
42    * class in the currently loaded packages.
43    * @param a_tosubclassname the name of the class to inherit from
44    * See http//www.javaworld.com/javaworld/javatips/jw-javatip113.html
45    */

46   public static List find(final String JavaDoc a_tosubclassname) {
47     try {
48       List result = new Vector();
49       Class JavaDoc tosubclass = Class.forName(a_tosubclassname);
50       Package JavaDoc[] pcks = Package.getPackages();
51       /**@todo take care of abstract classes --> introduce parameter for that*/
52       for (int i = 0; i < pcks.length; i++) {
53         List subresult = find(pcks[i].getName(), tosubclass);
54         result.addAll(subresult);
55       }
56 // List subresult = find("org.jgap.impl", tosubclass);
57
// result.addAll(subresult);
58
return result;
59     }
60     catch (ClassNotFoundException JavaDoc ex) {
61       System.err.println("Class " + a_tosubclassname + " not found!");
62       return null;
63     }
64   }
65
66   /**
67    * Display all the classes inheriting or implementing a given
68    * class in a given package.
69    * @param a_pckname the fully qualified name of the package
70    * @param a_tosubclassname the name of the class to inherit from
71    * See http//www.javaworld.com/javaworld/javatips/jw-javatip113.html
72    */

73   public static List find(final String JavaDoc a_pckname, final String JavaDoc a_tosubclassname)
74       throws ClassNotFoundException JavaDoc {
75     Class JavaDoc tosubclass = Class.forName(a_tosubclassname);
76     return find(a_pckname, tosubclass);
77   }
78
79   /**
80    * Display all the classes inheriting or implementing a given
81    * class in a given package.
82    * @param a_pckgname the fully qualified name of the package
83    * @param a_tosubclass the Class object to inherit from
84    * See http//www.javaworld.com/javaworld/javatips/jw-javatip113.html
85    */

86   public static List find(final String JavaDoc a_pckgname, final Class JavaDoc a_tosubclass) {
87     List result = new Vector();
88     // Translate the package name into an absolute path
89
String JavaDoc name = a_pckgname;
90     if (!name.startsWith("/")) {
91       name = "/" + name;
92     }
93     name = name.replace('.', '/');
94     // Get a File object for the package
95
URL url = ClassKit.class.getResource(name);
96 // URL url = tosubclass.getResource(name);
97
// URL url = ClassLoader.getSystemClassLoader().getResource(name);
98

99     // Happens only if the jar file is not well constructed, i.e.
100
// if the directories do not appear alone in the jar file like here:
101
//
102
// meta-inf/
103
// meta-inf/manifest.mf
104
// commands/ <== IMPORTANT
105
// commands/Command.class
106
// commands/DoorClose.class
107
// commands/DoorOpen.class
108
// ClassKit.class
109
//
110
if (url == null) {
111       return result;
112     }
113     return find(url, a_pckgname, a_tosubclass);
114   }
115
116   public static List find(final URL a_url, final String JavaDoc a_pckgname,
117                           final Class JavaDoc a_tosubclass) {
118     List result = new Vector();
119     File directory = new File(a_url.getFile());
120     if (directory.exists()) {
121       // Get the list of the files contained in the package
122
String JavaDoc[] files = directory.list();
123       for (int i = 0; i < files.length; i++) {
124         // we are only interested in .class files
125
if (files[i].endsWith(".class")) {
126           // removes the .class extension
127
String JavaDoc classname = files[i].substring(0, files[i].length() - 6);
128           try {
129             // Try to create an instance of the object
130
Class JavaDoc c = Class.forName(a_pckgname + "." + classname);
131             if (a_pckgname.equals("org.jgap.impl")
132                 && classname.equals("BestChromosomesSelector")) {
133               System.err.println("X");
134             }
135             if (implementsInterface(c, a_tosubclass)
136                 || extendsClass(c, a_tosubclass)) {
137               result.add(a_pckgname + "." + classname);
138             }
139           }
140           catch (ClassNotFoundException JavaDoc cnfex) {
141             System.err.println(cnfex);
142           }
143 // catch (InstantiationException iex) {
144
// // We try to instanciate an interface or an object that does not
145
// // have a default constructor
146
// }
147
// catch (IllegalAccessException iaex) {
148
// // The class is not public
149
// }
150
}
151       }
152     }
153     else {
154       findInJar(result, a_url, a_tosubclass);
155     }
156     return result;
157   }
158
159   public static void findInJar(final List a_result, final URL a_url,
160                                Class JavaDoc a_tosubclass) {
161     try {
162       // It does not work with the filesystem: we must
163
// be in the case of a package contained in a jar file.
164
JarURLConnection conn = (JarURLConnection) a_url.openConnection();
165       String JavaDoc starts = conn.getEntryName();
166       JarFile jfile = conn.getJarFile();
167       Enumeration e = jfile.entries();
168       while (e.hasMoreElements()) {
169         ZipEntry entry = (ZipEntry) e.nextElement();
170         String JavaDoc entryname = entry.getName();
171         if (entryname.startsWith(starts)
172             && (entryname.lastIndexOf('/') <= starts.length())
173             && entryname.endsWith(".class")) {
174           String JavaDoc classname = entryname.substring(0, entryname.length() - 6);
175           if (classname.startsWith("/")) {
176             classname = classname.substring(1);
177           }
178           classname = classname.replace('/', '.');
179           try {
180             // Try to create an instance of the object
181
Class JavaDoc c = Class.forName(classname);
182             if (implementsInterface(c, a_tosubclass)
183                 || extendsClass(c, a_tosubclass)) {
184 // Object o = Class.forName(classname).newInstance();
185
// if (tosubclass.isInstance(o)) {
186
a_result.add(classname);
187             }
188           }
189           catch (ClassNotFoundException JavaDoc cnfex) {
190             System.err.println(cnfex);
191           }
192         }
193       }
194     }
195     catch (IOException ioex) {
196       System.err.println(ioex);
197     }
198   }
199
200   public static boolean implementsInterface(final Class JavaDoc a_o,
201                                             final Class JavaDoc a_clazz) {
202     Class JavaDoc[] interfaces = a_o.getInterfaces();
203     for (int i = 0; i < interfaces.length; i++) {
204       Class JavaDoc c = interfaces[i];
205       if (c.equals(a_clazz)) {
206         return true;
207       }
208     }
209     return false;
210   }
211
212   public static boolean extendsClass(final Class JavaDoc a_o, final Class JavaDoc a_clazz) {
213     if (a_clazz.getName().equals(a_o.getName())) {
214       return false;
215     }
216     if (a_clazz.isAssignableFrom(a_o)) {
217       return true;
218     }
219     else {
220       return false;
221     }
222   }
223
224   /**@todo add input param: type (or list of types) to look for*/
225   public static void getPlugins(final String JavaDoc a_directory) {
226     File modulePath = new File(a_directory);
227 // if(modulePath == null || !modulePath.exists())modulePath.mkdirs();
228
File[] jarFiles = modulePath.listFiles(new ExtensionsFilter("jar", false));
229     URL[] urls = new URL[jarFiles.length + 1];
230     int i = 0;
231     for (; i < jarFiles.length; i++) {
232       try {
233         urls[i] = jarFiles[i].toURL();
234       }
235       catch (Exception JavaDoc ex) {
236       }
237     }
238     try {
239       urls[i] = modulePath.toURL();
240     }
241     catch (Exception JavaDoc ex) {
242       ; //do nothing?
243
}
244     ClassLoader JavaDoc ucl = new URLClassLoader(urls);
245     // -------------------------------
246
Vector classes = new Vector();
247     long startTime = System.currentTimeMillis();
248     addClasses(classes, modulePath, "");
249     System.out.println("Found Classes in: "
250                        + (System.currentTimeMillis() - startTime) + " mills");
251     // -------------------------------
252
// Vector implementingClasses = new Vector();
253
Enumeration e = classes.elements();
254     while (e.hasMoreElements()) {
255       try {
256         String JavaDoc name = e.nextElement().toString();
257         /**@todo check if class assignable from given type*/
258         System.err.println("found: " + name);
259       }
260       catch (Throwable JavaDoc ex) {
261         ; // do nothing?
262
}
263     }
264   }
265
266   public static void addClasses(final Vector a_v, final File a_path,
267                                 final String JavaDoc a_name) {
268     addClassesFile(a_v, a_path, a_name);
269     addClassesJar(a_v, a_path);
270   }
271
272   public static void addClassesJar(final Vector a_v, final File a_path) {
273     File[] files = a_path.listFiles(new ExtensionsFilter("jar", false));
274     for (int i = 0; i < files.length; i++) {
275       try {
276         java.util.jar.JarFile JavaDoc jar = new java.util.jar.JarFile JavaDoc(files[i]);
277         String JavaDoc wa;
278         java.util.Enumeration JavaDoc e = jar.entries();
279         while (e.hasMoreElements()) {
280           wa = e.nextElement().toString();
281           if (wa.endsWith(".class") && (wa.indexOf("$") == -1)) {
282             a_v.add(wa.substring(0, wa.length() - 6).replace('/', '.'));
283           }
284         }
285       }
286       catch (Exception JavaDoc ex) {
287         ; // do nothing?
288
}
289     }
290   }
291
292   //this method is recursive to go down sub-dirs
293
public static void addClassesFile(Vector a_v, final File a_path,
294                                     final String JavaDoc a_name) {
295     File[] files = a_path.listFiles(new ExtensionsFilter("class", true));
296     for (int i = 0; i < files.length; i++) {
297       if (files[i].isDirectory()) {
298         addClassesFile(a_v, files[i], a_name + files[i].getName() + ".");
299       }
300       else if (files[i].getName().indexOf("$") == -1) {
301         a_v.add(a_name
302                 + files[i].getName().
303                 substring(0, files[i].getName().length() - 6));
304       }
305     }
306   }
307
308   static class ExtensionsFilter
309       implements FilenameFilter {
310     private String JavaDoc m_ext;
311
312     public ExtensionsFilter(final String JavaDoc a_extension, final boolean a_dummy) {
313       m_ext = a_extension;
314     }
315
316     public boolean accept(final File a_dir, final String JavaDoc a_name) {
317       return a_name != null && a_name.endsWith("." + m_ext);
318     }
319   }
320 }
321
Popular Tags