001    package de.mospace.lang;
002    
003    /**
004    * RTSI.java
005    *
006    * Created: Wed Jan 24 11:15:02 2001
007    *
008    */
009    
010    import java.io.BufferedInputStream;
011    import java.io.BufferedOutputStream;
012    import java.io.File;
013    import java.io.FileInputStream;
014    import java.io.FileOutputStream;
015    import java.io.IOException;
016    import java.io.InputStream;
017    import java.io.OutputStream;
018    import java.lang.reflect.Modifier;
019    import java.net.JarURLConnection;
020    import java.net.MalformedURLException;
021    import java.net.URI;
022    import java.net.URL;
023    import java.net.URLClassLoader;
024    import java.util.Enumeration;
025    import java.util.List;
026    import java.util.Properties;
027    import java.util.Vector;
028    import java.util.jar.JarFile;
029    import java.util.logging.Handler;
030    import java.util.logging.Level;
031    import java.util.logging.Logger;
032    import java.util.prefs.Preferences;
033    import java.util.zip.ZipEntry;
034    
035    /**
036    * This utility class is looking for all the public classes
037    * implementing or inheriting from a given interface or class that
038    * can be instantiated with a zero-argument constructor.
039    * (RunTime Subclass Identification)
040    *
041    * @author <a href="mailto:daniel@satlive.org">Daniel Le Berre</a>
042    * @version 1.0
043    *
044    * [MR] find(String,Class) returns array with class names instead of printing to stdout.
045    * [MR] Using URIs to look up resources (previous version did not work
046    * when there was a blank in the file name)
047    * [MR] specify class loader to use
048    * [MR] optionally use properties cache
049    */
050    public class RTSI {
051        private static Logger logger = Logger.getLogger("de.mospace.lang");
052        static{
053            logger.setUseParentHandlers(false);
054        }
055        private final ClassLoader classloader;
056    
057        /** deprecated use a ClassLoaderProvider instead */
058        public static ClassLoader createLibClassLoader(File libdir){
059            return createLibClassLoader(new File[]{libdir});
060        }
061    
062        /** deprecated use a ClassLoaderProvider instead */
063        public static ClassLoader createLibClassLoader(File[] libdir){
064            ClassLoader libClassLoader = null;
065            List jars = new Vector(libdir.length * 10);
066            for(int j = 0; j<libdir.length; j++){
067                File lib = libdir[j];
068                if(lib.isDirectory()){
069                    File[] libs = lib.listFiles();
070    
071                    for(int i=0; i<libs.length; i++){
072                        if(libs[i].isFile() && libs[i].getName().endsWith(".jar")){
073                            try{
074                                jars.add(libs[i].toURI().toURL());
075                            } catch (MalformedURLException ignore){
076                                logger.warning(ignore.toString());
077                            }
078                        }
079                    }
080                } else if(lib.isFile() && lib.getName().endsWith(".jar")){
081                    try{
082                        jars.add(lib.toURI().toURL());
083                    } catch (MalformedURLException ignore){
084                        logger.warning(ignore.toString());
085                    }
086                }
087            }
088            libClassLoader = jars.isEmpty()
089                ? ClassLoader.getSystemClassLoader()
090                : new URLClassLoader((URL[]) jars.toArray(new URL[jars.size()]),
091                        ClassLoader.getSystemClassLoader());
092    
093            return libClassLoader;
094        }
095    
096        public RTSI(){
097            this(ClassLoader.getSystemClassLoader());
098        }
099    
100        public RTSI(ClassLoader cl){
101            classloader = cl;
102        }
103    
104        public ClassLoader getClassLoader(){
105            return classloader;
106        }
107    
108        public static void addLogHandler(Handler lh){
109            logger.setLevel(lh.getLevel());
110            logger.addHandler(lh);
111        }
112    
113        /**
114        * Display all the classes inheriting or implementing a given
115        * class in the currently loaded packages.
116        * Works only with the default class loader!!!
117        * @param tosubclassname the name of the class to inherit from
118        */
119        public void find(String tosubclassname) {
120            try {
121                Class tosubclass = Class.forName(tosubclassname, true, classloader);
122                Package [] pcks = Package.getPackages();
123                for (int i=0;i<pcks.length;i++) {
124                    find(pcks[i].getName(),tosubclass);
125                }
126            } catch (ClassNotFoundException ex) {
127                logger.logp(Level.SEVERE,
128                    RTSI.class.getName(),
129                    "find(String)",
130                    "Class "+tosubclassname+" not found!", ex);
131                //System.err.println("Class "+tosubclassname+" not found!");
132            }
133        }
134    
135        /**
136        * Display all the classes inheriting or implementing a given
137        * class in a given package.
138        * @param pckname the fully qualified name of the package
139        * @param tosubclassname the name of the class to inherit from
140        */
141        public void find(String pckname, String tosubclassname) {
142            try {
143                Class tosubclass = Class.forName(tosubclassname, true, classloader);
144                find(pckname,tosubclass);
145            } catch (ClassNotFoundException ex) {
146                logger.logp(Level.SEVERE,
147                        RTSI.class.getName(),
148                        "find(String, String)",
149                        "Class "+tosubclassname+" not found!", ex);
150                //System.err.println("Class "+tosubclassname+" not found!");
151            }
152        }
153    
154        /** pref cache **/
155        public String[] find(String pckname, Class tosubclass,
156                Preferences pref, String buildprop, String buildval){
157            String[] result = null;
158            Preferences p = pref;
159            if (p != null){
160                int reslength = pref.getInt(pckname, -1);
161                if(reslength < 0){
162                    p = null;
163                } else {
164                    result = new String[reslength];
165    
166                    /* check whether this is a new build */
167                    if(p.get(buildprop, null) != null && buildval.equals(p.get(buildprop, null))){
168                        /* if not try loading saved values */
169                        for(int i=0; i<reslength; i++){
170                            result[i] = p.get(pckname + "." + i, null);
171                            if(result[i] == null){
172                                /* the prefs are not what we expect them to be */
173                                p = null;
174                                break;
175                            }
176                        }
177                    } else {
178                        p = null;
179                    }
180                }
181            }
182            if(p == null){
183                result = find(pckname, tosubclass);
184                pref.putInt(pckname, result.length);
185                for(int i=0; i<result.length; i++){
186                    pref.put(pckname+"."+i, String.valueOf(result[i]));
187                }
188                pref.put(buildprop, buildval);
189            }
190            return result;
191        }
192    
193        /** property cache **/
194        public String[] find(String pckname, Class tosubclass,
195                File configdir, String buildprop, String buildval){
196            File prop = new File(configdir, tosubclass.getName()+".properties");
197            Properties properties = new Properties();
198            prop.getAbsoluteFile().getParentFile().mkdirs();
199            boolean fromFile = prop.isFile();
200            String[] result = null;
201            if (fromFile){
202                InputStream fips = null;
203                try{
204                    fips = new BufferedInputStream(new FileInputStream(prop));
205                    properties.load(fips);
206                    int reslength = Integer.parseInt(properties.getProperty(pckname));
207                    result = new String[reslength];
208    
209                    /* check whether this is a new build */
210                    if(properties.get(buildprop) != null &&
211                        buildval.equals(properties.get(buildprop)))
212                    {
213                        /* if not try loading saved values */
214                        for(int i=0; i<reslength; i++){
215                            result[i] = properties.getProperty(pckname + "." + i);
216                            if(result[i] == null){
217                                /* the property file is not what we expect it to be */
218                                fromFile = false;
219                                break;
220                            }
221                        }
222                    } else {
223                        fromFile = false;
224                    }
225                } catch (IOException ex){
226                    fromFile = false;
227                } catch (IllegalArgumentException ex){
228                    /* property file is malformed */
229                    fromFile = false;
230                } finally {
231                    if(fips != null){
232                        try{
233                            fips.close();
234                        } catch (IOException ioex){
235                            ioex.printStackTrace();
236                        }
237                    }
238                }
239            }
240            if(!fromFile){
241                result = find(pckname, tosubclass);
242                OutputStream fops = null;
243                try{
244                    fops = new BufferedOutputStream(new FileOutputStream(prop));
245                    properties.setProperty(pckname, String.valueOf(result.length));
246                    for(int i=0; i<result.length; i++){
247                        properties.setProperty(pckname+"."+i,
248                                String.valueOf(result[i]));
249                    }
250                    properties.setProperty(buildprop, buildval);
251                    properties.store(fops,
252                    "This file caches which implementations of " +
253                    tosubclass.getName() +
254                    " are available. Delete it when you want to rebuild the cache.");
255                } catch (IOException ioex){
256                    ioex.printStackTrace();
257                } finally {
258                    if(fops != null){
259                        try{
260                            fops.close();
261                        } catch (IOException ioex){
262                            ioex.printStackTrace();
263                        }
264                    }
265                }
266            }
267            return result;
268        }
269    
270        /**
271        * Display all the classes inheriting or implementing a given
272        * class in a given package.
273        * @param pckgname the fully qualified name of the package
274        * @param tosubclass the Class object to inherit from
275        */
276        public String[] find(String pckgname, Class tosubclass) {
277            logger.logp(Level.INFO,
278                        RTSI.class.getName(),
279                        "find(String, Class)",
280                        "Searching for " + tosubclass.getName() + " in package " + pckgname);
281            // Code from JWhich
282            // ======
283            // Translate the package name into an absolute path
284            String name = new String(pckgname);
285            //if (!name.startsWith("/")) {
286                //name = "/" + name;
287            //}
288            name = name.replace('.','/');
289    
290            // Get a File object for the package
291            URL url = classloader.getResource(name);
292            // URL url = tosubclass.getResource(name);
293            // URL url = ClassLoader.getSystemClassLoader().getResource(name);
294            //System.out.println(name+"->"+url);
295    
296            // Happens only if the jar file is not well constructed, i.e.
297            // if the directories do not appear alone in the jar file like here:
298            //
299            //          meta-inf/
300            //          meta-inf/manifest.mf
301            //          commands/                  <== IMPORTANT
302            //          commands/Command.class
303            //          commands/DoorClose.class
304            //          commands/DoorLock.class
305            //          commands/DoorOpen.class
306            //          commands/LightOff.class
307            //          commands/LightOn.class
308            //          RTSI.class
309            //
310            if (url==null){
311                return new String[0];
312            }
313    
314    
315            File directory = null;
316            try {
317                URI u = new URI(url.toString()); //Java 1.4 version of url.ToURI()
318                //test if u is hierarchical
319                if (!u.isOpaque()){
320                    directory  = new File(u);
321                }
322            } catch (java.net.URISyntaxException ex){
323                logger.logp(Level.SEVERE,
324                        RTSI.class.getName(),
325                        "find(String, Class)",
326                        "Error in RTSI: Returning Empty Array!", ex);
327                //System.err.println("Error in RTSI: Returning Empty Array!");
328                //ex.printStackTrace(System.err);
329                return new String[]{};
330            }
331            // New code
332            // ======
333            Vector validSubclasses = new Vector();
334            if (directory != null && directory.exists()) {
335                logger.logp(Level.INFO,
336                        RTSI.class.getName(),
337                        "find(String, Class)",
338                        "Searching for "+ tosubclass.getName() +
339                        " in directory " + directory.getAbsolutePath());
340                // Get the list of the files contained in the package
341                String [] files = directory.list();
342                for (int i=0;i<files.length;i++) {
343    
344                    // we are only interested in .class files
345                    if (files[i].endsWith(".class")) {
346                        // removes the .class extension
347                        String classname = files[i].substring(0,files[i].length()-6);
348                        classname = pckgname+"."+classname;
349                        if(testClass(classname, tosubclass)){
350                            validSubclasses.add(classname);
351                        }
352                    }
353                }
354            } else {
355                logger.logp(Level.INFO,
356                        RTSI.class.getName(),
357                        "find(String, Class)",
358                        "Searching for " + tosubclass.getName() + " in jarfile. ");
359                try {
360                    // It does not work with the filesystem: we must
361                    // be in the case of a package contained in a jar file.
362                    JarURLConnection conn = (JarURLConnection)url.openConnection();
363                    String starts = conn.getEntryName();
364                    JarFile jfile = conn.getJarFile();
365                    logger.logp(Level.INFO,
366                            RTSI.class.getName(),
367                            "find(String, Class)",
368                            "Jarfile name: " + jfile.getName());
369                    Enumeration e = jfile.entries();
370                    while (e.hasMoreElements()) {
371                        ZipEntry entry = (ZipEntry)e.nextElement();
372                        String entryname = entry.getName();
373                        if (entryname.startsWith(starts)
374                            &&(entryname.lastIndexOf('/')<=starts.length())
375                        &&entryname.endsWith(".class")) {
376                            String classname = entryname.substring(0,entryname.length()-6);
377                            if (classname.startsWith("/")){
378                                classname = classname.substring(1);
379                            }
380                            classname = classname.replace('/','.');
381                            if(testClass(classname, tosubclass)){
382                                validSubclasses.add(classname);
383                            }
384                        }
385                    }
386                } catch (IOException ioex) {
387                    logger.warning(ioex.toString());
388                }
389            }
390            return (String[]) validSubclasses.toArray(new String[validSubclasses.size()]);
391        }
392    
393        public void main(String []args) {
394            if (args.length==2) {
395                find(args[0],args[1]);
396            } else {
397                if (args.length==1) {
398                    find(args[0]);
399                } else {
400                    System.out.println("Usage: java RTSI [<package>] <subclass>");
401                }
402            }
403        }
404    
405        public boolean testClass(String classname, Class tosubclass){
406            boolean result = false;
407            logger.logp(Level.FINE,
408            RTSI.class.getName(),
409            "testClass",
410            "Candidate class: " + classname);
411            try {
412                // Test if this class is public.
413                Class cl = Class.forName(classname, true, classloader);
414                if(Modifier.isPublic(cl.getModifiers())){
415                    // Try to create an instance of the object
416                    Object o = Class.forName(classname, true, classloader).newInstance();
417                    if (tosubclass.isInstance(o)) {
418                        logger.logp(Level.FINE,
419                        RTSI.class.getName(),
420                        "testClass",
421                        "Candidate class " + classname +
422                        " passed tests.");
423                        result = true;
424                    } else {
425                        logger.logp(Level.FINE,
426                        RTSI.class.getName(),
427                        "testClass",
428                        "Candidate class " + classname +
429                        " is not an instance of " + tosubclass.getName() +".");
430                    }
431                } else {
432    
433                    logger.logp(Level.FINE,
434                    RTSI.class.getName(),
435                    "testClass",
436                    "Candidate class: " + classname +
437                    "; Class is not public!");
438                }
439            } catch (NoClassDefFoundError ncdfe){
440                logger.logp(Level.FINE,
441                RTSI.class.getName(),
442                "testClass",
443                "Candidate class: " + classname +
444                "; Class Definition not found!");
445                //System.err.println(ncdfe);
446            } catch (ClassNotFoundException cnfex) {
447                logger.logp(Level.FINE,
448                RTSI.class.getName(),
449                "testClass",
450                "Candidate class: " + classname +
451                "; Class not found!");
452                //System.err.println(cnfex);
453            } catch (InstantiationException iex) {
454                // We try to instanciate an interface
455                // or an object that does not have a
456                // default constructor
457                logger.logp(Level.FINE,
458                RTSI.class.getName(),
459                "testClass",
460                "Candidate class: " + classname +
461                "; Class is not instantiable or does not have" +
462                " a default constructor!");
463            } catch (IllegalAccessException iaex) {
464                // The class is not public
465                logger.logp(Level.FINE,
466                RTSI.class.getName(),
467                "testClass",
468                "Candidate class: " + classname +
469                "; Class is not accessible!");
470            } catch(Throwable ex){
471                // An unexpected error
472                logger.logp(Level.FINE,
473                RTSI.class.getName(),
474                "testClass",
475                "Candidate class: " + classname +
476                "; Unexpected exception " + ex.toString());
477            }
478            return result;
479        }
480    }// RTSI