summaryrefslogtreecommitdiff
path: root/src/de/lmu/ifi/dbs/elki/utilities/InspectionUtil.java
blob: e3cfe895371a6e3ca57338537988d457eb8be287 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package de.lmu.ifi.dbs.elki.utilities;
/*
This file is part of ELKI:
Environment for Developing KDD-Applications Supported by Index-Structures

Copyright (C) 2011
Ludwig-Maximilians-Universität München
Lehr- und Forschungseinheit für Datenbanksysteme
ELKI Development Team

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
import java.util.Vector;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import de.lmu.ifi.dbs.elki.logging.LoggingUtil;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.ClassParameter;

/**
 * A collection of inspection-related utility functions.
 * 
 * @author Erich Schubert
 * 
 * @apiviz.uses InspectionUtilFrequentlyScanned
 */
public class InspectionUtil {
  /**
   * Default package ignores.
   */
  private static final String[] DEFAULT_IGNORES = {
  // Sun Java
  "java.", "com.sun.",
  // Batik classes
  "org.apache.",
  // W3C / SVG / XML classes
  "org.w3c.", "org.xml.", "javax.xml.",
  // JUnit
  "org.junit.", "junit.", "org.hamcrest.",
  // Eclipse
  "org.eclipse.",
  // ApiViz
  "org.jboss.apiviz.",
  // JabRef
  "spin.", "osxadapter.", "antlr.", "ca.odell.", "com.jgoodies.", "com.michaelbaranov.", "com.mysql.", "gnu.dtools.", "net.sf.ext.", "net.sf.jabref.", "org.antlr.", "org.gjt.", "org.java.plugin.", "org.jempbox.", "org.pdfbox.", "wsi.ra.",
  // Wrappers don't have important own parameters, they just set some defaults
  "experimentalcode.shared.wrapper." };

  /**
   * If we have a non-static classpath, we do more extensive scanning for user
   * extensions.
   */
  public static final boolean NONSTATIC_CLASSPATH;

  // Check for non-jar entries in classpath.
  static {
    String[] classpath = System.getProperty("java.class.path").split(System.getProperty("path.separator"));
    boolean hasnonstatic = false;
    for(String path : classpath) {
      if(!path.endsWith(".jar")) {
        hasnonstatic = true;
      }
    }
    NONSTATIC_CLASSPATH = hasnonstatic;
  }

  private static WeakReference<List<Class<?>>> CLASS_CACHE = new WeakReference<List<Class<?>>>(null);

  /**
   * Cached version of "findAllImplementations". For Parameterizable classes
   * only!
   * 
   * @param c Class to scan for
   * @return Found implementations
   */
  public static List<Class<?>> cachedFindAllImplementations(Class<?> c) {
    if (c == null) {
      return Collections.emptyList();
    }
    if(InspectionUtilFrequentlyScanned.class.isAssignableFrom(c)) {
      List<Class<?>> cache = CLASS_CACHE.get();
      if(cache == null) {
        cache = findAllImplementations(InspectionUtilFrequentlyScanned.class, false);
        CLASS_CACHE = new WeakReference<List<Class<?>>>(cache);
      }
      ArrayList<Class<?>> list = new ArrayList<Class<?>>();
      for(Class<?> cls : cache) {
        if(c.isAssignableFrom(cls)) {
          list.add(cls);
        }
      }
      return list;
    }
    else {
      // Need to scan - not cached.
      // LoggingUtil.logExpensive(Level.FINE,
      // "Slow scan for implementations: "+c.getName());
      return findAllImplementations(c, false);
    }
  }

  /**
   * Find all implementations of a given class in the classpath.
   * 
   * Note: returned classes may be abstract.
   * 
   * @param c Class restriction
   * @param everything include interfaces, abstract and private classes
   * @return List of found classes.
   */
  public static List<Class<?>> findAllImplementations(Class<?> c, boolean everything) {
    String[] classpath = System.getProperty("java.class.path").split(System.getProperty("path.separator"));
    return findAllImplementations(classpath, c, DEFAULT_IGNORES, everything);
  }

  /**
   * Find all implementations of a given class.
   * 
   * @param classpath Classpath to use (JARs and folders supported)
   * @param c Class restriction
   * @param ignorepackages List of packages to ignore
   * @param everything include interfaces, abstract and private classes
   * @return List of found classes.
   */
  public static List<Class<?>> findAllImplementations(String[] classpath, Class<?> c, String[] ignorepackages, boolean everything) {
    // Collect iterators
    Vector<Iterable<String>> iters = new Vector<Iterable<String>>(classpath.length);
    for(String path : classpath) {
      File p = new File(path);
      if(path.endsWith(".jar")) {
        iters.add(new JarClassIterator(path));
      }
      else if(p.isDirectory()) {
        iters.add(new DirClassIterator(p));
      }
    }

    ArrayList<Class<?>> res = new ArrayList<Class<?>>();
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    for(Iterable<String> iter : iters) {
      for(String classname : iter) {
        boolean ignore = false;
        for(String pkg : ignorepackages) {
          if(classname.startsWith(pkg)) {
            ignore = true;
            break;
          }
        }
        if(ignore) {
          continue;
        }
        try {
          Class<?> cls = cl.loadClass(classname);
          // skip abstract / private classes.
          if(!everything && (Modifier.isInterface(cls.getModifiers()) || Modifier.isAbstract(cls.getModifiers()) || Modifier.isPrivate(cls.getModifiers()))) {
            continue;
          }
          // skip classes where we can't get a full name.
          if(cls.getCanonicalName() == null) {
            continue;
          }
          if(c.isAssignableFrom(cls)) {
            res.add(cls);
          }
        }
        catch(ClassNotFoundException e) {
          continue;
        }
        catch(NoClassDefFoundError e) {
          continue;
        }
        catch(Exception e) {
          continue;
        }
      }
    }
    Collections.sort(res, new ClassSorter());
    return res;
  }

  /**
   * Class to iterate over a Jar file.
   * 
   * @author Erich Schubert
   * 
   * @apiviz.exclude
   */
  static class JarClassIterator implements Iterator<String>, Iterable<String> {
    private Enumeration<JarEntry> jarentries;

    private String ne;

    /**
     * Constructor from Jar file.
     * 
     * @param path Jar file entries to iterate over.
     */
    public JarClassIterator(String path) {
      try {
        JarFile jf = new JarFile(path);
        this.jarentries = jf.entries();
        this.ne = findNext();
      }
      catch(IOException e) {
        LoggingUtil.exception("Error opening jar file: " + path, e);
        this.jarentries = null;
        this.ne = null;
      }
    }

    @Override
    public boolean hasNext() {
      // Do we have a next entry?
      return (ne != null);
    }

    /**
     * Find the next entry, since we need to skip some jar file entries.
     * 
     * @return next entry or null
     */
    private String findNext() {
      while(jarentries.hasMoreElements()) {
        JarEntry je = jarentries.nextElement();
        String name = je.getName();
        if(name.endsWith(".class")) {
          String classname = name.substring(0, name.length() - ".class".length());
          if(classname.endsWith(ClassParameter.FACTORY_POSTFIX) || !classname.contains("$")) {
            return classname.replace("/", ".");
          }
        }
      }
      return null;
    }

    @Override
    public String next() {
      // Return the previously stored entry.
      String ret = ne;
      ne = findNext();
      return ret;
    }

    @Override
    public void remove() {
      throw new UnsupportedOperationException();
    }

    @Override
    public Iterator<String> iterator() {
      return this;
    }
  }

  /**
   * Class to iterate over a directory tree.
   * 
   * @author Erich Schubert
   * 
   * @apiviz.exclude
   */
  static class DirClassIterator implements Iterator<String>, Iterable<String> {
    private String prefix;

    private Stack<File> set = new Stack<File>();

    private String cur;

    /**
     * Constructor from Directory
     * 
     * @param path Directory to iterate over
     */
    public DirClassIterator(File path) {
      this.prefix = path.getAbsolutePath();
      this.set.push(path);
      this.cur = findNext();
    }

    @Override
    public boolean hasNext() {
      // Do we have a next entry?
      return (cur != null);
    }

    /**
     * Find the next entry, since we need to skip some jar file entries.
     * 
     * @return next entry or null
     */
    private String findNext() {
      while(set.size() > 0) {
        File f = set.pop();
        // recurse into directories
        if(f.isDirectory()) {
          // TODO: do not recurse into ignored packages!.
          for(File newf : f.listFiles()) {
            set.push(newf);
          }
          continue;
        }
        String name = f.getAbsolutePath();
        if(name.startsWith(prefix)) {
          int l = prefix.length();
          if(name.charAt(l) == File.separatorChar) {
            l += 1;
          }
          name = name.substring(l);
        }
        else {
          LoggingUtil.warning("I was expecting all directories to start with '" + prefix + "' but '" + name + "' did not.");
        }
        if(name.endsWith(".class")) {
          String classname = name.substring(0, name.length() - ".class".length());
          if(classname.endsWith(ClassParameter.FACTORY_POSTFIX) || !classname.contains("$")) {
            return classname.replace(File.separator, ".");
          }
        }
      }
      return null;
    }

    @Override
    public String next() {
      // Return the previously stored entry.
      String ret = this.cur;
      this.cur = findNext();
      return ret;
    }

    @Override
    public void remove() {
      throw new UnsupportedOperationException();
    }

    @Override
    public Iterator<String> iterator() {
      return this;
    }
  }

  /**
   * Sort classes by their class name. Package first, then class.
   * 
   * @author Erich Schubert
   * 
   * @apiviz.exclude
   */
  public static class ClassSorter implements Comparator<Class<?>> {
    @Override
    public int compare(Class<?> o1, Class<?> o2) {
      int pkgcmp = o1.getPackage().getName().compareTo(o2.getPackage().getName());
      if(pkgcmp != 0) {
        return pkgcmp;
      }
      return o1.getCanonicalName().compareTo(o2.getCanonicalName());
    }
  }
}