You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by le...@apache.org on 2003/08/21 01:13:29 UTC
cvs commit: jakarta-commons-sandbox/attributes/api/src/java/org/apache/commons/attributes AttributeIndex.java AttributeRepositoryClass.java Attributes.java
leosutic 2003/08/20 16:13:29
Added: attributes/compiler/src/java/org/apache/commons/attributes
anttasks.properties
attributes/compiler/src/java/org/apache/commons/attributes/compiler
AttributeCompiler.java AttributeIndexer.java
attributes/api/src/java/org/apache/commons/attributes
AttributeIndex.java AttributeRepositoryClass.java
Attributes.java
Removed: attributes/src/java/org/apache/commons/attributes
Attribute.java AttributeFinder.java Attributes.java
Log:
Moving in, from Avalon Sandbox.
Revision Changes Path
1.1 jakarta-commons-sandbox/attributes/compiler/src/java/org/apache/commons/attributes/anttasks.properties
Index: anttasks.properties
===================================================================
attribute-compiler=org.apache.commons.attributes.compiler.AttributeCompiler
attribute-indexer=org.apache.commons.attributes.compiler.AttributeIndexer
1.1 jakarta-commons-sandbox/attributes/compiler/src/java/org/apache/commons/attributes/compiler/AttributeCompiler.java
Index: AttributeCompiler.java
===================================================================
package org.apache.commons.attributes.compiler;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.types.FileSet;
import xjavadoc.XClass;
import xjavadoc.XConstructor;
import xjavadoc.XJavaDoc;
import xjavadoc.XField;
import xjavadoc.XMethod;
import xjavadoc.XParameter;
import xjavadoc.XProgramElement;
import xjavadoc.XTag;
import xjavadoc.ant.XJavadocTask;
/**
* Ant task to compile attributes. Usage:
*
* <pre><code>
* <taskdef resource="org/apache/commons/attributes/anttasks.properties"/>
*
* <attribute-compiler destDir="temp/">
* <fileset dir="src/" includes="*.java"/>
* </attribute-compiler>
* </code></pre>
*
* The task should be run before compiling the Java sources, and will produce some
* additional Java source files in the destination directory that should be compiled
* along with the input source files. (See the overview for a diagram.)
*/
public class AttributeCompiler extends XJavadocTask {
private final ArrayList fileSets = new ArrayList ();
private File destDir;
private int numGenerated;
public AttributeCompiler () {
}
public void addFileset (FileSet set) {
super.addFileset (set);
fileSets.add (set);
}
public void setDestdir (File destDir) {
this.destDir = destDir;
}
protected void copyImports (File source, PrintWriter dest) throws Exception {
BufferedReader br = new BufferedReader (new FileReader (source));
try {
String line = null;
while ((line = br.readLine ()) != null) {
if (line.startsWith ("import ")) {
dest.println (line);
}
}
} finally {
br.close ();
}
}
protected void addExpressions (Collection tags, PrintWriter pw, String collectionName, String fileName) {
fileName = fileName.replace ('\\', '/');
Iterator iter = tags.iterator ();
while (iter.hasNext ()) {
XTag tag = (XTag) iter.next ();
if (isAttribute (tag)) {
String expression = tag.getName () + " " + tag.getValue ();
if (expression.startsWith ("@")) {
expression = expression.substring (1);
}
if (!expression.endsWith (")")) {
expression = expression + "()";
}
pw.println (" " + collectionName + ".add (\n" +
"new " + expression + " // " + fileName + ":" + tag.getLineNumber () + "\n" +
");");
}
}
}
protected boolean elementHasAttributes (Collection xElements) {
Iterator iter = xElements.iterator ();
while (iter.hasNext ()) {
XProgramElement element = (XProgramElement) iter.next ();
if (tagHasAttributes (element.getDoc ().getTags ())) {
return true;
}
}
return false;
}
protected String getParameterTypes (Collection parameters) {
StringBuffer sb = new StringBuffer ();
for (Iterator params = parameters.iterator (); params.hasNext ();) {
XParameter parameter = (XParameter) params.next ();
sb.append (parameter.getType ().getQualifiedName ());
sb.append (parameter.getDimensionAsString ());
if (params.hasNext ()) {
sb.append (",");
}
}
return sb.toString ();
}
protected void generateClass (XClass xClass) throws Exception {
if (xClass.isAnonymous ()) {
log (xClass.getName () + " is anonymous - ignoring.");
}
if (!hasAttributes (xClass)) {
return;
}
String name = null;
File sourceFile = null;
File destFile = null;
String packageName = null;
String className = null;
packageName = xClass.getContainingPackage().getName ();
if (xClass.isInner ()) {
name = xClass.getQualifiedName ().substring (packageName.length ());
StringTokenizer tok = new StringTokenizer (name, ".");
String outermostClass = packageName + (packageName.length () > 0 ? "." : "") + tok.nextToken ();
sourceFile = getSourceFile (outermostClass);
className = xClass.getName ().replace ('.', '$');
name = packageName + (packageName.length () > 0 ? "." : "") + className;
} else {
name = xClass.getQualifiedName ();
sourceFile = getSourceFile (name);
className = xClass.getName ();
}
destFile = new File (destDir, name.replace ('.', '/') + "$__attributeRepository.java");
if (destFile.exists () && destFile.lastModified () >= sourceFile.lastModified ()) {
return;
}
numGenerated++;
destFile.getParentFile ().mkdirs ();
PrintWriter pw = new PrintWriter (new FileWriter (destFile));
if (packageName != null && !packageName.equals ("")) {
pw.println ("package " + packageName + ";");
}
copyImports (sourceFile, pw);
pw.println ("public class " + className + "$__attributeRepository implements org.apache.commons.attributes.AttributeRepositoryClass {");
{
pw.println (" private static final java.util.Set classAttributes = new java.util.HashSet ();");
pw.println (" private static final java.util.Map fieldAttributes = new java.util.HashMap ();");
pw.println (" private static final java.util.Map methodAttributes = new java.util.HashMap ();");
pw.println (" private static final java.util.Map constructorAttributes = new java.util.HashMap ();");
pw.println ();
pw.println (" static {");
pw.println (" initClassAttributes ();");
pw.println (" initMethodAttributes ();");
pw.println (" initFieldAttributes ();");
pw.println (" initConstructorAttributes ();");
pw.println (" }");
pw.println ();
pw.println (" public java.util.Set getClassAttributes () { return classAttributes; }");
pw.println (" public java.util.Map getFieldAttributes () { return fieldAttributes; }");
pw.println (" public java.util.Map getConstructorAttributes () { return constructorAttributes; }");
pw.println (" public java.util.Map getMethodAttributes () { return methodAttributes; }");
pw.println ();
pw.println (" private static void initClassAttributes () {");
addExpressions (xClass.getDoc ().getTags (), pw, "classAttributes", sourceFile.getPath ());
pw.println (" }");
pw.println ();
// ---- Field Attributes
pw.println (" private static void initFieldAttributes () {");
pw.println (" java.util.Set attrs = null;");
for (Iterator iter = xClass.getFields ().iterator (); iter.hasNext ();) {
XField member = (XField) iter.next ();
if (member.getDoc ().getTags ().size () > 0) {
String key = member.getName ();
pw.println (" attrs = new java.util.HashSet ();");
addExpressions (member.getDoc ().getTags (), pw, "attrs", sourceFile.getPath ());
pw.println (" fieldAttributes.put (\"" + key + "\", attrs);");
pw.println (" attrs = null;");
pw.println ();
}
}
pw.println (" }");
// ---- Method Attributes
pw.println (" private static void initMethodAttributes () {");
pw.println (" java.util.Set attrs = null;");
for (Iterator iter = xClass.getMethods ().iterator (); iter.hasNext ();) {
XMethod member = (XMethod) iter.next ();
if (member.getDoc ().getTags ().size () > 0) {
StringBuffer sb = new StringBuffer ();
sb.append (member.getName ()).append ("(");
sb.append (getParameterTypes (member.getParameters ()));
sb.append (")");
String key = sb.toString ();
pw.println (" attrs = new java.util.HashSet ();");
addExpressions (member.getDoc ().getTags (), pw, "attrs", sourceFile.getPath ());
pw.println (" methodAttributes.put (\"" + key + "\", attrs);");
pw.println (" attrs = null;");
pw.println ();
}
}
pw.println (" }");
// ---- Constructor Attributes
pw.println (" private static void initConstructorAttributes () {");
pw.println (" java.util.Set attrs = null;");
for (Iterator iter = xClass.getConstructors ().iterator (); iter.hasNext ();) {
XConstructor member = (XConstructor) iter.next ();
if (member.getDoc ().getTags ().size () > 0) {
StringBuffer sb = new StringBuffer ();
sb.append ("(");
sb.append (getParameterTypes (member.getParameters ()));
sb.append (")");
String key = sb.toString ();
pw.println (" attrs = new java.util.HashSet ();");
addExpressions (member.getDoc ().getTags (), pw, "attrs", sourceFile.getPath ());
pw.println (" constructorAttributes.put (\"" + key + "\", attrs);");
pw.println (" attrs = null;");
pw.println ();
}
}
pw.println (" }");
}
pw.println ("}");
pw.close ();
}
protected File getSourceFile (String qualifiedName) throws BuildException {
String path = qualifiedName.replace ('.', '/') + ".java";
Iterator iter = fileSets.iterator ();
while (iter.hasNext ()) {
FileSet fs = (FileSet) iter.next ();
File maybe = new File (fs.getDir (project), path);
if (maybe.exists ()) {
return maybe;
}
}
throw new BuildException ("Could not find source file for " + qualifiedName);
}
protected boolean hasAttributes (XClass xClass) {
if (tagHasAttributes (xClass.getDoc ().getTags ()) ||
elementHasAttributes (xClass.getFields ()) ||
elementHasAttributes (xClass.getMethods ()) ||
elementHasAttributes (xClass.getConstructors ()) ) {
return true;
}
return false;
}
protected boolean isClassName (String name) {
StringTokenizer tok = new StringTokenizer (name, ".");
String lastToken = null;
while (tok.hasMoreTokens ()) {
lastToken = tok.nextToken ();
}
return Character.isUpperCase (lastToken.charAt (0));
}
protected boolean isAttribute (XTag tag) {
return tag.getName ().charAt (0) == '@' || isClassName (tag.getName ());
}
protected void start() throws BuildException {
destDir.mkdirs ();
numGenerated = 0;
XJavaDoc doc = getXJavaDoc ();
Iterator iter = doc.getSourceClasses ().iterator ();
try {
while (iter.hasNext ()) {
XClass xClass = (XClass) iter.next ();
generateClass (xClass);
}
} catch (Exception e) {
throw new BuildException (e.toString (), e);
}
log ("Generated attribute information for " + numGenerated + " classes.");
}
protected boolean tagHasAttributes (Collection tags) {
Iterator iter = tags.iterator ();
while (iter.hasNext ()) {
XTag tag = (XTag) iter.next ();
if (isAttribute (tag)) {
return true;
}
}
return false;
}
}
1.1 jakarta-commons-sandbox/attributes/compiler/src/java/org/apache/commons/attributes/compiler/AttributeIndexer.java
Index: AttributeIndexer.java
===================================================================
package org.apache.commons.attributes.compiler;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.jar.JarFile;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import org.apache.commons.attributes.AttributeRepositoryClass;
import org.apache.commons.attributes.Attributes;
import org.apache.commons.attributes.Indexed;
import org.apache.tools.ant.AntClassLoader;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.Path;
/**
* Ant task to compile attribute indexes. Usage:
*
* <pre><code>
* <taskdef resource="org/apache/commons/attributes/anttasks.properties"/>
*
* <attribute-indexer jarFile="myclasses.jar">
* <classpath>
* ...
* </classpath>
* </attribute-indexer>
* </code></pre>
*
* The task will inspect the classes in the given jar and add a <tt>META-INF/attrs.index</tt>
* file to it, which contains the index information. The classpath element is required and
* must contain all dependencies for the attributes used.
*/
public class AttributeIndexer extends Task {
private File jarFile;
private HashMap attributes = new HashMap ();
private Path classPath;
private final static String INDEX_FILENAME = "META-INF/attrs.index";
public AttributeIndexer () {
}
protected void addAttribute (String className, String attributeName) {
HashSet thisAttr = (HashSet) attributes.get (attributeName);
if (thisAttr == null) {
thisAttr = new HashSet ();
attributes.put (attributeName, thisAttr);
}
thisAttr.add (className);
}
public void setJarfile (File jarFile) {
this.jarFile = jarFile;
}
public Path createClasspath () {
this.classPath = new Path(project);
return classPath;
}
private static final String SUFFIX = "$__attributeRepository";
private static final String CLASS_SUFFIX = SUFFIX + ".class";
private static final String SOURCE_SUFFIX = SUFFIX + ".java";
protected void copyEntry (JarFile jar, JarEntry entry, JarOutputStream outputStream) throws Exception {
outputStream.putNextEntry (entry);
if (!entry.isDirectory ()) {
InputStream is = new BufferedInputStream (jar.getInputStream (entry));
try {
byte[] buffer = new byte[16384];
while (true) {
int numRead = is.read (buffer, 0, 16384);
if (numRead == 0 || numRead == -1) {
break;
}
outputStream.write (buffer, 0, numRead);
}
} finally {
is.close ();
}
}
}
public void execute () throws BuildException {
try {
log ("Building attribute index for " + jarFile.getPath ());
AntClassLoader cl = new AntClassLoader (this.getClass ().getClassLoader (), project, classPath, true);
cl.addPathElement (jarFile.getPath ());
JarFile jar = new JarFile (jarFile);
File newJarFile = new File (jarFile.getPath () + ".new");
JarOutputStream output = new JarOutputStream (new FileOutputStream (newJarFile));
try {
Enumeration enum = jar.entries ();
while (enum.hasMoreElements ()) {
JarEntry entry = (JarEntry) enum.nextElement ();
if (!entry.isDirectory ()) {
String className = entry.getName ();
if (className.endsWith (CLASS_SUFFIX)) {
className = className.replace ('/', '.').replace ('\\', '.');
String baseClassName = className.substring (0, className.length () - CLASS_SUFFIX.length ()).replace ('$', '.');
className = className.substring (0, className.length () - 6);
Class repoClass = cl.loadClass (className);
AttributeRepositoryClass repo = (AttributeRepositoryClass) repoClass.newInstance ();
Collection classAttrs = repo.getClassAttributes ();
Collection indexedAttrs = new HashSet ();
Iterator inner = classAttrs.iterator ();
while (inner.hasNext ()) {
indexedAttrs.add (inner.next ().getClass ());
}
indexedAttrs = Attributes.getClassesWithAttributeType (indexedAttrs, Indexed.class);
inner = indexedAttrs.iterator ();
while (inner.hasNext ()) {
addAttribute (baseClassName, ((Class) inner.next ()).getName ());
}
}
}
if (!entry.getName ().equals (INDEX_FILENAME)) {
copyEntry (jar, entry, output);
}
}
output.putNextEntry (new JarEntry (INDEX_FILENAME));
Iterator attrs = attributes.keySet ().iterator ();
while (attrs.hasNext ()) {
String attrName = (String) attrs.next ();
output.write (("Attribute: " + attrName + "\n").getBytes ());
Iterator classes = ((Collection) attributes.get (attrName)).iterator ();
while (classes.hasNext ()) {
output.write (("Class: " + classes.next () + "\n").getBytes ());
}
output.write ("\n".getBytes ());
}
} finally {
output.close ();
jar.close ();
}
cl.cleanup ();
jarFile.delete ();
newJarFile.renameTo (jarFile);
} catch (Exception e) {
e.printStackTrace ();
throw new BuildException (e.toString ());
}
}
}
1.1 jakarta-commons-sandbox/attributes/api/src/java/org/apache/commons/attributes/AttributeIndex.java
Index: AttributeIndex.java
===================================================================
package org.apache.commons.attributes;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
/**
* An index providing a list of classes with given attributes. This
* requires that the attribute is <code>Indexed</code> and that the
* attribute indexer tool has been run on the jar file containing the
* classes.
*/
public class AttributeIndex {
private final HashMap index = new HashMap ();
AttributeIndex (ClassLoader cl) throws Exception {
Enumeration enum = cl.getResources ("META-INF/attrs.index");
while (enum.hasMoreElements ()) {
URL url = (URL) enum.nextElement ();
loadFromURL (url);
}
}
/**
* Add a class to the index.
*/
private void addClass (String attributeClass, String clazz) {
Collection coll = (Collection) index.get (attributeClass);
if (coll == null) {
coll = new HashSet ();
index.put (attributeClass, coll);
}
coll.add (clazz);
}
/**
* Load the attrs.index from a given URL.
*/
private void loadFromURL (URL url) throws Exception {
URLConnection connection = url.openConnection ();
BufferedReader br = new BufferedReader (new InputStreamReader (connection.getInputStream ()));
try {
String currentAttributeClass = null;
String line = null;
while ((line = br.readLine ()) != null) {
if (line.startsWith ("Attribute: ")) {
currentAttributeClass = line.substring ("Attribute: ".length ()).trim ();
} else if (line.startsWith ("Class: ")) {
String className = line.substring ("Class: ".length ()).trim ();
addClass (currentAttributeClass, className);
}
}
} finally {
br.close ();
}
}
/**
* Gets a Collection of the classes that have an attribute of the specified class.
* The Collection contains the class names (String).
*/
public Collection getClassesWithAttribute (String attributeClass) {
if (index.containsKey (attributeClass)) {
return (Collection) index.get (attributeClass);
} else {
return Collections.EMPTY_SET;
}
}
/**
* Gets a Collection of the classes that have an attribute of the specified class.
* The Collection contains the class names (String).
*/
public Collection getClassesWithAttribute (Class attributeClass) {
return getClassesWithAttribute (attributeClass.getName ());
}
}
1.1 jakarta-commons-sandbox/attributes/api/src/java/org/apache/commons/attributes/AttributeRepositoryClass.java
Index: AttributeRepositoryClass.java
===================================================================
package org.apache.commons.attributes;
import java.util.Set;
import java.util.Map;
/**
* Interface implemented by all attribute repository classes.
* This interface is used internally and should not be used
* by clients. The only reason it is public is because the
* classes implementing it may be in any package.
*/
public interface AttributeRepositoryClass {
public Set getClassAttributes ();
public Map getFieldAttributes ();
public Map getMethodAttributes ();
public Map getConstructorAttributes ();
}
1.1 jakarta-commons-sandbox/attributes/api/src/java/org/apache/commons/attributes/Attributes.java
Index: Attributes.java
===================================================================
package org.apache.commons.attributes;
import java.lang.reflect.Field;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
/**
* API for accessing attributes.
*/
public class Attributes {
/**
* A cache of attribute repositories. The map used is a WeakHashMap keyed on the
* Class owning the attribute repository. This works because Class objects use
* the identity function to compare for equality - i.e. if the two classes
* have the same name, and are loaded from the same two ClassLoaders, then
* <code>class1 == class2</code>. Also, <code>(class1.equals(class2)) == (class1 ==
* class2)</code>. This means that a once a Class reference has been garbage-collected,
* it can't be re-created. Thus we can treat the cache map as a normal map - the only
* entries that will ever disappear are those we can't look up anyway because we
* can't ever create the key for them!
*
* <p>Also, this will keep the cache from growing too big in environments where
* classes are loaded and unloaded all the time (i.e. application servers).
*/
private final static Map classRepositories = new WeakHashMap ();
private static List initList = new ArrayList ();
private synchronized static CachedRepository getCachedRepository (Class clazz) throws RepositoryError, CircularDependencyError {
if (classRepositories.containsKey (clazz)) {
CachedRepository cr = (CachedRepository) classRepositories.get (clazz);
if (cr == null) {
// Circular references.
List dependencyList = new ArrayList ();
dependencyList.addAll (initList);
throw new CircularDependencyError (clazz.getName (), dependencyList);
} else {
return cr;
}
} else {
// Indicate that we're loading it.
initList.add (clazz.getName ());
classRepositories.put (clazz, null);
Class attributeRepo;
CachedRepository cached;
try {
attributeRepo = Class.forName (clazz.getName () + "$__attributeRepository", true, clazz.getClassLoader ());
AttributeRepositoryClass repo = (AttributeRepositoryClass) attributeRepo.newInstance ();
cached = new DefaultCachedRepository (clazz, repo);
} catch (ClassNotFoundException cnfe) {
cached = CachedRepository.EMPTY;
} catch (InstantiationException ie) {
throw new RepositoryError (ie);
} catch (IllegalAccessException iae) {
throw new RepositoryError (iae);
}
classRepositories.put (clazz, cached);
initList.remove (initList.size () - 1);
return cached;
}
}
/**
* Gets all attributes for a class.
*/
public static Collection getAttributes (Class clazz) {
return Collections.unmodifiableCollection (getCachedRepository (clazz).getAttributes ());
}
/**
* Gets all attributes for a method.
*/
public static Collection getAttributes (Method method) {
return Collections.unmodifiableCollection (getCachedRepository (method.getDeclaringClass()).getAttributes (method));
}
/**
* Gets all attributes for a field.
*/
public static Collection getAttributes (Field field) {
return Collections.unmodifiableCollection (getCachedRepository (field.getDeclaringClass()).getAttributes (field));
}
/**
* Gets all attributes for a constructor.
*/
public static Collection getAttributes (Constructor cons) {
return Collections.unmodifiableCollection (getCachedRepository (cons.getDeclaringClass()).getAttributes (cons));
}
/**
* Selects from a collection of attributes only those with a given class.
*/
private static Collection getAttributes (Collection attrs, Class attributeClass) {
HashSet result = new HashSet ();
Iterator iter = attrs.iterator ();
while (iter.hasNext ()) {
Object attr = iter.next ();
if (attr.getClass () == attributeClass) {
result.add (attr);
}
}
return Collections.unmodifiableCollection (result);
}
/**
* Get all attributes of a given type from a class. For all objects o in the returned
* collection, <code>o.getClass() == attributeClass</code>.
*/
public static Collection getAttributes (Class clazz, Class attributeClass) {
return getAttributes (getAttributes (clazz), attributeClass);
}
/**
* Get all attributes of a given type from a field. For all objects o in the returned
* collection, <code>o.getClass() == attributeClass</code>.
*/
public static Collection getAttributes (Field field, Class attributeClass) {
return getAttributes (getAttributes (field), attributeClass);
}
/**
* Get all attributes of a given type from a constructor. For all objects o in the returned
* collection, <code>o.getClass() == attributeClass</code>.
*/
public static Collection getAttributes (Constructor ctor, Class attributeClass) {
return getAttributes (getAttributes (ctor), attributeClass);
}
/**
* Get all attributes of a given type from a method. For all objects o in the returned
* collection, <code>o.getClass() == attributeClass</code>.
*/
public static Collection getAttributes (Method method, Class attributeClass) {
return getAttributes (getAttributes (method), attributeClass);
}
/**
* Filters a collection of <code>Class</code> objects. The returned collection
* only contains those classes that have an attribute of the specified type.
*/
public static Collection getClassesWithAttributeType (Collection classes, Class attributeClass) {
ArrayList result = new ArrayList ();
Iterator iter = classes.iterator ();
while (iter.hasNext ()) {
Class clazz = (Class) iter.next ();
if (hasAttributeType (clazz, attributeClass)) {
result.add (clazz);
}
}
return result;
}
/**
* Filters a collection objects. The returned collection
* only contains those objects that have an attribute of the specified type.
*/
public static Collection getObjectsWithAttributeType (Collection objects, Class attributeClass) {
ArrayList result = new ArrayList ();
Iterator iter = objects.iterator ();
while (iter.hasNext ()) {
Class clazz = (Class) iter.next ().getClass ();
if (hasAttributeType (clazz, attributeClass)) {
result.add (clazz);
}
}
return result;
}
/**
* Convenience function to test whether a collection of attributes contain
* an attribute of a given class.
*/
private static boolean hasAttributeType (Collection attrs, Class attributeClass) {
Iterator iter = attrs.iterator ();
while (iter.hasNext ()) {
Object attr = iter.next ();
if (attr.getClass () == attributeClass) {
return true;
}
}
return false;
}
/**
* Tests if a class has an attribute of a given type. That is, is there any attribute
* <code>attr</code> such that <code>attr.getClass() == attributeClass</code>?
*/
public static boolean hasAttributeType (Class clazz, Class attributeClass) {
return hasAttributeType (getAttributes (clazz), attributeClass);
}
/**
* Tests if a field has an attribute of a given type. That is, is there any attribute
* <code>attr</code> such that <code>attr.getClass() == attributeClass</code>?
*/
public static boolean hasAttributeType (Field field, Class attributeClass) {
return hasAttributeType (getAttributes (field), attributeClass);
}
/**
* Tests if a constructor has an attribute of a given type. That is, is there any attribute
* <code>attr</code> such that <code>attr.getClass() == attributeClass</code>?
*/
public static boolean hasAttributeType (Constructor ctor, Class attributeClass) {
return hasAttributeType (getAttributes (ctor), attributeClass);
}
/**
* Tests if a method has an attribute of a given type. That is, is there any attribute
* <code>attr</code> such that <code>attr.getClass() == attributeClass</code>?
*/
public static boolean hasAttributeType (Method method, Class attributeClass) {
return hasAttributeType (getAttributes (method), attributeClass);
}
/**
* Convenience function to test whether a collection of attributes contain
* an attribute.
*/
private static boolean hasAttribute (Collection attrs, Object attribute) {
return attrs.contains (attribute);
}
/**
* Tests if a class has an attribute. That is, is there any attribute
* <code>attr</code> such that <code>attr.equals(attribute)</code>?
*/
public static boolean hasAttribute (Class clazz, Object attribute) {
return hasAttribute (getAttributes (clazz), attribute);
}
/**
* Tests if a field has an attribute. That is, is there any attribute
* <code>attr</code> such that <code>attr.equals(attribute)</code>?
*/
public static boolean hasAttribute (Field field, Object attribute) {
return hasAttribute (getAttributes (field), attribute);
}
/**
* Tests if a constructor has an attribute. That is, is there any attribute
* <code>attr</code> such that <code>attr.equals(attribute)</code>?
*/
public static boolean hasAttribute (Constructor ctor, Object attribute) {
return hasAttribute (getAttributes (ctor), attribute);
}
/**
* Tests if a method has an attribute. That is, is there any attribute
* <code>attr</code> such that <code>attr.equals(attribute)</code>?
*/
public static boolean hasAttribute (Method method, Object attribute) {
return hasAttribute (getAttributes (method), attribute);
}
/**
* Constructs an <code>AttributeIndex</code> for the given <code>ClassLoader</code>.
* An AttributeIndex allows oyu to quickly find all classes that have a given
* attribute.
*/
public static AttributeIndex getAttributeIndex (ClassLoader cl) throws Exception {
return new AttributeIndex (cl);
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commons-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-dev-help@jakarta.apache.org