-#Fri Nov 25 19:12:57 GMT 2005
+#Tue Sep 08 17:08:00 PDT 2009
eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.3
+org.eclipse.jdt.core.compiler.compliance=1.5
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=ignore
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
org.eclipse.jdt.core.compiler.problem.deprecation=warning
org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=ignore
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore
org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=ignore
org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.3
+org.eclipse.jdt.core.compiler.source=1.5
/**
* Exception constants.
*
- * @version $Id: ExceptionConstants.java,v 1.3 2008/05/28 23:53:04 aclement Exp $
+ * @version $Id: ExceptionConstants.java,v 1.4 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="http://www.inf.fu-berlin.de/~ehaase">E. Haase</A>
*/
public interface ExceptionConstants {
/** The mother of all exceptions
*/
- public static final Class THROWABLE = Throwable.class;
+ public static final Class<Throwable> THROWABLE = Throwable.class;
/** Super class of any run-time exception
*/
- public static final Class RUNTIME_EXCEPTION = RuntimeException.class;
+ public static final Class<RuntimeException> RUNTIME_EXCEPTION = RuntimeException.class;
/** Super class of any linking exception (aka Linkage Error)
*/
- public static final Class LINKING_EXCEPTION = LinkageError.class;
+ public static final Class<LinkageError> LINKING_EXCEPTION = LinkageError.class;
/** Linking Exceptions
*/
- public static final Class CLASS_CIRCULARITY_ERROR = ClassCircularityError.class;
- public static final Class CLASS_FORMAT_ERROR = ClassFormatError.class;
- public static final Class EXCEPTION_IN_INITIALIZER_ERROR = ExceptionInInitializerError.class;
- public static final Class INCOMPATIBLE_CLASS_CHANGE_ERROR = IncompatibleClassChangeError.class;
- public static final Class ABSTRACT_METHOD_ERROR = AbstractMethodError.class;
+ public static final Class<ClassCircularityError> CLASS_CIRCULARITY_ERROR = ClassCircularityError.class;
+ public static final Class<ClassFormatError> CLASS_FORMAT_ERROR = ClassFormatError.class;
+ public static final Class<ExceptionInInitializerError> EXCEPTION_IN_INITIALIZER_ERROR = ExceptionInInitializerError.class;
+ public static final Class<IncompatibleClassChangeError> INCOMPATIBLE_CLASS_CHANGE_ERROR = IncompatibleClassChangeError.class;
+ public static final Class<AbstractMethodError> ABSTRACT_METHOD_ERROR = AbstractMethodError.class;
public static final Class ILLEGAL_ACCESS_ERROR = IllegalAccessError.class;
- public static final Class INSTANTIATION_ERROR = InstantiationError.class;
- public static final Class NO_SUCH_FIELD_ERROR = NoSuchFieldError.class;
- public static final Class NO_SUCH_METHOD_ERROR = NoSuchMethodError.class;
- public static final Class NO_CLASS_DEF_FOUND_ERROR = NoClassDefFoundError.class;
- public static final Class UNSATISFIED_LINK_ERROR = UnsatisfiedLinkError.class;
- public static final Class VERIFY_ERROR = VerifyError.class;
+ public static final Class<InstantiationError> INSTANTIATION_ERROR = InstantiationError.class;
+ public static final Class<NoSuchFieldError> NO_SUCH_FIELD_ERROR = NoSuchFieldError.class;
+ public static final Class<NoSuchMethodError> NO_SUCH_METHOD_ERROR = NoSuchMethodError.class;
+ public static final Class<NoClassDefFoundError> NO_CLASS_DEF_FOUND_ERROR = NoClassDefFoundError.class;
+ public static final Class<UnsatisfiedLinkError> UNSATISFIED_LINK_ERROR = UnsatisfiedLinkError.class;
+ public static final Class<VerifyError> VERIFY_ERROR = VerifyError.class;
/* UnsupportedClassVersionError is new in JDK 1.2 */
//public static final Class UnsupportedClassVersionError = UnsupportedClassVersionError.class;
/** Run-Time Exceptions
*/
- public static final Class NULL_POINTER_EXCEPTION = NullPointerException.class;
- public static final Class ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION = ArrayIndexOutOfBoundsException.class;
- public static final Class ARITHMETIC_EXCEPTION = ArithmeticException.class;
+ public static final Class<NullPointerException> NULL_POINTER_EXCEPTION = NullPointerException.class;
+ public static final Class<ArrayIndexOutOfBoundsException> ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION = ArrayIndexOutOfBoundsException.class;
+ public static final Class<ArithmeticException> ARITHMETIC_EXCEPTION = ArithmeticException.class;
public static final Class NEGATIVE_ARRAY_SIZE_EXCEPTION = NegativeArraySizeException.class;
- public static final Class CLASS_CAST_EXCEPTION = ClassCastException.class;
- public static final Class ILLEGAL_MONITOR_STATE = IllegalMonitorStateException.class;
+ public static final Class<ClassCastException> CLASS_CAST_EXCEPTION = ClassCastException.class;
+ public static final Class<IllegalMonitorStateException> ILLEGAL_MONITOR_STATE = IllegalMonitorStateException.class;
/** Pre-defined exception arrays according to chapters 5.1-5.4 of the Java Virtual
* Machine Specification
private Constant[] pool;
private int poolSize; // number of entries in the pool (could be < pool.length as the array is resized in 'chunks')
- private Map utf8Cache = new HashMap();
- private Map methodCache = new HashMap();
- private Map fieldCache = new HashMap();
+ private Map<String, Integer> utf8Cache = new HashMap<String, Integer>();
+ private Map<String, Integer> methodCache = new HashMap<String, Integer>();
+ private Map<String, Integer> fieldCache = new HashMap<String, Integer>();
public int getSize() { return poolSize; }
public int lookupUtf8(String string) {
- Integer pos = (Integer) utf8Cache.get(string);
+ Integer pos = utf8Cache.get(string);
if (pos!=null) return pos.intValue();
for (int i=1;i<poolSize;i++) {
Constant c = pool[i];
public int lookupFieldref(String searchClassname, String searchFieldname, String searchSignature) {
searchClassname = searchClassname.replace('.','/');
String k = new StringBuffer().append(searchClassname).append(searchFieldname).append(searchSignature).toString();
- Integer pos = (Integer) fieldCache.get(k);
+ Integer pos = fieldCache.get(k);
if (pos!=null) return pos.intValue();
for (int i=1;i<poolSize;i++) {
Constant c = pool[i];
public int lookupMethodref(String searchClassname, String searchMethodName, String searchSignature) {
String key = new StringBuffer().append(searchClassname).append(searchMethodName).append(searchSignature).toString();
- Integer cached = (Integer)methodCache.get(key);
+ Integer cached = methodCache.get(key);
if (cached!=null) return cached.intValue();
searchClassname = searchClassname.replace('.','/');
for (int i=1;i<poolSize;i++) {
/**
* Abstract super class for fields and methods.
*
- * @version $Id: FieldOrMethod.java,v 1.7 2008/06/06 04:24:20 aclement Exp $
+ * @version $Id: FieldOrMethod.java,v 1.8 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
*/
public abstract class FieldOrMethod extends Modifiers implements Cloneable, Node {
// remain there.
if (annotations==null) {
// Find attributes that contain annotation data
- List accumulatedAnnotations = new ArrayList();
+ List<AnnotationGen> accumulatedAnnotations = new ArrayList<AnnotationGen>();
for (int i = 0; i < attributes.length; i++) {
Attribute attribute = attributes[i];
if (attribute instanceof RuntimeAnnotations) {
if (accumulatedAnnotations.size()==0) {
annotations = AnnotationGen.NO_ANNOTATIONS;
} else {
- annotations = (AnnotationGen[])accumulatedAnnotations.toArray(new AnnotationGen[]{});
+ annotations = accumulatedAnnotations.toArray(new AnnotationGen[]{});
}
}
return annotations;
* The intent of this class is to represent a parsed or otherwise existing class file. Those interested in programatically
* generating classes should see the <a href="../generic/ClassGen.html">ClassGen</a> class.
*
- * @version $Id: JavaClass.java,v 1.14 2008/10/20 18:31:01 aclement Exp $
+ * @version $Id: JavaClass.java,v 1.15 2009/09/09 19:56:20 aclement Exp $
* @see org.aspectj.apache.bcel.generic.ClassGen
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
*/
public AnnotationGen[] getAnnotations() {
if (annotationsOutOfDate) {
// Find attributes that contain annotation data
- List accumulatedAnnotations = new ArrayList();
+ List<AnnotationGen> accumulatedAnnotations = new ArrayList<AnnotationGen>();
for (int i = 0; i < attributes.length; i++) {
Attribute attribute = attributes[i];
if (attribute instanceof RuntimeAnnotations) {
accumulatedAnnotations.addAll(runtimeAnnotations.getAnnotations());
}
}
- annotations = (AnnotationGen[]) accumulatedAnnotations.toArray(new AnnotationGen[] {});
+ annotations = accumulatedAnnotations.toArray(new AnnotationGen[] {});
annotationsOutOfDate = false;
}
return annotations;
/**
* @return String representing class contents.
*/
+ @Override
public String toString() {
String access = Utility.accessToString(modifiers, true);
access = access.equals("") ? "" : access + " ";
}
c.constant_pool = constant_pool.copy();
- c.interfaces = (int[]) interfaces.clone();
- c.interface_names = (String[]) interface_names.clone();
+ c.interfaces = interfaces.clone();
+ c.interface_names = interface_names.clone();
c.fields = new Field[fields.length];
for (int i = 0; i < fields.length; i++) {
* for a method in the class. See JVM specification for details.
* A method has access flags, a name, a signature and a number of attributes.
*
- * @version $Id: Method.java,v 1.7 2008/08/26 15:01:15 aclement Exp $
+ * @version $Id: Method.java,v 1.8 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
*/
public final class Method extends FieldOrMethod {
boolean foundSome = false;
// Build a list of annotation arrays, one per argument
if (parameterAnnotationsInvis!=null || parameterAnnotationsVis!=null) {
- List annotationsForEachParameter = new ArrayList();
+ List<AnnotationGen[]> annotationsForEachParameter = new ArrayList<AnnotationGen[]>();
AnnotationGen[] visibleOnes = null;
AnnotationGen[] invisibleOnes = null;
for (int i=0; i<parameterCount; i++) {
annotationsForEachParameter.add(complete);
}
if (foundSome) {
- unpackedParameterAnnotations = (AnnotationGen[][])annotationsForEachParameter.toArray(new AnnotationGen[][]{});
+ unpackedParameterAnnotations = annotationsForEachParameter.toArray(new AnnotationGen[][]{});
return;
}
}
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen;
+import org.aspectj.apache.bcel.classfile.annotation.RuntimeAnnotations;
import org.aspectj.apache.bcel.classfile.annotation.RuntimeInvisibleAnnotations;
import org.aspectj.apache.bcel.classfile.annotation.RuntimeInvisibleParameterAnnotations;
+import org.aspectj.apache.bcel.classfile.annotation.RuntimeParameterAnnotations;
import org.aspectj.apache.bcel.classfile.annotation.RuntimeVisibleAnnotations;
import org.aspectj.apache.bcel.classfile.annotation.RuntimeVisibleParameterAnnotations;
import org.aspectj.apache.bcel.util.ByteSequence;
/**
* Utility functions that do not really belong to any class in particular.
*
- * @version $Id: Utility.java,v 1.7 2008/05/30 17:29:13 aclement Exp $
+ * @version $Id: Utility.java,v 1.8 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
*
* modified: Andy Clement 2-mar-05 Removed unnecessary static and optimized
* @param cp The constant pool gen where we can create the necessary name refs
* @param vec A list of AnnotationGen objects
*/
- public static Attribute[] getAnnotationAttributes(ConstantPool cp,List vec) {
+ public static Attribute[] getAnnotationAttributes(ConstantPool cp,List<AnnotationGen> vec) {
if (vec.size()==0) return null;
// put the annotations in the right output stream
for (int i=0; i<vec.size(); i++) {
- AnnotationGen a = (AnnotationGen)vec.get(i);
+ AnnotationGen a = vec.get(i);
if (a.isRuntimeVisible()) countVisible++;
else countInvisible++;
}
// put the annotations in the right output stream
for (int i=0; i<vec.size(); i++) {
- AnnotationGen a = (AnnotationGen)vec.get(i);
+ AnnotationGen a = vec.get(i);
if (a.isRuntimeVisible()) a.dump(rvaDos);
else a.dump(riaDos);
}
if (rvaData.length>2) rvaIndex = cp.addUtf8("RuntimeVisibleAnnotations");
if (riaData.length>2) riaIndex = cp.addUtf8("RuntimeInvisibleAnnotations");
- List newAttributes = new ArrayList();
+ List<RuntimeAnnotations> newAttributes = new ArrayList<RuntimeAnnotations>();
if (rvaData.length>2) {
newAttributes.add(
new RuntimeVisibleAnnotations(rvaIndex,rvaData.length,rvaData,cp));
new RuntimeInvisibleAnnotations(riaIndex,riaData.length,riaData,cp));
}
- return (Attribute[])newAttributes.toArray(new Attribute[]{});
+ return newAttributes.toArray(new Attribute[]{});
} catch (IOException e) {
System.err.println("IOException whilst processing annotations");
e.printStackTrace();
if (totalVisCount>0) rvaIndex = cp.addUtf8("RuntimeVisibleParameterAnnotations");
if (totalInvisCount>0) riaIndex = cp.addUtf8("RuntimeInvisibleParameterAnnotations");
- List newAttributes = new ArrayList();
+ List<RuntimeParameterAnnotations> newAttributes = new ArrayList<RuntimeParameterAnnotations>();
if (totalVisCount>0) {
newAttributes.add(
new RuntimeInvisibleParameterAnnotations(riaIndex,riaData.length,riaData,cp));
}
- return (Attribute[])newAttributes.toArray(new Attribute[]{});
+ return newAttributes.toArray(new Attribute[]{});
} catch (IOException e) {
System.err.println("IOException whilst processing parameter annotations");
e.printStackTrace();
public static final AnnotationGen[] NO_ANNOTATIONS = new AnnotationGen[0];
private int typeIndex;
- private List /* ElementNameValuePairGen */ evs;
+ private List /* ElementNameValuePairGen */<ElementNameValuePairGen> evs;
private ConstantPool cpool;
private boolean isRuntimeVisible = false;
evs = copyValues(a.getValues(),cpool,copyPoolEntries);
}
- private List copyValues(List in,ConstantPool cpool,boolean copyPoolEntries) {
- List out = new ArrayList();
- for (Iterator iter = in.iterator(); iter.hasNext();) {
- ElementNameValuePairGen nvp = (ElementNameValuePairGen) iter.next();
+ private List<ElementNameValuePairGen> copyValues(List<ElementNameValuePairGen> in,ConstantPool cpool,boolean copyPoolEntries) {
+ List<ElementNameValuePairGen> out = new ArrayList<ElementNameValuePairGen>();
+ for (Iterator<ElementNameValuePairGen> iter = in.iterator(); iter.hasNext();) {
+ ElementNameValuePairGen nvp = iter.next();
out.add(new ElementNameValuePairGen(nvp,cpool,copyPoolEntries));
}
return out;
private AnnotationGen(ConstantPool cpool) {
this.cpool = cpool;
- this.evs=new ArrayList();
+ this.evs=new ArrayList<ElementNameValuePairGen>();
}
/**
//// return a;
// }
- public AnnotationGen(ObjectType type,List /*ElementNameValuePairGen*/ elements,boolean vis,ConstantPool cpool) {
+ public AnnotationGen(ObjectType type,List /*ElementNameValuePairGen*/<ElementNameValuePairGen> elements,boolean vis,ConstantPool cpool) {
this.cpool = cpool;
if (type!=null) this.typeIndex = cpool.addUtf8(type.getSignature()); // Only null for funky *temporary* FakeAnnotation objects
evs = elements;
dos.writeShort(typeIndex); // u2 index of type name in cpool
dos.writeShort(evs.size()); // u2 element_value pair count
for (int i = 0 ; i<evs.size();i++) {
- ElementNameValuePairGen envp = (ElementNameValuePairGen) evs.get(i);
+ ElementNameValuePairGen envp = evs.get(i);
envp.dump(dos);
}
}
public void addElementNameValuePair(ElementNameValuePairGen evp) {
- if (evs == null) evs = new ArrayList();
+ if (evs == null) evs = new ArrayList<ElementNameValuePairGen>();
evs.add(evp);
}
/**
* Returns list of ElementNameValuePair objects
*/
- public List getValues() {
+ public List<ElementNameValuePairGen> getValues() {
return evs;
}
*/
public boolean hasNameValuePair(String n, String v) {
for (int i=0;i<evs.size();i++) {
- ElementNameValuePairGen pair = (ElementNameValuePairGen)evs.get(i);
+ ElementNameValuePairGen pair = evs.get(i);
if (pair.getNameString().equals(n)) {
if (pair.getValue().stringifyValue().equals(v)) return true;
}
*/
public boolean hasNamedValue(String n) {
for (int i=0;i<evs.size();i++) {
- ElementNameValuePairGen pair = (ElementNameValuePairGen)evs.get(i);
+ ElementNameValuePairGen pair = evs.get(i);
if (pair.getNameString().equals(n)) return true;
}
return false;
public abstract class RuntimeAnnotations extends Attribute {
- private List /*Annotation*/ annotations;
+ private List /*Annotation*/<AnnotationGen> annotations;
private boolean visible;
// Keep just a byte stream of the data until someone actually asks for it
ConstantPool cpool) {
super(attrid,nameIdx,len,cpool);
this.visible = visible;
- annotations = new ArrayList();
+ annotations = new ArrayList<AnnotationGen>();
}
public RuntimeAnnotations(byte attrid,boolean visible,int nameIdx,int len,byte[] data,ConstantPool cpool) {
super(attrid,nameIdx,len,cpool);
this.visible = visible;
- annotations = new ArrayList();
+ annotations = new ArrayList<AnnotationGen>();
annotation_data = data;
}
- public List getAnnotations() {
+ public List<AnnotationGen> getAnnotations() {
if (!inflated) inflate();
return annotations;
}
dos.write(annotation_data,0,length);
} else {
dos.writeShort(annotations.size());
- for (Iterator i = annotations.iterator(); i.hasNext();) {
- AnnotationGen ann = (AnnotationGen) i.next();
+ for (Iterator<AnnotationGen> i = annotations.iterator(); i.hasNext();) {
+ AnnotationGen ann = i.next();
ann.dump(dos);
}
}
public abstract class RuntimeParameterAnnotations extends Attribute {
- private List /*Annotation[]*/ parameterAnnotations;
+ private List /*Annotation[]*/<AnnotationGen[]> parameterAnnotations;
private boolean visible;
int nameIdx, int len, ConstantPool cpool) {
super(attrid,nameIdx,len,cpool);
this.visible = visible;
- parameterAnnotations = new ArrayList();
+ parameterAnnotations = new ArrayList<AnnotationGen[]>();
}
public RuntimeParameterAnnotations(byte attrid,boolean visible,int nameIdx,int len,byte[] data,ConstantPool cpool) {
super(attrid,nameIdx,len,cpool);
this.visible = visible;
- parameterAnnotations = new ArrayList();
+ parameterAnnotations = new ArrayList<AnnotationGen[]>();
annotation_data = data;
}
}
/** Return a list of Annotation[] - each list entry contains the annotations for one parameter */
- public List /*Annotation[]*/ getParameterAnnotations() {
+ public List /*Annotation[]*/<AnnotationGen[]> getParameterAnnotations() {
if (!inflated) inflate();
return parameterAnnotations;
}
if (parameterIndex>=parameterAnnotations.size()) {
return AnnotationGen.NO_ANNOTATIONS;
}
- return (AnnotationGen[])parameterAnnotations.get(parameterIndex);
+ return parameterAnnotations.get(parameterIndex);
}
public boolean areVisible() {
} else {
dos.writeByte(parameterAnnotations.size());
for (int i=0; i<parameterAnnotations.size(); i++) {
- AnnotationGen[] annotations = (AnnotationGen[])parameterAnnotations.get(i);
+ AnnotationGen[] annotations = parameterAnnotations.get(i);
dos.writeShort(annotations.length);
for (int j=0; j<annotations.length;j++) {
annotations[j].dump(dos);
import java.util.List;
import org.aspectj.apache.bcel.Constants;
+import org.aspectj.apache.bcel.classfile.FieldOrMethod;
import org.aspectj.apache.bcel.classfile.Modifiers;
import org.aspectj.apache.bcel.classfile.Attribute;
import org.aspectj.apache.bcel.classfile.ConstantPool;
* existing java class (file).
*
* @see JavaClass
- * @version $Id: ClassGen.java,v 1.10 2008/08/27 23:59:48 aclement Exp $
+ * @version $Id: ClassGen.java,v 1.11 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
*
* Upgraded, Andy Clement 9th Mar 06 - calculates SUID
private ConstantPool cp;
- private ArrayList field_vec = new ArrayList();
- private ArrayList method_vec = new ArrayList();
- private ArrayList attributesList = new ArrayList();
- private ArrayList interface_vec = new ArrayList();
- private ArrayList annotation_vec= new ArrayList();
+ private ArrayList<Field> field_vec = new ArrayList<Field>();
+ private ArrayList<Method> method_vec = new ArrayList<Method>();
+ private ArrayList<Attribute> attributesList = new ArrayList<Attribute>();
+ private ArrayList<String> interface_vec = new ArrayList<String>();
+ private ArrayList<AnnotationGen> annotation_vec= new ArrayList<AnnotationGen>();
/** Convenience constructor to set up some important values initially.
*
* Look for attributes representing annotations and unpack them.
*/
private AnnotationGen[] unpackAnnotations(Attribute[] attrs) {
- List /*AnnotationGen*/ annotationGenObjs = new ArrayList();
+ List /*AnnotationGen*/<AnnotationGen> annotationGenObjs = new ArrayList<AnnotationGen>();
for (int i = 0; i < attrs.length; i++) {
Attribute attr = attrs[i];
if (attr instanceof RuntimeVisibleAnnotations) {
RuntimeVisibleAnnotations rva = (RuntimeVisibleAnnotations)attr;
- List annos = rva.getAnnotations();
- for (Iterator iter = annos.iterator(); iter.hasNext();) {
- AnnotationGen a = (AnnotationGen) iter.next();
+ List<AnnotationGen> annos = rva.getAnnotations();
+ for (Iterator<AnnotationGen> iter = annos.iterator(); iter.hasNext();) {
+ AnnotationGen a = iter.next();
annotationGenObjs.add(new AnnotationGen(a,getConstantPool(),false));
}
} else if (attr instanceof RuntimeInvisibleAnnotations) {
RuntimeInvisibleAnnotations ria = (RuntimeInvisibleAnnotations)attr;
- List annos = ria.getAnnotations();
- for (Iterator iter = annos.iterator(); iter.hasNext();) {
- AnnotationGen a = (AnnotationGen) iter.next();
+ List<AnnotationGen> annos = ria.getAnnotations();
+ for (Iterator<AnnotationGen> iter = annos.iterator(); iter.hasNext();) {
+ AnnotationGen a = iter.next();
annotationGenObjs.add(new AnnotationGen(a,getConstantPool(),false));
}
}
}
- return (AnnotationGen[])annotationGenObjs.toArray(new AnnotationGen[]{});
+ return annotationGenObjs.toArray(new AnnotationGen[]{});
}
/**
/** @return field object with given name, or null
*/
public Field containsField(String name) {
- for(Iterator e=field_vec.iterator(); e.hasNext(); ) {
- Field f = (Field)e.next();
+ for(Iterator<Field> e=field_vec.iterator(); e.hasNext(); ) {
+ Field f = e.next();
if(f.getName().equals(name))
return f;
}
/** @return method object with given name and signature, or null
*/
public Method containsMethod(String name, String signature) {
- for(Iterator e=method_vec.iterator(); e.hasNext();) {
- Method m = (Method)e.next();
+ for(Iterator<Method> e=method_vec.iterator(); e.hasNext();) {
+ Method m = e.next();
if(m.getName().equals(name) && m.getSignature().equals(signature))
return m;
}
}
public Method getMethodAt(int pos) {
- return (Method)method_vec.get(pos);
+ return method_vec.get(pos);
}
public String[] getInterfaceNames() {
int[] interfaces = new int[size];
for(int i=0; i < size; i++)
- interfaces[i] = cp.addClass((String)interface_vec.get(i));
+ interfaces[i] = cp.addClass(interface_vec.get(i));
return interfaces;
}
dos.writeInt(classmods);
// 3. ordered list of interfaces
- List list = new ArrayList();
+ List<FieldOrMethod> list = new ArrayList<FieldOrMethod>();
String[] names = getInterfaceNames();
if (names!=null) {
Arrays.sort(names);
Collections.sort(list,new FieldComparator());
int relevantFlags = Constants.ACC_PUBLIC | Constants.ACC_PRIVATE | Constants.ACC_PROTECTED |
Constants.ACC_STATIC | Constants.ACC_FINAL | Constants.ACC_VOLATILE | Constants.ACC_TRANSIENT;
- for (Iterator iter = list.iterator(); iter.hasNext();) {
+ for (Iterator<FieldOrMethod> iter = list.iterator(); iter.hasNext();) {
Field f = (Field) iter.next();
dos.writeUTF(f.getName());
dos.writeInt(relevantFlags&f.getModifiers());
// some up front method processing: discover clinit, init and ordinary methods of interest:
list.clear(); // now used for methods
- List ctors = new ArrayList();
+ List<Method> ctors = new ArrayList<Method>();
boolean hasClinit = false;
for (int i = 0; i < methods.length; i++) {
Method m = methods[i];
Constants.ACC_NATIVE | Constants.ACC_ABSTRACT | Constants.ACC_STRICT;
// 6. sorted non-private constructors
- for (Iterator iter = ctors.iterator(); iter.hasNext();) {
- Method m = (Method) iter.next();
+ for (Iterator<Method> iter = ctors.iterator(); iter.hasNext();) {
+ Method m = iter.next();
dos.writeUTF(m.getName()); // <init>
dos.writeInt(relevantFlags & m.getModifiers());
dos.writeUTF(m.getSignature().replace('/','.'));
}
// 7. sorted non-private methods
- for (Iterator iter = list.iterator(); iter.hasNext();) {
+ for (Iterator<FieldOrMethod> iter = list.iterator(); iter.hasNext();) {
Method m = (Method) iter.next();
dos.writeUTF(m.getName());
dos.writeInt(relevantFlags & m.getModifiers());
}
public boolean hasAttribute(String attributeName) {
- for (Iterator iter = attributesList.iterator(); iter.hasNext();) {
- Attribute attr = (Attribute) iter.next();
+ for (Iterator<Attribute> iter = attributesList.iterator(); iter.hasNext();) {
+ Attribute attr = iter.next();
if (attr.getName().equals(attributeName)) return true;
}
return false;
}
public Attribute getAttribute(String attributeName) {
- for (Iterator iter = attributesList.iterator(); iter.hasNext();) {
- Attribute attr = (Attribute) iter.next();
+ for (Iterator<Attribute> iter = attributesList.iterator(); iter.hasNext();) {
+ Attribute attr = iter.next();
if (attr.getName().equals(attributeName)) return attr;
}
return null;
* one can do is to add a constant value attribute to a field (which must of
* course be compatible with the declared type).
*
- * @version $Id: FieldGen.java,v 1.5 2008/05/28 23:52:59 aclement Exp $
+ * @version $Id: FieldGen.java,v 1.6 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
* @see Field
*/
setValue(((ConstantValue)attrs[i]).getConstantValueIndex());
} else if (attrs[i] instanceof RuntimeAnnotations) {
RuntimeAnnotations runtimeAnnotations = (RuntimeAnnotations)attrs[i];
- List l = runtimeAnnotations.getAnnotations();
- for (Iterator it = l.iterator(); it.hasNext();) {
- AnnotationGen element = (AnnotationGen) it.next();
+ List<AnnotationGen> l = runtimeAnnotations.getAnnotations();
+ for (Iterator<AnnotationGen> it = l.iterator(); it.hasNext();) {
+ AnnotationGen element = it.next();
addAnnotation(new AnnotationGen(element,cp,false));
}
} else {
* Super class for FieldGen and MethodGen objects, since they have some methods
* in common!
*
- * @version $Id: FieldGenOrMethodGen.java,v 1.4 2008/05/28 23:52:59 aclement Exp $
+ * @version $Id: FieldGenOrMethodGen.java,v 1.5 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
*/
public abstract class FieldGenOrMethodGen extends Modifiers implements Cloneable {
protected String name;
protected Type type;
protected ConstantPool cp;
- private ArrayList/*<Attribute>*/ attributeList = new ArrayList();
- private ArrayList annotationList = new ArrayList();
+ private ArrayList/*<Attribute>*/<Attribute> attributeList = new ArrayList<Attribute>();
+ private ArrayList<AnnotationGen> annotationList = new ArrayList<AnnotationGen>();
protected FieldGenOrMethodGen() {
}
annotationList.clear();
}
- public List/*<Attribute>*/ getAttributes() {
+ public List/*<Attribute>*/<Attribute> getAttributes() {
return attributeList;
}
* doubly-linked list. From the outside only the next and the previous instruction (handle) are accessible. One can traverse the
* list via an Enumeration returned by InstructionList.elements().
*
- * @version $Id: InstructionHandle.java,v 1.6 2008/08/28 00:03:46 aclement Exp $
+ * @version $Id: InstructionHandle.java,v 1.7 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
* @see Instruction
* @see BranchHandle
InstructionHandle next, prev; // Will be set from the outside
Instruction instruction;
protected int i_position = -1; // byte code offset of instruction
- private HashSet targeters;
+ private HashSet<InstructionTargeter> targeters;
public final InstructionHandle getNext() {
return next;
*/
public void addTargeter(InstructionTargeter t) {
if (targeters == null) {
- targeters = new HashSet();
+ targeters = new HashSet<InstructionTargeter>();
}
// if(!targeters.contains(t))
return t;
}
- public Set getTargeters() {
+ public Set<InstructionTargeter> getTargeters() {
if (targeters == null || targeters.size() == 0) {
return Collections.EMPTY_SET;
}
*
* A list is finally dumped to a byte code array with <a href="#getByteCode()">getByteCode</a>.
*
- * @version $Id: InstructionList.java,v 1.7 2008/08/28 00:04:04 aclement Exp $
+ * @version $Id: InstructionList.java,v 1.8 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
* @see Instruction
* @see InstructionHandle
return;
}
- ArrayList target_vec = new ArrayList();
+ ArrayList<InstructionHandle> target_vec = new ArrayList<InstructionHandle>();
for (InstructionHandle ih = first; ih != null; ih = ih.next) {
ih.getInstruction().dispose(); // e.g. BranchInstructions release their targets
next = ih.next;
length--;
- Set targeters = ih.getTargeters();
+ Set<InstructionTargeter> targeters = ih.getTargeters();
boolean isOK = false;
- Iterator tIter = targeters.iterator();
+ Iterator<InstructionTargeter> tIter = targeters.iterator();
while (tIter.hasNext()) {
- InstructionTargeter instructionTargeter = (InstructionTargeter) tIter.next();
+ InstructionTargeter instructionTargeter = tIter.next();
if (instructionTargeter.getClass().getName().endsWith("ShadowRange")
|| instructionTargeter.getClass().getName().endsWith("ExceptionRange")
|| instructionTargeter.getClass().getName().endsWith("LineNumberTag")) {
*/
public Instruction[] getInstructions() {
ByteSequence bytes = new ByteSequence(getByteCode());
- ArrayList instructions = new ArrayList();
+ ArrayList<Instruction> instructions = new ArrayList<Instruction>();
try {
while (bytes.available() > 0) {
* @return complete, i.e., deep copy of this list
*/
public InstructionList copy() {
- HashMap map = new HashMap();
+ HashMap<InstructionHandle, InstructionHandle> map = new HashMap<InstructionHandle, InstructionHandle>();
InstructionList il = new InstructionList();
/*
InstructionHandle itarget = bi.getTarget(); // old target
// New target is in hash map
- bc.setTarget((InstructionHandle) map.get(itarget));
+ bc.setTarget(map.get(itarget));
if (bi instanceof InstructionSelect) { // Either LOOKUPSWITCH or TABLESWITCH
InstructionHandle[] itargets = ((InstructionSelect) bi).getTargets();
InstructionHandle[] ctargets = ((InstructionSelect) bc).getTargets();
for (int j = 0; j < itargets.length; j++) { // Update all targets
- ctargets[j] = (InstructionHandle) map.get(itargets[j]);
+ ctargets[j] = map.get(itargets[j]);
}
}
}
* While generating code it may be necessary to insert NOP operations. You can use the `removeNOPs' method to get rid off them. The
* resulting method object can be obtained via the `getMethod()' method.
*
- * @version $Id: MethodGen.java,v 1.11 2009/05/28 00:12:52 aclement Exp $
+ * @version $Id: MethodGen.java,v 1.12 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
* @author <A HREF="http://www.vmeng.com/beard">Patrick C. Beard</A> [setMaxStack()]
* @see InstructionList
private int highestLineNumber = 0;
- private ArrayList localVariablesList = new ArrayList();
- private ArrayList lineNumbersList = new ArrayList();
- private ArrayList exceptionsList = new ArrayList();
- private ArrayList throws_vec = new ArrayList();
- private ArrayList codeAttributesList = new ArrayList();
+ private ArrayList<LocalVariableGen> localVariablesList = new ArrayList<LocalVariableGen>();
+ private ArrayList<LineNumberGen> lineNumbersList = new ArrayList<LineNumberGen>();
+ private ArrayList<CodeExceptionGen> exceptionsList = new ArrayList<CodeExceptionGen>();
+ private ArrayList<String> throws_vec = new ArrayList<String>();
+ private ArrayList<Attribute> codeAttributesList = new ArrayList<Attribute>();
private List[] param_annotations; // Array of lists containing AnnotationGen objects
private boolean hasParameterAnnotations = false;
private boolean haveUnpackedParameterAnnotations = false;
addException(names[j]);
} else if (a instanceof RuntimeAnnotations) {
RuntimeAnnotations runtimeAnnotations = (RuntimeAnnotations) a;
- List l = runtimeAnnotations.getAnnotations();
- for (Iterator it = l.iterator(); it.hasNext();) {
- AnnotationGen element = (AnnotationGen) it.next();
+ List<AnnotationGen> l = runtimeAnnotations.getAnnotations();
+ for (Iterator<AnnotationGen> it = l.iterator(); it.hasNext();) {
+ AnnotationGen element = it.next();
addAnnotation(new AnnotationGen(element, cp, false));
}
} else {
LineNumber[] ln = new LineNumber[size];
for (int i = 0; i < size; i++) {
- ln[i] = ((LineNumberGen) lineNumbersList.get(i)).getLineNumber();
+ ln[i] = lineNumbersList.get(i).getLineNumber();
}
return new LineNumberTable(cp.addUtf8("LineNumberTable"), 2 + ln.length * 4, ln, cp);
try {
for (int i = 0; i < size; i++) {
- CodeExceptionGen c = (CodeExceptionGen) exceptionsList.get(i);
+ CodeExceptionGen c = exceptionsList.get(i);
c_exc[i] = c.getCodeException(cp);
}
} catch (ArrayIndexOutOfBoundsException e) {
try {
for (int i = 0; i < size; i++)
- ex[i] = cp.addClass((String) throws_vec.get(i));
+ ex[i] = cp.addClass(throws_vec.get(i));
} catch (ArrayIndexOutOfBoundsException e) {
}
if ((il != null) && !isAbstract()) {
// Remove any stale code attribute
- List attributes = getAttributes();
+ List<Attribute> attributes = getAttributes();
for (int i = 0; i < attributes.size(); i++) {
- Attribute a = (Attribute) attributes.get(i);
+ Attribute a = attributes.get(i);
if (a instanceof Code)
removeAttribute(a);
}
}
static final class BranchStack {
- Stack branchTargets = new Stack();
- Hashtable visitedTargets = new Hashtable();
+ Stack<BranchTarget> branchTargets = new Stack<BranchTarget>();
+ Hashtable<InstructionHandle, BranchTarget> visitedTargets = new Hashtable<InstructionHandle, BranchTarget>();
public void push(InstructionHandle target, int stackDepth) {
if (visited(target))
public BranchTarget pop() {
if (!branchTargets.empty()) {
- BranchTarget bt = (BranchTarget) branchTargets.pop();
+ BranchTarget bt = branchTargets.pop();
return bt;
}
StringBuffer buf = new StringBuffer(signature);
if (throws_vec.size() > 0) {
- for (Iterator e = throws_vec.iterator(); e.hasNext();)
+ for (Iterator<String> e = throws_vec.iterator(); e.hasNext();)
buf.append("\n\t\tthrows " + e.next());
}
if (haveUnpackedParameterAnnotations)
return;
// Find attributes that contain parameter annotation data
- List attrs = getAttributes();
+ List<Attribute> attrs = getAttributes();
RuntimeParameterAnnotations paramAnnVisAttr = null;
RuntimeParameterAnnotations paramAnnInvisAttr = null;
List accumulatedAnnotations = new ArrayList();
for (int i = 0; i < attrs.size(); i++) {
- Attribute attribute = (Attribute) attrs.get(i);
+ Attribute attribute = attrs.get(i);
if (attribute instanceof RuntimeParameterAnnotations) {
// Initialize param_annotations
// This returns Annotation[] ...
AnnotationGen[] immutableArray = rpa.getAnnotationsOnParameter(j);
// ... which needs transforming into an AnnotationGen[] ...
- List mutable = makeMutableVersion(immutableArray);
+ List<AnnotationGen> mutable = makeMutableVersion(immutableArray);
// ... then add these to any we already know about
param_annotations[j].addAll(mutable);
}
haveUnpackedParameterAnnotations = true;
}
- private List /* AnnotationGen */makeMutableVersion(AnnotationGen[] mutableArray) {
- List result = new ArrayList();
+ private List /* AnnotationGen */<AnnotationGen>makeMutableVersion(AnnotationGen[] mutableArray) {
+ List<AnnotationGen> result = new ArrayList<AnnotationGen>();
for (int i = 0; i < mutableArray.length; i++) {
result.add(new AnnotationGen(mutableArray[i], getConstantPool(), false));
}
param_annotations = new List[parameterTypes.length];
hasParameterAnnotations = true;
}
- List existingAnnotations = param_annotations[parameterIndex];
+ List<AnnotationGen> existingAnnotations = param_annotations[parameterIndex];
if (existingAnnotations != null) {
existingAnnotations.add(annotation);
} else {
- List l = new ArrayList();
+ List<AnnotationGen> l = new ArrayList<AnnotationGen>();
l.add(annotation);
param_annotations[parameterIndex] = l;
}
import org.aspectj.apache.bcel.classfile.ClassFormatException;
import org.aspectj.apache.bcel.classfile.Utility;
-
-/**
- * Abstract super class for all possible java types, namely basic types
- * such as int, object types like String and array types, e.g. int[]
- *
- * @version $Id: Type.java,v 1.10 2008/06/23 04:01:47 aclement Exp $
- * @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
+/**
+ * Abstract super class for all possible java types, namely basic types such as int, object types like String and array types, e.g.
+ * int[]
*
- * modified:
- * AndyClement 2-mar-05: Removed unnecessary static and optimized
+ * @version $Id: Type.java,v 1.11 2009/09/09 19:56:20 aclement Exp $
+ * @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
+ *
+ * modified: AndyClement 2-mar-05: Removed unnecessary static and optimized
*/
public abstract class Type implements java.io.Serializable {
- protected byte type;
- protected String signature; // signature for the type
-
- /* Predefined constants */
- public static final BasicType VOID = new BasicType(Constants.T_VOID);
- public static final BasicType BOOLEAN = new BasicType(Constants.T_BOOLEAN);
- public static final BasicType INT = new BasicType(Constants.T_INT);
- public static final BasicType SHORT = new BasicType(Constants.T_SHORT);
- public static final BasicType BYTE = new BasicType(Constants.T_BYTE);
- public static final BasicType LONG = new BasicType(Constants.T_LONG);
- public static final BasicType DOUBLE = new BasicType(Constants.T_DOUBLE);
- public static final BasicType FLOAT = new BasicType(Constants.T_FLOAT);
- public static final BasicType CHAR = new BasicType(Constants.T_CHAR);
- public static final ObjectType OBJECT = new ObjectType("java.lang.Object");
- public static final ObjectType STRING = new ObjectType("java.lang.String");
- public static final ObjectType OBJECT_ARRAY = new ObjectType("java.lang.Object[]");
- public static final ObjectType STRING_ARRAY = new ObjectType("java.lang.String[]");
- public static final ObjectType STRINGBUFFER = new ObjectType("java.lang.StringBuffer");
- public static final ObjectType STRINGBUILDER= new ObjectType("java.lang.StringBuilder");
- public static final ObjectType THROWABLE = new ObjectType("java.lang.Throwable");
- public static final ObjectType CLASS = new ObjectType("java.lang.Class");
- public static final ObjectType INTEGER = new ObjectType("java.lang.Integer");
- public static final ObjectType EXCEPTION = new ObjectType("java.lang.Exception");
- public static final ObjectType LIST = new ObjectType("java.util.List");
- public static final ObjectType ITERATOR = new ObjectType("java.util.Iterator");
- public static final Type[] NO_ARGS = new Type[0];
- public static final ReferenceType NULL = new ReferenceType(){};
- public static final Type UNKNOWN = new Type(Constants.T_UNKNOWN,"<unknown object>"){};
- public static final Type[] STRINGARRAY1 = new Type[]{STRING};
- public static final Type[] STRINGARRAY2 = new Type[]{STRING,STRING};
- public static final Type[] STRINGARRAY3 = new Type[]{STRING,STRING,STRING};
- public static final Type[] STRINGARRAY4 = new Type[]{STRING,STRING,STRING,STRING};
- public static final Type[] STRINGARRAY5 = new Type[]{STRING,STRING,STRING,STRING,STRING};
- public static final Type[] STRINGARRAY6 = new Type[]{STRING,STRING,STRING,STRING,STRING,STRING};
- public static final Type[] STRINGARRAY7 = new Type[]{STRING,STRING,STRING,STRING,STRING,STRING,STRING};
-
- private static Map commonTypes = new HashMap();
-
- static {
- commonTypes.put(STRING.getSignature(), STRING);
- commonTypes.put(THROWABLE.getSignature(), THROWABLE);
- commonTypes.put(VOID.getSignature(), VOID);
- commonTypes.put(BOOLEAN.getSignature(), BOOLEAN);
- commonTypes.put(BYTE.getSignature(), BYTE);
- commonTypes.put(SHORT.getSignature(), SHORT);
- commonTypes.put(CHAR.getSignature(), CHAR);
- commonTypes.put(INT.getSignature(), INT);
- commonTypes.put(LONG.getSignature(), LONG);
- commonTypes.put(DOUBLE.getSignature(), DOUBLE);
- commonTypes.put(FLOAT.getSignature(), FLOAT);
- commonTypes.put(CLASS.getSignature(), CLASS);
- commonTypes.put(OBJECT.getSignature(), OBJECT);
- commonTypes.put(STRING_ARRAY.getSignature(), STRING_ARRAY);
- commonTypes.put(OBJECT_ARRAY.getSignature(), OBJECT_ARRAY);
- commonTypes.put(INTEGER.getSignature(), INTEGER);
- commonTypes.put(EXCEPTION.getSignature(), EXCEPTION);
- commonTypes.put(STRINGBUFFER.getSignature(), STRINGBUFFER);
- commonTypes.put(STRINGBUILDER.getSignature(), STRINGBUILDER);
- commonTypes.put(LIST.getSignature(), LIST);
- commonTypes.put(ITERATOR.getSignature(), ITERATOR);
-
- }
-
- protected Type(byte t, String s) {
- type = t;
- signature = s;
- }
-
- /**
- * @return signature for given type.
- */
- public String getSignature() { return signature; }
-
- /**
- * @return type as defined in Constants
- */
- public byte getType() { return type; }
-
- /**
- * @return stack size of this type (2 for long and double, 0 for void, 1 otherwise)
- */
- public int getSize() {
- switch(type) {
- case Constants.T_DOUBLE: case Constants.T_LONG:
- return 2;
- case Constants.T_VOID:
- return 0;
- default:
- return 1;
- }
- }
-
- /**
- * @return Type string, e.g. 'int[]'
- */
- public String toString() {
- return ((this.equals(Type.NULL) || (type >= Constants.T_UNKNOWN)))? signature :
- Utility.signatureToString(signature, false);
- }
-
- /**
- * Convert type to Java method signature, e.g. int[] f(java.lang.String x)
- * becomes (Ljava/lang/String;)[I
- *
- * @param return_type what the method returns
- * @param arg_types what are the argument types
- * @return method signature for given type(s).
- */
- public static String getMethodSignature(Type return_type, Type[] arg_types) {
- StringBuffer buf = new StringBuffer("(");
- int length = (arg_types == null)? 0 : arg_types.length;
- for(int i=0; i < length; i++) {
- buf.append(arg_types[i].getSignature());
- }
- buf.append(')');
- buf.append(return_type.getSignature());
- return buf.toString();
- }
-
- public static final Type getType(String signature) {
- Type t = (Type)commonTypes.get(signature);
- if (t!=null) return t;
- byte type = Utility.typeOfSignature(signature);
- if (type <= Constants.T_VOID) {
- return BasicType.getType(type);
- } else if (type == Constants.T_ARRAY) {
- int dim=0;
- do { dim++; } while(signature.charAt(dim) == '[');
- // Recurse, but just once, if the signature is ok
- Type componentType = getType(signature.substring(dim));
- return new ArrayType(componentType, dim);
- } else { // type == T_REFERENCE
- // generics awareness
- int nextAngly = signature.indexOf('<');
- // Format is 'Lblahblah;'
- int index = signature.indexOf(';'); // Look for closing ';'
-
- String typeString = null;
- if (nextAngly==-1 || nextAngly>index) {
- typeString = signature.substring(1,index).replace('/','.');
- } else {
- boolean endOfSigReached = false;
- int posn = nextAngly;
- int genericDepth=0;
- while (!endOfSigReached) {
- switch (signature.charAt(posn++)) {
- case '<': genericDepth++;break;
- case '>': genericDepth--;break;
- case ';': if (genericDepth==0) endOfSigReached=true;break;
- default:
+ protected byte type;
+ protected String signature; // signature for the type
+
+ /* Predefined constants */
+ public static final BasicType VOID = new BasicType(Constants.T_VOID);
+ public static final BasicType BOOLEAN = new BasicType(Constants.T_BOOLEAN);
+ public static final BasicType INT = new BasicType(Constants.T_INT);
+ public static final BasicType SHORT = new BasicType(Constants.T_SHORT);
+ public static final BasicType BYTE = new BasicType(Constants.T_BYTE);
+ public static final BasicType LONG = new BasicType(Constants.T_LONG);
+ public static final BasicType DOUBLE = new BasicType(Constants.T_DOUBLE);
+ public static final BasicType FLOAT = new BasicType(Constants.T_FLOAT);
+ public static final BasicType CHAR = new BasicType(Constants.T_CHAR);
+ public static final ObjectType OBJECT = new ObjectType("java.lang.Object");
+ public static final ObjectType STRING = new ObjectType("java.lang.String");
+ public static final ObjectType OBJECT_ARRAY = new ObjectType("java.lang.Object[]");
+ public static final ObjectType STRING_ARRAY = new ObjectType("java.lang.String[]");
+ public static final ObjectType STRINGBUFFER = new ObjectType("java.lang.StringBuffer");
+ public static final ObjectType STRINGBUILDER = new ObjectType("java.lang.StringBuilder");
+ public static final ObjectType THROWABLE = new ObjectType("java.lang.Throwable");
+ public static final ObjectType CLASS = new ObjectType("java.lang.Class");
+ public static final ObjectType INTEGER = new ObjectType("java.lang.Integer");
+ public static final ObjectType EXCEPTION = new ObjectType("java.lang.Exception");
+ public static final ObjectType LIST = new ObjectType("java.util.List");
+ public static final ObjectType ITERATOR = new ObjectType("java.util.Iterator");
+ public static final Type[] NO_ARGS = new Type[0];
+ public static final ReferenceType NULL = new ReferenceType() {
+ };
+ public static final Type UNKNOWN = new Type(Constants.T_UNKNOWN, "<unknown object>") {
+ };
+ public static final Type[] STRINGARRAY1 = new Type[] { STRING };
+ public static final Type[] STRINGARRAY2 = new Type[] { STRING, STRING };
+ public static final Type[] STRINGARRAY3 = new Type[] { STRING, STRING, STRING };
+ public static final Type[] STRINGARRAY4 = new Type[] { STRING, STRING, STRING, STRING };
+ public static final Type[] STRINGARRAY5 = new Type[] { STRING, STRING, STRING, STRING, STRING };
+ public static final Type[] STRINGARRAY6 = new Type[] { STRING, STRING, STRING, STRING, STRING, STRING };
+ public static final Type[] STRINGARRAY7 = new Type[] { STRING, STRING, STRING, STRING, STRING, STRING, STRING };
+
+ private static Map<String, Type> commonTypes = new HashMap<String, Type>();
+
+ static {
+ commonTypes.put(STRING.getSignature(), STRING);
+ commonTypes.put(THROWABLE.getSignature(), THROWABLE);
+ commonTypes.put(VOID.getSignature(), VOID);
+ commonTypes.put(BOOLEAN.getSignature(), BOOLEAN);
+ commonTypes.put(BYTE.getSignature(), BYTE);
+ commonTypes.put(SHORT.getSignature(), SHORT);
+ commonTypes.put(CHAR.getSignature(), CHAR);
+ commonTypes.put(INT.getSignature(), INT);
+ commonTypes.put(LONG.getSignature(), LONG);
+ commonTypes.put(DOUBLE.getSignature(), DOUBLE);
+ commonTypes.put(FLOAT.getSignature(), FLOAT);
+ commonTypes.put(CLASS.getSignature(), CLASS);
+ commonTypes.put(OBJECT.getSignature(), OBJECT);
+ commonTypes.put(STRING_ARRAY.getSignature(), STRING_ARRAY);
+ commonTypes.put(OBJECT_ARRAY.getSignature(), OBJECT_ARRAY);
+ commonTypes.put(INTEGER.getSignature(), INTEGER);
+ commonTypes.put(EXCEPTION.getSignature(), EXCEPTION);
+ commonTypes.put(STRINGBUFFER.getSignature(), STRINGBUFFER);
+ commonTypes.put(STRINGBUILDER.getSignature(), STRINGBUILDER);
+ commonTypes.put(LIST.getSignature(), LIST);
+ commonTypes.put(ITERATOR.getSignature(), ITERATOR);
+
+ }
+
+ protected Type(byte t, String s) {
+ type = t;
+ signature = s;
+ }
+
+ /**
+ * @return signature for given type.
+ */
+ public String getSignature() {
+ return signature;
+ }
+
+ /**
+ * @return type as defined in Constants
+ */
+ public byte getType() {
+ return type;
+ }
+
+ /**
+ * @return stack size of this type (2 for long and double, 0 for void, 1 otherwise)
+ */
+ public int getSize() {
+ switch (type) {
+ case Constants.T_DOUBLE:
+ case Constants.T_LONG:
+ return 2;
+ case Constants.T_VOID:
+ return 0;
+ default:
+ return 1;
+ }
+ }
+
+ /**
+ * @return Type string, e.g. 'int[]'
+ */
+ @Override
+ public String toString() {
+ return ((this.equals(Type.NULL) || (type >= Constants.T_UNKNOWN))) ? signature : Utility
+ .signatureToString(signature, false);
+ }
+
+ /**
+ * Convert type to Java method signature, e.g. int[] f(java.lang.String x) becomes (Ljava/lang/String;)[I
+ *
+ * @param return_type what the method returns
+ * @param arg_types what are the argument types
+ * @return method signature for given type(s).
+ */
+ public static String getMethodSignature(Type return_type, Type[] arg_types) {
+ StringBuffer buf = new StringBuffer("(");
+ int length = (arg_types == null) ? 0 : arg_types.length;
+ for (int i = 0; i < length; i++) {
+ buf.append(arg_types[i].getSignature());
+ }
+ buf.append(')');
+ buf.append(return_type.getSignature());
+ return buf.toString();
+ }
+
+ public static final Type getType(String signature) {
+ Type t = commonTypes.get(signature);
+ if (t != null)
+ return t;
+ byte type = Utility.typeOfSignature(signature);
+ if (type <= Constants.T_VOID) {
+ return BasicType.getType(type);
+ } else if (type == Constants.T_ARRAY) {
+ int dim = 0;
+ do {
+ dim++;
+ } while (signature.charAt(dim) == '[');
+ // Recurse, but just once, if the signature is ok
+ Type componentType = getType(signature.substring(dim));
+ return new ArrayType(componentType, dim);
+ } else { // type == T_REFERENCE
+ // generics awareness
+ int nextAngly = signature.indexOf('<');
+ // Format is 'Lblahblah;'
+ int index = signature.indexOf(';'); // Look for closing ';'
+
+ String typeString = null;
+ if (nextAngly == -1 || nextAngly > index) {
+ typeString = signature.substring(1, index).replace('/', '.');
+ } else {
+ boolean endOfSigReached = false;
+ int posn = nextAngly;
+ int genericDepth = 0;
+ while (!endOfSigReached) {
+ switch (signature.charAt(posn++)) {
+ case '<':
+ genericDepth++;
+ break;
+ case '>':
+ genericDepth--;
+ break;
+ case ';':
+ if (genericDepth == 0)
+ endOfSigReached = true;
+ break;
+ default:
+ }
+ }
+ index = posn - 1;
+ typeString = signature.substring(1, nextAngly).replace('/', '.');
+ }
+ // ObjectType doesn't currently store parameterized info
+ return new ObjectType(typeString);
+ }
+ }
+
+ /**
+ * Convert signature to a Type object.
+ *
+ * @param signature signature string such as Ljava/lang/String;
+ * @return type object
+ */
+ public static final TypeHolder getTypeInternal(String signature) throws StringIndexOutOfBoundsException {
+ byte type = Utility.typeOfSignature(signature);
+
+ if (type <= Constants.T_VOID) {
+ return new TypeHolder(BasicType.getType(type), 1);
+ } else if (type == Constants.T_ARRAY) {
+ int dim = 0;
+ do {
+ dim++;
+ } while (signature.charAt(dim) == '[');
+ // Recurse, but just once, if the signature is ok
+ TypeHolder th = getTypeInternal(signature.substring(dim));
+ return new TypeHolder(new ArrayType(th.getType(), dim), dim + th.getConsumed());
+ } else { // type == T_REFERENCE
+ // Format is 'Lblahblah;'
+ int index = signature.indexOf(';'); // Look for closing ';'
+ if (index < 0)
+ throw new ClassFormatException("Invalid signature: " + signature);
+
+ // generics awareness
+ int nextAngly = signature.indexOf('<');
+ String typeString = null;
+ if (nextAngly == -1 || nextAngly > index) {
+ typeString = signature.substring(1, index).replace('/', '.');
+ } else {
+ boolean endOfSigReached = false;
+ int posn = nextAngly;
+ int genericDepth = 0;
+ while (!endOfSigReached) {
+ switch (signature.charAt(posn++)) {
+ case '<':
+ genericDepth++;
+ break;
+ case '>':
+ genericDepth--;
+ break;
+ case ';':
+ if (genericDepth == 0)
+ endOfSigReached = true;
+ break;
+ default:
+ }
}
+ index = posn - 1;
+ typeString = signature.substring(1, nextAngly).replace('/', '.');
}
- index=posn-1;
- typeString = signature.substring(1,nextAngly).replace('/','.');
- }
- // ObjectType doesn't currently store parameterized info
- return new ObjectType(typeString);
- }
- }
-
- /**
- * Convert signature to a Type object.
- * @param signature signature string such as Ljava/lang/String;
- * @return type object
- */
- public static final TypeHolder getTypeInternal(String signature) throws StringIndexOutOfBoundsException {
- byte type = Utility.typeOfSignature(signature);
-
- if (type <= Constants.T_VOID) {
- return new TypeHolder(BasicType.getType(type),1);
- } else if (type == Constants.T_ARRAY) {
- int dim=0;
- do { dim++; } while(signature.charAt(dim) == '[');
- // Recurse, but just once, if the signature is ok
- TypeHolder th = getTypeInternal(signature.substring(dim));
- return new TypeHolder(new ArrayType(th.getType(), dim),dim+th.getConsumed());
- } else { // type == T_REFERENCE
- // Format is 'Lblahblah;'
- int index = signature.indexOf(';'); // Look for closing ';'
- if (index < 0) throw new ClassFormatException("Invalid signature: " + signature);
-
- // generics awareness
- int nextAngly = signature.indexOf('<');
- String typeString = null;
- if (nextAngly==-1 || nextAngly>index) {
- typeString = signature.substring(1,index).replace('/','.');
- } else {
- boolean endOfSigReached = false;
- int posn = nextAngly;
- int genericDepth=0;
- while (!endOfSigReached) {
- switch (signature.charAt(posn++)) {
- case '<': genericDepth++;break;
- case '>': genericDepth--;break;
- case ';': if (genericDepth==0) endOfSigReached=true;break;
- default:
+ // ObjectType doesn't currently store parameterized info
+ return new TypeHolder(new ObjectType(typeString), index + 1);
+ }
+ }
+
+ /**
+ * Convert return value of a method (signature) to a Type object.
+ *
+ * @param signature signature string such as (Ljava/lang/String;)V
+ * @return return type
+ */
+ public static Type getReturnType(String signature) {
+ try {
+ // Read return type after `)'
+ int index = signature.lastIndexOf(')') + 1;
+ return getType(signature.substring(index));
+ } catch (StringIndexOutOfBoundsException e) { // Should never occur
+ throw new ClassFormatException("Invalid method signature: " + signature);
+ }
+ }
+
+ /**
+ * Convert arguments of a method (signature) to an array of Type objects.
+ *
+ * @param signature signature string such as (Ljava/lang/String;)V
+ * @return array of argument types
+ */
+ // OPTIMIZE crap impl
+ public static Type[] getArgumentTypes(String signature) {
+ ArrayList<Type> vec = new ArrayList<Type>();
+ int index;
+ Type[] types;
+
+ try { // Read all declarations between for `(' and `)'
+ if (signature.charAt(0) != '(')
+ throw new ClassFormatException("Invalid method signature: " + signature);
+
+ index = 1; // current string position
+
+ while (signature.charAt(index) != ')') {
+ TypeHolder th = getTypeInternal(signature.substring(index));
+ vec.add(th.getType());
+ index += th.getConsumed(); // update position
}
+ } catch (StringIndexOutOfBoundsException e) { // Should never occur
+ throw new ClassFormatException("Invalid method signature: " + signature);
+ }
+
+ types = new Type[vec.size()];
+ vec.toArray(types);
+ return types;
+ }
+
+ /**
+ * Work out the type of each argument in the signature and return the cumulative sizes of all the types (size means number of
+ * stack slots it consumes, eg double=2, int=1). Unlike the call above, this does minimal unpacking
+ */
+ public static int getArgumentSizes(String signature) {
+ int size = 0;
+ if (signature.charAt(0) != '(')
+ throw new ClassFormatException("Invalid method signature: " + signature);
+
+ int index = 1; // current string position
+ try {
+ while (signature.charAt(index) != ')') {
+ byte type = Utility.typeOfSignature(signature.charAt(index));
+ if (type <= Constants.T_VOID) {
+ size += BasicType.getType(type).getSize();
+ index++;
+ } else if (type == Constants.T_ARRAY) {
+ int dim = 0;
+ do {
+ dim++;
+ } while (signature.charAt(dim + index) == '[');
+ TypeHolder th = getTypeInternal(signature.substring(dim + index));
+ size += 1;
+ index += dim + th.getConsumed();
+ } else { // type == T_REFERENCE
+ // Format is 'Lblahblah;'
+ int index2 = signature.indexOf(';', index); // Look for closing ';'
+
+ // generics awareness
+ int nextAngly = signature.indexOf('<', index);
+ if (nextAngly == -1 || nextAngly > index2) {
+ } else {
+ boolean endOfSigReached = false;
+ int posn = nextAngly;
+ int genericDepth = 0;
+ while (!endOfSigReached) {
+ switch (signature.charAt(posn++)) {
+ case '<':
+ genericDepth++;
+ break;
+ case '>':
+ genericDepth--;
+ break;
+ case ';':
+ if (genericDepth == 0)
+ endOfSigReached = true;
+ break;
+ default:
+ }
+ }
+ index2 = posn - 1;
+ }
+ size++;
+ index = index2 + 1;
+ }
+ }
+ } catch (StringIndexOutOfBoundsException e) { // Should never occur
+ throw new ClassFormatException("Invalid method signature: " + signature);
+ }
+ return size;
+ }
+
+ /**
+ * Return the size of the type expressed in the signature. The signature should contain only one type.
+ */
+ public static int getTypeSize(String signature) {
+ byte type = Utility.typeOfSignature(signature.charAt(0));
+ if (type <= Constants.T_VOID) {
+ return BasicType.getType(type).getSize();
+ } else if (type == Constants.T_ARRAY) {
+ return 1;
+ } else { // type == T_REFERENCE
+ return 1;
+ }
+ }
+
+ /**
+ * Convert runtime java.lang.Class to BCEL Type object.
+ *
+ * @param cl Java class
+ * @return corresponding Type object
+ */
+ public static Type getType(java.lang.Class cl) {
+ if (cl == null) {
+ throw new IllegalArgumentException("Class must not be null");
+ }
+
+ /*
+ * That's an amazingly easy case, because getName() returns the signature. That's what we would have liked anyway.
+ */
+ if (cl.isArray()) {
+ return getType(cl.getName());
+ } else if (cl.isPrimitive()) {
+ if (cl == Integer.TYPE) {
+ return INT;
+ } else if (cl == Void.TYPE) {
+ return VOID;
+ } else if (cl == Double.TYPE) {
+ return DOUBLE;
+ } else if (cl == Float.TYPE) {
+ return FLOAT;
+ } else if (cl == Boolean.TYPE) {
+ return BOOLEAN;
+ } else if (cl == Byte.TYPE) {
+ return BYTE;
+ } else if (cl == Short.TYPE) {
+ return SHORT;
+ } else if (cl == Byte.TYPE) {
+ return BYTE;
+ } else if (cl == Long.TYPE) {
+ return LONG;
+ } else if (cl == Character.TYPE) {
+ return CHAR;
+ } else {
+ throw new IllegalStateException("Ooops, what primitive type is " + cl);
+ }
+ } else { // "Real" class
+ return new ObjectType(cl.getName());
+ }
+ }
+
+ public static String getSignature(java.lang.reflect.Method meth) {
+ StringBuffer sb = new StringBuffer("(");
+ Class[] params = meth.getParameterTypes(); // avoid clone
+
+ for (int j = 0; j < params.length; j++) {
+ sb.append(getType(params[j]).getSignature());
+ }
+
+ sb.append(")");
+ sb.append(getType(meth.getReturnType()).getSignature());
+ return sb.toString();
+ }
+
+ public static String getSignature(java.lang.reflect.Constructor cons) {
+ StringBuffer sb = new StringBuffer("(");
+ Class[] params = cons.getParameterTypes(); // avoid clone
+
+ for (int j = 0; j < params.length; j++) {
+ sb.append(getType(params[j]).getSignature());
+ }
+
+ sb.append(")V");
+ return sb.toString();
+ }
+
+ public static class TypeHolder {
+ private Type t;
+ private int consumed;
+
+ public Type getType() {
+ return t;
+ }
+
+ public int getConsumed() {
+ return consumed;
+ }
+
+ public TypeHolder(Type t, int i) {
+ this.t = t;
+ this.consumed = i;
}
- index=posn-1;
- typeString = signature.substring(1,nextAngly).replace('/','.');
- }
- // ObjectType doesn't currently store parameterized info
- return new TypeHolder(new ObjectType(typeString),index+1);
- }
- }
-
- /**
- * Convert return value of a method (signature) to a Type object.
- *
- * @param signature signature string such as (Ljava/lang/String;)V
- * @return return type
- */
- public static Type getReturnType(String signature) {
- try {
- // Read return type after `)'
- int index = signature.lastIndexOf(')') + 1;
- return getType(signature.substring(index));
- } catch(StringIndexOutOfBoundsException e) { // Should never occur
- throw new ClassFormatException("Invalid method signature: " + signature);
- }
- }
-
- /**
- * Convert arguments of a method (signature) to an array of Type objects.
- * @param signature signature string such as (Ljava/lang/String;)V
- * @return array of argument types
- */
- // OPTIMIZE crap impl
- public static Type[] getArgumentTypes(String signature) {
- ArrayList vec = new ArrayList();
- int index;
- Type[] types;
-
- try { // Read all declarations between for `(' and `)'
- if (signature.charAt(0) != '(')
- throw new ClassFormatException("Invalid method signature: " + signature);
-
- index = 1; // current string position
-
- while(signature.charAt(index) != ')') {
- TypeHolder th = getTypeInternal(signature.substring(index));
- vec.add(th.getType());
- index += th.getConsumed(); // update position
- }
- } catch(StringIndexOutOfBoundsException e) { // Should never occur
- throw new ClassFormatException("Invalid method signature: " + signature);
- }
-
- types = new Type[vec.size()];
- vec.toArray(types);
- return types;
- }
-
- /**
- * Work out the type of each argument in the signature and return the cumulative sizes of
- * all the types (size means number of stack slots it consumes, eg double=2, int=1).
- * Unlike the call above, this does minimal unpacking
- */
- public static int getArgumentSizes(String signature) {
- int size = 0;
- if (signature.charAt(0) != '(')
- throw new ClassFormatException("Invalid method signature: " + signature);
-
- int index = 1; // current string position
- try {
- while (signature.charAt(index) != ')') {
- byte type = Utility.typeOfSignature(signature.charAt(index));
- if (type<=Constants.T_VOID) {
- size+=BasicType.getType(type).getSize();
- index++;
- } else if (type==Constants.T_ARRAY) {
- int dim=0;
- do { dim++; } while(signature.charAt(dim+index) == '[');
- TypeHolder th = getTypeInternal(signature.substring(dim+index));
- size+=1;
- index+=dim+th.getConsumed();
- } else { // type == T_REFERENCE
- // Format is 'Lblahblah;'
- int index2 = signature.indexOf(';',index); // Look for closing ';'
-
- // generics awareness
- int nextAngly = signature.indexOf('<',index);
- if (nextAngly==-1 || nextAngly>index2) {
- } else {
- boolean endOfSigReached = false;
- int posn = nextAngly;
- int genericDepth=0;
- while (!endOfSigReached) {
- switch (signature.charAt(posn++)) {
- case '<': genericDepth++;break;
- case '>': genericDepth--;break;
- case ';': if (genericDepth==0) endOfSigReached=true;break;
- default:
- }
- }
- index2=posn-1;
- }
- size++;
- index=index2+1;
- }
- }
- } catch(StringIndexOutOfBoundsException e) { // Should never occur
- throw new ClassFormatException("Invalid method signature: " + signature);
- }
- return size;
- }
-
- /**
- * Return the size of the type expressed in the signature. The signature should contain only one type.
- */
- public static int getTypeSize(String signature) {
- byte type = Utility.typeOfSignature(signature.charAt(0));
- if (type<=Constants.T_VOID) {
- return BasicType.getType(type).getSize();
- } else if (type==Constants.T_ARRAY) {
- return 1;
- } else { // type == T_REFERENCE
- return 1;
- }
- }
-
- /** Convert runtime java.lang.Class to BCEL Type object.
- * @param cl Java class
- * @return corresponding Type object
- */
- public static Type getType(java.lang.Class cl) {
- if(cl == null) {
- throw new IllegalArgumentException("Class must not be null");
- }
-
- /* That's an amazingly easy case, because getName() returns
- * the signature. That's what we would have liked anyway.
- */
- if(cl.isArray()) {
- return getType(cl.getName());
- } else if(cl.isPrimitive()) {
- if(cl == Integer.TYPE) {
- return INT;
- } else if(cl == Void.TYPE) {
- return VOID;
- } else if(cl == Double.TYPE) {
- return DOUBLE;
- } else if(cl == Float.TYPE) {
- return FLOAT;
- } else if(cl == Boolean.TYPE) {
- return BOOLEAN;
- } else if(cl == Byte.TYPE) {
- return BYTE;
- } else if(cl == Short.TYPE) {
- return SHORT;
- } else if(cl == Byte.TYPE) {
- return BYTE;
- } else if(cl == Long.TYPE) {
- return LONG;
- } else if(cl == Character.TYPE) {
- return CHAR;
- } else {
- throw new IllegalStateException("Ooops, what primitive type is " + cl);
- }
- } else { // "Real" class
- return new ObjectType(cl.getName());
- }
- }
-
- public static String getSignature(java.lang.reflect.Method meth) {
- StringBuffer sb = new StringBuffer("(");
- Class[] params = meth.getParameterTypes(); // avoid clone
-
- for(int j = 0; j < params.length; j++) {
- sb.append(getType(params[j]).getSignature());
- }
-
- sb.append(")");
- sb.append(getType(meth.getReturnType()).getSignature());
- return sb.toString();
- }
-
- public static String getSignature(java.lang.reflect.Constructor cons) {
- StringBuffer sb = new StringBuffer("(");
- Class[] params = cons.getParameterTypes(); // avoid clone
-
- for(int j = 0; j < params.length; j++) {
- sb.append(getType(params[j]).getSignature());
- }
-
- sb.append(")V");
- return sb.toString();
- }
-
- public static class TypeHolder {
- private Type t;
- private int consumed;
-
- public Type getType() {return t;}
- public int getConsumed() { return consumed;}
-
- public TypeHolder(Type t,int i) { this.t=t;this.consumed = i;}
- }
+ }
}
import org.aspectj.apache.bcel.classfile.ClassParser;
import org.aspectj.apache.bcel.classfile.JavaClass;
+import org.aspectj.apache.bcel.util.ClassLoaderRepository.SoftHashMap.SpecialValue;
/**
- * The repository maintains information about which classes have
- * been loaded.
- *
- * It loads its data from the ClassLoader implementation
- * passed into its constructor.
- *
+ * The repository maintains information about which classes have been loaded.
+ *
+ * It loads its data from the ClassLoader implementation passed into its constructor.
+ *
* @see org.aspectj.apache.bcel.Repository
- *
- * @version $Id: ClassLoaderRepository.java,v 1.12 2008/08/26 15:02:41 aclement Exp $
+ *
+ * @version $Id: ClassLoaderRepository.java,v 1.13 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
* @author David Dixon-Peugh
*/
public class ClassLoaderRepository implements Repository {
- private static java.lang.ClassLoader bootClassLoader = null;
- private ClassLoaderReference loaderRef;
-
- // Choice of cache...
- private WeakHashMap /*<URL,SoftRef(JavaClass)>*/localCache = new WeakHashMap();
- private static SoftHashMap /*<URL,JavaClass>*/sharedCache = new SoftHashMap(Collections.synchronizedMap(new HashMap()));
-
- // For fast translation of the classname *intentionally not static*
- private SoftHashMap /*<String,URL>*/ nameMap = new SoftHashMap(new HashMap(), false);
-
- public static boolean useSharedCache =
- System.getProperty("org.aspectj.apache.bcel.useSharedCache","true").equalsIgnoreCase("true");
-
- private static int cacheHitsShared = 0;
- private static int missSharedEvicted = 0; // Misses in shared cache access due to reference GC
- private long timeManipulatingURLs = 0L;
- private long timeSpentLoading = 0L;
- private int classesLoadedCount = 0;
- private int misses = 0;
- private int cacheHitsLocal = 0;
- private int missLocalEvicted = 0; // Misses in local cache access due to reference GC
-
- public ClassLoaderRepository(java.lang.ClassLoader loader) {
- this.loaderRef = new DefaultClassLoaderReference((loader != null) ? loader : getBootClassLoader());
- }
-
- public ClassLoaderRepository(ClassLoaderReference loaderRef) {
- this.loaderRef = loaderRef;
- }
-
- private static synchronized java.lang.ClassLoader getBootClassLoader() {
- if (bootClassLoader == null) {
- bootClassLoader = new URLClassLoader(new URL[0]);
- }
- return bootClassLoader;
- }
-
- // Can track back to its key
- public static class SoftHashMap extends AbstractMap {
- private Map map;
- boolean recordMiss = true; // only interested in recording miss stats sometimes
- private ReferenceQueue rq = new ReferenceQueue();
-
- public SoftHashMap(Map map) { this.map = map; }
- public SoftHashMap() { this(new HashMap()); }
- public SoftHashMap(Map map, boolean b) { this(map); this.recordMiss=b;}
-
- class SpecialValue extends SoftReference {
- private final Object key;
- SpecialValue(Object k,Object v) {
- super(v,rq);
- this.key = k;
- }
- }
-
- private void processQueue() {
- SpecialValue sv = null;
- while ((sv = (SpecialValue)rq.poll())!=null) {
- map.remove(sv.key);
+ private static java.lang.ClassLoader bootClassLoader = null;
+ private ClassLoaderReference loaderRef;
+
+ // Choice of cache...
+ private WeakHashMap /* <URL,SoftRef(JavaClass)> */<URL, SoftReference<JavaClass>> localCache = new WeakHashMap<URL, SoftReference<JavaClass>>();
+ private static SoftHashMap /* <URL,JavaClass> */sharedCache = new SoftHashMap(Collections
+ .synchronizedMap(new HashMap<Object, SpecialValue>()));
+
+ // For fast translation of the classname *intentionally not static*
+ private SoftHashMap /* <String,URL> */nameMap = new SoftHashMap(new HashMap(), false);
+
+ public static boolean useSharedCache = System.getProperty("org.aspectj.apache.bcel.useSharedCache", "true").equalsIgnoreCase(
+ "true");
+
+ private static int cacheHitsShared = 0;
+ private static int missSharedEvicted = 0; // Misses in shared cache access due to reference GC
+ private long timeManipulatingURLs = 0L;
+ private long timeSpentLoading = 0L;
+ private int classesLoadedCount = 0;
+ private int misses = 0;
+ private int cacheHitsLocal = 0;
+ private int missLocalEvicted = 0; // Misses in local cache access due to reference GC
+
+ public ClassLoaderRepository(java.lang.ClassLoader loader) {
+ this.loaderRef = new DefaultClassLoaderReference((loader != null) ? loader : getBootClassLoader());
+ }
+
+ public ClassLoaderRepository(ClassLoaderReference loaderRef) {
+ this.loaderRef = loaderRef;
+ }
+
+ private static synchronized java.lang.ClassLoader getBootClassLoader() {
+ if (bootClassLoader == null) {
+ bootClassLoader = new URLClassLoader(new URL[0]);
+ }
+ return bootClassLoader;
+ }
+
+ // Can track back to its key
+ public static class SoftHashMap extends AbstractMap {
+ private Map<Object, SpecialValue> map;
+ boolean recordMiss = true; // only interested in recording miss stats sometimes
+ private ReferenceQueue rq = new ReferenceQueue();
+
+ public SoftHashMap(Map<Object, SpecialValue> map) {
+ this.map = map;
+ }
+
+ public SoftHashMap() {
+ this(new HashMap());
+ }
+
+ public SoftHashMap(Map map, boolean b) {
+ this(map);
+ this.recordMiss = b;
+ }
+
+ class SpecialValue extends SoftReference {
+ private final Object key;
+
+ SpecialValue(Object k, Object v) {
+ super(v, rq);
+ this.key = k;
+ }
+ }
+
+ private void processQueue() {
+ SpecialValue sv = null;
+ while ((sv = (SpecialValue) rq.poll()) != null) {
+ map.remove(sv.key);
+ }
+ }
+
+ @Override
+ public Object get(Object key) {
+ SpecialValue value = map.get(key);
+ if (value == null)
+ return null;
+ if (value.get() == null) {
+ // it got GC'd
+ map.remove(value.key);
+ if (recordMiss)
+ missSharedEvicted++;
+ return null;
+ } else {
+ return value.get();
+ }
+ }
+
+ @Override
+ public Object put(Object k, Object v) {
+ processQueue();
+ return map.put(k, new SpecialValue(k, v));
}
- }
-
- public Object get(Object key) {
- SpecialValue value = (SpecialValue)map.get(key);
- if (value==null) return null;
- if (value.get()==null) {
- // it got GC'd
- map.remove(value.key);
- if (recordMiss) missSharedEvicted++;
+
+ @Override
+ public Set entrySet() {
+ return map.entrySet();
+ }
+
+ @Override
+ public void clear() {
+ processQueue();
+ map.clear();
+ }
+
+ @Override
+ public int size() {
+ processQueue();
+ return map.size();
+ }
+
+ @Override
+ public Object remove(Object k) {
+ processQueue();
+ SpecialValue value = map.remove(k);
+ if (value == null)
+ return null;
+ if (value.get() != null) {
+ return value.get();
+ }
return null;
+ }
+ }
+
+ /**
+ * Store a new JavaClass into this repository as a soft reference and return the reference
+ */
+ private void storeClassAsReference(URL url, JavaClass clazz) {
+ if (useSharedCache) {
+ clazz.setRepository(null); // can't risk setting repository, we'll get in a pickle!
+ sharedCache.put(url, clazz);
} else {
- return value.get();
+ clazz.setRepository(this);
+ localCache.put(url, new SoftReference<JavaClass>(clazz));
}
- }
-
- public Object put(Object k, Object v) {
- processQueue();
- return map.put(k, new SpecialValue(k,v));
- }
-
- public Set entrySet() {
- return map.entrySet();
- }
-
- public void clear() {
- processQueue();
- map.clear();
- }
-
- public int size() {
- processQueue();
- return map.size();
- }
-
- public Object remove(Object k) {
- processQueue();
- SpecialValue value = (SpecialValue)map.remove(k);
- if (value==null) return null;
- if (value.get()!=null) {
- return value.get();
+ }
+
+ /**
+ * Store a new JavaClass into this Repository.
+ */
+ public void storeClass(JavaClass clazz) {
+ storeClassAsReference(toURL(clazz.getClassName()), clazz);
+ }
+
+ /**
+ * Remove class from repository
+ */
+ public void removeClass(JavaClass clazz) {
+ if (useSharedCache)
+ sharedCache.remove(toURL(clazz.getClassName()));
+ else
+ localCache.remove(toURL(clazz.getClassName()));
+ }
+
+ /**
+ * Find an already defined JavaClass in the local cache.
+ */
+ public JavaClass findClass(String className) {
+ if (useSharedCache)
+ return findClassShared(toURL(className));
+ else
+ return findClassLocal(toURL(className));
+ }
+
+ private JavaClass findClassLocal(URL url) {
+ Object o = localCache.get(url);
+ if (o != null) {
+ o = ((Reference) o).get();
+ if (o != null) {
+ return (JavaClass) o;
+ } else {
+ missLocalEvicted++;
+ }
}
return null;
- }
- }
-
- /**
- * Store a new JavaClass into this repository as a soft reference and return the reference
- */
- private void storeClassAsReference(URL url, JavaClass clazz ) {
- if (useSharedCache) {
- clazz.setRepository(null); // can't risk setting repository, we'll get in a pickle!
- sharedCache.put(url, clazz);
- } else {
- clazz.setRepository(this);
- localCache.put(url, new SoftReference(clazz));
}
- }
-
- /**
- * Store a new JavaClass into this Repository.
- */
- public void storeClass( JavaClass clazz ) {
- storeClassAsReference(toURL(clazz.getClassName()),clazz);
- }
-
- /**
- * Remove class from repository
- */
- public void removeClass(JavaClass clazz) {
- if (useSharedCache) sharedCache.remove(toURL(clazz.getClassName()));
- else localCache.remove(toURL(clazz.getClassName()));
- }
-
- /**
- * Find an already defined JavaClass in the local cache.
- */
- public JavaClass findClass( String className ) {
- if (useSharedCache) return findClassShared(toURL(className));
- else return findClassLocal(toURL(className));
- }
-
- private JavaClass findClassLocal( URL url ) {
- Object o = localCache.get(url);
- if (o != null) {
- o = ((Reference)o).get();
- if (o != null) {
- return (JavaClass)o;
- } else {
- missLocalEvicted++;
- }
- }
- return null;
- }
-
- /**
- * Find an already defined JavaClass in the shared cache.
- */
- private JavaClass findClassShared(URL url) {
- return (JavaClass)sharedCache.get(url);
- }
-
- private URL toURL(String className) {
- URL url = (URL)nameMap.get(className);
- if (url==null) {
- String classFile = className.replace('.', '/');
- url = loaderRef.getClassLoader().getResource(classFile + ".class");
- nameMap.put(className, url);
- }
- return url;
- }
-
- /**
- * Lookup a JavaClass object from the Class Name provided.
- */
- public JavaClass loadClass( String className ) throws ClassNotFoundException {
-
- // translate to a URL
- long time = System.currentTimeMillis();
- java.net.URL url = toURL(className);
- timeManipulatingURLs += (System.currentTimeMillis() - time);
- if (url==null) throw new ClassNotFoundException(className + " not found - unable to determine URL");
-
- JavaClass clazz = null;
-
- // Look in the appropriate cache
- if (useSharedCache) {
- clazz = findClassShared(url);
- if (clazz != null) { cacheHitsShared++; return clazz; }
- } else {
- clazz = findClassLocal(url);
- if (clazz != null) { cacheHitsLocal++; return clazz; }
+
+ /**
+ * Find an already defined JavaClass in the shared cache.
+ */
+ private JavaClass findClassShared(URL url) {
+ return (JavaClass) sharedCache.get(url);
+ }
+
+ private URL toURL(String className) {
+ URL url = (URL) nameMap.get(className);
+ if (url == null) {
+ String classFile = className.replace('.', '/');
+ url = loaderRef.getClassLoader().getResource(classFile + ".class");
+ nameMap.put(className, url);
+ }
+ return url;
+ }
+
+ /**
+ * Lookup a JavaClass object from the Class Name provided.
+ */
+ public JavaClass loadClass(String className) throws ClassNotFoundException {
+
+ // translate to a URL
+ long time = System.currentTimeMillis();
+ java.net.URL url = toURL(className);
+ timeManipulatingURLs += (System.currentTimeMillis() - time);
+ if (url == null)
+ throw new ClassNotFoundException(className + " not found - unable to determine URL");
+
+ JavaClass clazz = null;
+
+ // Look in the appropriate cache
+ if (useSharedCache) {
+ clazz = findClassShared(url);
+ if (clazz != null) {
+ cacheHitsShared++;
+ return clazz;
+ }
+ } else {
+ clazz = findClassLocal(url);
+ if (clazz != null) {
+ cacheHitsLocal++;
+ return clazz;
+ }
+ }
+
+ // Didn't find it in either cache
+ misses++;
+
+ try {
+ // Load it
+ String classFile = className.replace('.', '/');
+ InputStream is = (useSharedCache ? url.openStream() : loaderRef.getClassLoader().getResourceAsStream(
+ classFile + ".class"));
+ if (is == null) {
+ throw new ClassNotFoundException(className + " not found using url " + url);
+ }
+ ClassParser parser = new ClassParser(is, className);
+ clazz = parser.parse();
+
+ // Cache it
+ storeClassAsReference(url, clazz);
+
+ timeSpentLoading += (System.currentTimeMillis() - time);
+ classesLoadedCount++;
+ return clazz;
+ } catch (IOException e) {
+ throw new ClassNotFoundException(e.toString());
+ }
}
-
- // Didn't find it in either cache
- misses++;
-
- try {
- // Load it
- String classFile = className.replace('.', '/');
- InputStream is = (useSharedCache ? url.openStream() : loaderRef.getClassLoader().getResourceAsStream(classFile + ".class"));
- if (is == null) {
- throw new ClassNotFoundException(className + " not found using url "+url);
- }
- ClassParser parser = new ClassParser( is, className );
- clazz = parser.parse();
-
- // Cache it
- storeClassAsReference(url, clazz );
-
- timeSpentLoading += (System.currentTimeMillis() - time);
- classesLoadedCount++;
- return clazz;
- } catch (IOException e) {
- throw new ClassNotFoundException( e.toString() );
- }
- }
-
- /**
- * Produce a report on cache usage.
- */
- public String report() {
- StringBuffer sb = new StringBuffer();
- sb.append("BCEL repository report.");
- if (useSharedCache) sb.append(" (shared cache)");
- else sb.append(" (local cache)");
- sb.append(" Total time spent loading: "+timeSpentLoading+"ms.");
- sb.append(" Time spent manipulating URLs: "+timeManipulatingURLs+"ms.");
- sb.append(" Classes loaded: "+classesLoadedCount+".");
- if (useSharedCache) {
- sb.append(" Shared cache size: "+sharedCache.size());
- sb.append(" Shared cache (hits/missDueToEviction): ("+cacheHitsShared+"/"+missSharedEvicted+").");
- } else {
- sb.append(" Local cache size: "+localCache.size());
- sb.append(" Local cache (hits/missDueToEviction): ("+cacheHitsLocal+"/"+missLocalEvicted+").");
- }
- return sb.toString();
- }
-
- /**
- * Returns an array of the stats, for testing, the order is fixed:
- * 0=time spent loading (static)
- * 1=time spent manipulating URLs (static)
- * 2=classes loaded (static)
- * 3=cache hits shared (static)
- * 4=misses in shared due to eviction (static)
- * 5=cache hits local
- * 6=misses in local due to eviction
- * 7=shared cache size
- */
- public long[] reportStats() {
- return new long[]{timeSpentLoading,timeManipulatingURLs,classesLoadedCount,
- cacheHitsShared,missSharedEvicted,cacheHitsLocal,missLocalEvicted,
- sharedCache.size()};
- }
-
- /**
- * Reset statistics and clear all caches
- */
- public void reset() {
- timeManipulatingURLs = 0L;
- timeSpentLoading = 0L;
- classesLoadedCount = 0;
- cacheHitsLocal = 0;
- cacheHitsShared = 0;
- missSharedEvicted = 0;
- missLocalEvicted = 0;
- misses = 0;
- clear();
- }
-
-
- public JavaClass loadClass(Class clazz) throws ClassNotFoundException {
- return loadClass(clazz.getName());
- }
-
- /** Clear all entries from the local cache */
- public void clear() {
- if (useSharedCache) sharedCache.clear();
- else localCache.clear();
- }
-
-}
+ /**
+ * Produce a report on cache usage.
+ */
+ public String report() {
+ StringBuffer sb = new StringBuffer();
+ sb.append("BCEL repository report.");
+ if (useSharedCache)
+ sb.append(" (shared cache)");
+ else
+ sb.append(" (local cache)");
+ sb.append(" Total time spent loading: " + timeSpentLoading + "ms.");
+ sb.append(" Time spent manipulating URLs: " + timeManipulatingURLs + "ms.");
+ sb.append(" Classes loaded: " + classesLoadedCount + ".");
+ if (useSharedCache) {
+ sb.append(" Shared cache size: " + sharedCache.size());
+ sb.append(" Shared cache (hits/missDueToEviction): (" + cacheHitsShared + "/" + missSharedEvicted + ").");
+ } else {
+ sb.append(" Local cache size: " + localCache.size());
+ sb.append(" Local cache (hits/missDueToEviction): (" + cacheHitsLocal + "/" + missLocalEvicted + ").");
+ }
+ return sb.toString();
+ }
+ /**
+ * Returns an array of the stats, for testing, the order is fixed: 0=time spent loading (static) 1=time spent manipulating URLs
+ * (static) 2=classes loaded (static) 3=cache hits shared (static) 4=misses in shared due to eviction (static) 5=cache hits
+ * local 6=misses in local due to eviction 7=shared cache size
+ */
+ public long[] reportStats() {
+ return new long[] { timeSpentLoading, timeManipulatingURLs, classesLoadedCount, cacheHitsShared, missSharedEvicted,
+ cacheHitsLocal, missLocalEvicted, sharedCache.size() };
+ }
+
+ /**
+ * Reset statistics and clear all caches
+ */
+ public void reset() {
+ timeManipulatingURLs = 0L;
+ timeSpentLoading = 0L;
+ classesLoadedCount = 0;
+ cacheHitsLocal = 0;
+ cacheHitsShared = 0;
+ missSharedEvicted = 0;
+ missLocalEvicted = 0;
+ misses = 0;
+ clear();
+ }
+
+ public JavaClass loadClass(Class clazz) throws ClassNotFoundException {
+ return loadClass(clazz.getName());
+ }
+
+ /** Clear all entries from the local cache */
+ public void clear() {
+ if (useSharedCache)
+ sharedCache.clear();
+ else
+ localCache.clear();
+ }
+
+}
* Responsible for loading (class) files from the CLASSPATH. Inspired by
* sun.tools.ClassPath.
*
- * @version $Id: ClassPath.java,v 1.4 2008/05/28 23:52:53 aclement Exp $
+ * @version $Id: ClassPath.java,v 1.5 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
*/
public class ClassPath implements Serializable {
public ClassPath(String class_path) {
this.class_path = class_path;
- ArrayList vec = new ArrayList();
+ ArrayList<PathEntry> vec = new ArrayList<PathEntry>();
for(StringTokenizer tok=new StringTokenizer(class_path,
System.getProperty("path.separator"));
return false;
}
- private static final void getPathComponents(String path, ArrayList list) {
+ private static final void getPathComponents(String path, ArrayList<String> list) {
if(path != null) {
StringTokenizer tok = new StringTokenizer(path, File.pathSeparator);
String boot_path = System.getProperty("sun.boot.class.path");
String ext_path = System.getProperty("java.ext.dirs");
- ArrayList list = new ArrayList();
+ ArrayList<String> list = new ArrayList<String>();
getPathComponents(class_path, list);
getPathComponents(boot_path, list);
- ArrayList dirs = new ArrayList();
+ ArrayList<String> dirs = new ArrayList<String>();
getPathComponents(ext_path, dirs);
- for(Iterator e = dirs.iterator(); e.hasNext(); ) {
- File ext_dir = new File((String)e.next());
+ for(Iterator<String> e = dirs.iterator(); e.hasNext(); ) {
+ File ext_dir = new File(e.next());
String[] extensions = ext_dir.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
name = name.toLowerCase();
StringBuffer buf = new StringBuffer();
- for(Iterator e = list.iterator(); e.hasNext(); ) {
- buf.append((String)e.next());
+ for(Iterator<String> e = list.iterator(); e.hasNext(); ) {
+ buf.append(e.next());
if(e.hasNext())
buf.append(File.pathSeparatorChar);
* Utility class implementing a (typesafe) queue of JavaClass
* objects.
*
- * @version $Id: ClassQueue.java,v 1.3 2008/05/28 23:52:53 aclement Exp $
+ * @version $Id: ClassQueue.java,v 1.4 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
* @see ClassVector
*/
public class ClassQueue implements java.io.Serializable {
- protected LinkedList vec = new LinkedList();
+ protected LinkedList<JavaClass> vec = new LinkedList<JavaClass>();
public void enqueue(JavaClass clazz) { vec.addLast(clazz); }
public JavaClass dequeue() {
- return (JavaClass)vec.removeFirst();
+ return vec.removeFirst();
}
public boolean empty() { return vec.isEmpty(); }
* Utility class implementing a (typesafe) collection of JavaClass
* objects. Contains the most important methods of a Vector.
*
- * @version $Id: ClassVector.java,v 1.3 2008/05/28 23:52:53 aclement Exp $
+ * @version $Id: ClassVector.java,v 1.4 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
* @see ClassQueue
*/
public class ClassVector implements java.io.Serializable {
- protected ArrayList vec = new ArrayList();
+ protected ArrayList<JavaClass> vec = new ArrayList<JavaClass>();
public void addElement(JavaClass clazz) { vec.add(clazz); }
- public JavaClass elementAt(int index) { return (JavaClass)vec.get(index); }
+ public JavaClass elementAt(int index) { return vec.get(index); }
public void removeElementAt(int index) { vec.remove(index); }
public JavaClass[] toArray() {
*
* @see org.aspectj.apache.bcel.Repository
*
- * @version $Id: NonCachingClassLoaderRepository.java,v 1.5 2009/09/04 18:42:08 aclement Exp $
+ * @version $Id: NonCachingClassLoaderRepository.java,v 1.6 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
* @author David Dixon-Peugh
*
private static java.lang.ClassLoader bootClassLoader = null;
private final ClassLoaderReference loaderRef;
- private final Map loadedClasses = new SoftHashMap(); // CLASSNAME X JAVACLASS
+ private final Map<String, JavaClass> loadedClasses = new SoftHashMap(); // CLASSNAME X JAVACLASS
public static class SoftHashMap extends AbstractMap {
- private Map map;
+ private Map<Object, SpecialValue> map;
private ReferenceQueue rq = new ReferenceQueue();
- public SoftHashMap(Map map) {
+ public SoftHashMap(Map<Object, SpecialValue> map) {
this.map = map;
}
}
}
+ @Override
public Object get(Object key) {
- SpecialValue value = (SpecialValue) map.get(key);
+ SpecialValue value = map.get(key);
if (value == null)
return null;
if (value.get() == null) {
}
}
+ @Override
public Object put(Object k, Object v) {
processQueue();
return map.put(k, new SpecialValue(k, v));
}
+ @Override
public Set entrySet() {
return map.entrySet();
}
+ @Override
public void clear() {
processQueue();
- Set keys = map.keySet();
- for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
+ Set<Object> keys = map.keySet();
+ for (Iterator<Object> iterator = keys.iterator(); iterator.hasNext();) {
Object name = iterator.next();
map.remove(name);
}
}
+ @Override
public int size() {
processQueue();
return map.size();
}
+ @Override
public Object remove(Object k) {
processQueue();
- SpecialValue value = (SpecialValue) map.remove(k);
+ SpecialValue value = map.remove(k);
if (value == null)
return null;
if (value.get() != null) {
public JavaClass findClass(String className) {
synchronized (loadedClasses) {
if (loadedClasses.containsKey(className)) {
- return (JavaClass) loadedClasses.get(className);
+ return loadedClasses.get(className);
} else {
return null;
}
import org.aspectj.apache.bcel.classfile.JavaClass;
/**
- * Abstract definition of a class repository. Instances may be used
- * to load classes from different sources and may be used in the
+ * Abstract definition of a class repository. Instances may be used to load classes from different sources and may be used in the
* Repository.setRepository method.
- *
+ *
* @see org.aspectj.apache.bcel.Repository
- * @version $Id: Repository.java,v 1.4 2008/08/28 00:01:38 aclement Exp $
+ * @version $Id: Repository.java,v 1.5 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
* @author David Dixon-Peugh
*/
public interface Repository {
- /**
- * Store the provided class under "clazz.getClassName()"
- */
- public void storeClass(JavaClass clazz);
-
- /**
- * Remove class from repository
- */
- public void removeClass(JavaClass clazz);
-
- /**
- * Find the class with the name provided, if the class
- * isn't there, return NULL.
- */
- public JavaClass findClass(String className);
+ /**
+ * Store the provided class under "clazz.getClassName()"
+ */
+ public void storeClass(JavaClass clazz);
- /**
- * Find the class with the name provided, if the class
- * isn't there, make an attempt to load it.
- */
- public JavaClass loadClass(String className)
- throws java.lang.ClassNotFoundException;
+ /**
+ * Remove class from repository
+ */
+ public void removeClass(JavaClass clazz);
- /**
- * Find the JavaClass instance for the given run-time class object
- */
- public JavaClass loadClass(Class clazz)
- throws java.lang.ClassNotFoundException;
-
- /** Clear all entries from cache.
- */
- public void clear();
-}
+ /**
+ * Find the class with the name provided, if the class isn't there, return NULL.
+ */
+ public JavaClass findClass(String className);
+ /**
+ * Find the class with the name provided, if the class isn't there, make an attempt to load it.
+ */
+ public JavaClass loadClass(String className) throws java.lang.ClassNotFoundException;
+ /**
+ * Find the JavaClass instance for the given run-time class object
+ */
+ public JavaClass loadClass(Class clazz) throws java.lang.ClassNotFoundException;
+ /**
+ * Clear all entries from cache.
+ */
+ public void clear();
+}
import org.aspectj.apache.bcel.classfile.JavaClass;
/**
- * This repository is used in situations where a Class is created
- * outside the realm of a ClassLoader. Classes are loaded from
- * the file systems using the paths specified in the given
- * class path. By default, this is the value returned by
- * ClassPath.getClassPath().
- * <br>
- * It is designed to be used as a singleton, however it
- * can also be used with custom classpaths.
- *
-/**
- * Abstract definition of a class repository. Instances may be used
- * to load classes from different sources and may be used in the
- * Repository.setRepository method.
- *
+ * This repository is used in situations where a Class is created outside the realm of a ClassLoader. Classes are loaded from the
+ * file systems using the paths specified in the given class path. By default, this is the value returned by
+ * ClassPath.getClassPath(). <br>
+ * It is designed to be used as a singleton, however it can also be used with custom classpaths.
+ *
+ * /** Abstract definition of a class repository. Instances may be used to load classes from different sources and may be used in
+ * the Repository.setRepository method.
+ *
* @see org.aspectj.apache.bcel.Repository
- *
- * @version $Id: SyntheticRepository.java,v 1.7 2008/05/28 23:52:53 aclement Exp $
+ *
+ * @version $Id: SyntheticRepository.java,v 1.8 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
* @author David Dixon-Peugh
*/
public class SyntheticRepository implements Repository {
- private static final String DEFAULT_PATH = ClassPath.getClassPath();
-
- private static HashMap _instances = new HashMap(); // CLASSPATH X REPOSITORY
-
- private ClassPath _path = null;
- private WeakHashMap _loadedClasses = new WeakHashMap(); // CLASSNAME X JAVACLASS
-
- private SyntheticRepository(ClassPath path) {
- _path = path;
- }
-
- public static SyntheticRepository getInstance() {
- return getInstance(ClassPath.getSystemClassPath());
- }
-
- public static SyntheticRepository getInstance(ClassPath classPath) {
- SyntheticRepository rep = (SyntheticRepository)_instances.get(classPath);
-
- if(rep == null) {
- rep = new SyntheticRepository(classPath);
- _instances.put(classPath, rep);
- }
-
- return rep;
- }
-
- /**
- * Store a new JavaClass instance into this Repository.
- */
- public void storeClass(JavaClass clazz) {
- _loadedClasses.put(clazz.getClassName(), clazz);
- clazz.setRepository(this);
- }
-
- /**
- * Remove class from repository
- */
- public void removeClass(JavaClass clazz) {
- _loadedClasses.remove(clazz.getClassName());
- }
-
- /**
- * Find an already defined (cached) JavaClass object by name.
- */
- public JavaClass findClass(String className) {
- return (JavaClass)_loadedClasses.get(className);
- }
-
- /**
- * Load a JavaClass object for the given class name using
- * the CLASSPATH environment variable.
- */
- public JavaClass loadClass(String className)
- throws ClassNotFoundException
- {
- if(className == null || className.equals("")) {
- throw new IllegalArgumentException("Invalid class name " + className);
- }
-
- className = className.replace('/', '.'); // Just in case, canonical form
-
- try {
- return loadClass(_path.getInputStream(className), className);
- } catch(IOException e) {
- throw new ClassNotFoundException("Exception while looking for class " +
- className + ": " + e.toString());
- }
- }
-
- /**
- * Try to find class source via getResourceAsStream().
- * @see Class
- * @return JavaClass object for given runtime class
- */
- public JavaClass loadClass(Class clazz) throws ClassNotFoundException {
- String className = clazz.getName();
- String name = className;
- int i = name.lastIndexOf('.');
-
- if(i > 0) {
- name = name.substring(i + 1);
- }
-
- return loadClass(clazz.getResourceAsStream(name + ".class"), className);
- }
-
- private JavaClass loadClass(InputStream is, String className)
- throws ClassNotFoundException
- {
- JavaClass clazz = findClass(className);
-
- if(clazz != null) {
- return clazz;
- }
-
- try {
- if(is != null) {
- ClassParser parser = new ClassParser(is, className);
- clazz = parser.parse();
-
- storeClass(clazz);
-
- return clazz;
- }
- } catch(IOException e) {
- throw new ClassNotFoundException("Exception while looking for class " +
- className + ": " + e.toString());
- }
-
- throw new ClassNotFoundException("SyntheticRepository could not load " +
- className);
- }
-
- /** Clear all entries from cache.
- */
- public void clear() {
- _loadedClasses.clear();
- }
+ private static final String DEFAULT_PATH = ClassPath.getClassPath();
+
+ private static HashMap<ClassPath, SyntheticRepository> _instances = new HashMap<ClassPath, SyntheticRepository>(); // CLASSPATH
+ // X
+ // REPOSITORY
+
+ private ClassPath _path = null;
+ private WeakHashMap<String, JavaClass> _loadedClasses = new WeakHashMap<String, JavaClass>(); // CLASSNAME X JAVACLASS
+
+ private SyntheticRepository(ClassPath path) {
+ _path = path;
+ }
+
+ public static SyntheticRepository getInstance() {
+ return getInstance(ClassPath.getSystemClassPath());
+ }
+
+ public static SyntheticRepository getInstance(ClassPath classPath) {
+ SyntheticRepository rep = _instances.get(classPath);
+
+ if (rep == null) {
+ rep = new SyntheticRepository(classPath);
+ _instances.put(classPath, rep);
+ }
+
+ return rep;
+ }
+
+ /**
+ * Store a new JavaClass instance into this Repository.
+ */
+ public void storeClass(JavaClass clazz) {
+ _loadedClasses.put(clazz.getClassName(), clazz);
+ clazz.setRepository(this);
+ }
+
+ /**
+ * Remove class from repository
+ */
+ public void removeClass(JavaClass clazz) {
+ _loadedClasses.remove(clazz.getClassName());
+ }
+
+ /**
+ * Find an already defined (cached) JavaClass object by name.
+ */
+ public JavaClass findClass(String className) {
+ return _loadedClasses.get(className);
+ }
+
+ /**
+ * Load a JavaClass object for the given class name using the CLASSPATH environment variable.
+ */
+ public JavaClass loadClass(String className) throws ClassNotFoundException {
+ if (className == null || className.equals("")) {
+ throw new IllegalArgumentException("Invalid class name " + className);
+ }
+
+ className = className.replace('/', '.'); // Just in case, canonical form
+
+ try {
+ return loadClass(_path.getInputStream(className), className);
+ } catch (IOException e) {
+ throw new ClassNotFoundException("Exception while looking for class " + className + ": " + e.toString());
+ }
+ }
+
+ /**
+ * Try to find class source via getResourceAsStream().
+ *
+ * @see Class
+ * @return JavaClass object for given runtime class
+ */
+ public JavaClass loadClass(Class clazz) throws ClassNotFoundException {
+ String className = clazz.getName();
+ String name = className;
+ int i = name.lastIndexOf('.');
+
+ if (i > 0) {
+ name = name.substring(i + 1);
+ }
+
+ return loadClass(clazz.getResourceAsStream(name + ".class"), className);
+ }
+
+ private JavaClass loadClass(InputStream is, String className) throws ClassNotFoundException {
+ JavaClass clazz = findClass(className);
+
+ if (clazz != null) {
+ return clazz;
+ }
+
+ try {
+ if (is != null) {
+ ClassParser parser = new ClassParser(is, className);
+ clazz = parser.parse();
+
+ storeClass(clazz);
+
+ return clazz;
+ }
+ } catch (IOException e) {
+ throw new ClassNotFoundException("Exception while looking for class " + className + ": " + e.toString());
+ }
+
+ throw new ClassNotFoundException("SyntheticRepository could not load " + className);
+ }
+
+ /**
+ * Clear all entries from cache.
+ */
+ public void clear() {
+ _loadedClasses.clear();
+ }
}
ObjectType t = new ObjectType("SimpleAnnotation");
- List elements = new ArrayList();
+ List<ElementNameValuePairGen> elements = new ArrayList<ElementNameValuePairGen>();
elements.add(nvGen);
// Build an annotation of type 'SimpleAnnotation' with 'id=4' as the only value :)
ObjectType t = new ObjectType("SimpleAnnotation");
- List elements = new ArrayList();
+ List<ElementNameValuePairGen> elements = new ArrayList<ElementNameValuePairGen>();
elements.add(nvGen);
// Build a RV annotation of type 'SimpleAnnotation' with 'id=4' as the only value :)
AnnotationGen a = new AnnotationGen(t,elements,true,cp);
- Vector v = new Vector();
+ Vector<AnnotationGen> v = new Vector<AnnotationGen>();
v.add(a);
Attribute[] attributes = Utility.getAnnotationAttributes(cp, v);
boolean foundRV = false;
// Build a RIV annotation of type 'SimpleAnnotation' with 'id=4' as the only value :)
AnnotationGen a2 = new AnnotationGen(t,elements,false,cp);
- Vector v2 = new Vector();
+ Vector<AnnotationGen> v2 = new Vector<AnnotationGen>();
v2.add(a2);
Attribute[] attributes2 = Utility.getAnnotationAttributes(cp, v2);
boolean foundRIV = false;
private void checkSerialize(AnnotationGen a,ConstantPool cpg) {
try {
String beforeName = a.getTypeName();
- List beforeValues = a.getValues();
+ List<ElementNameValuePairGen> beforeValues = a.getValues();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
a.dump(dos);
dis.close();
String afterName = annAfter.getTypeName();
- List afterValues = annAfter.getValues();
+ List<ElementNameValuePairGen> afterValues = annAfter.getValues();
if (!beforeName.equals(afterName)) {
fail("Deserialization failed: before type='"+beforeName+"' after type='"+afterName+"'");
fail("Different numbers of element name value pairs?? "+a.getValues().size()+"!="+annAfter.getValues().size());
}
for (int i=0;i<a.getValues().size();i++) {
- ElementNameValuePairGen beforeElement = (ElementNameValuePairGen) a.getValues().get(i);
- ElementNameValuePairGen afterElement = (ElementNameValuePairGen) annAfter.getValues().get(i);
+ ElementNameValuePairGen beforeElement = a.getValues().get(i);
+ ElementNameValuePairGen afterElement = annAfter.getValues().get(i);
if (!beforeElement.getNameString().equals(afterElement.getNameString())) {
fail("Different names?? "+beforeElement.getNameString()+"!="+afterElement.getNameString());
}
protected Attribute[] findAttribute(String name, JavaClass clazz) {
Attribute[] all = clazz.getAttributes();
- List chosenAttrsList = new ArrayList();
+ List<Attribute> chosenAttrsList = new ArrayList<Attribute>();
for (int i = 0; i < all.length; i++) {
if (verbose) System.err.println("Attribute: "+all[i].getName());
if (all[i].getName().equals(name)) chosenAttrsList.add(all[i]);
}
- return (Attribute[])chosenAttrsList.toArray(new Attribute[]{});
+ return chosenAttrsList.toArray(new Attribute[]{});
}
protected Attribute findAttribute(String name, Attribute[] all) {
- List chosenAttrsList = new ArrayList();
+ List<Attribute> chosenAttrsList = new ArrayList<Attribute>();
for (int i = 0; i < all.length; i++) {
if (verbose) System.err.println("Attribute: "+all[i].getName());
if (all[i].getName().equals(name)) chosenAttrsList.add(all[i]);
}
assertTrue("Should be one match: "+chosenAttrsList.size(),chosenAttrsList.size()==1);
- return (Attribute)chosenAttrsList.get(0);
+ return chosenAttrsList.get(0);
}
SimpleElementValueGen evg = new SimpleElementValueGen(ElementValueGen.STRING,cp,aFruit);
ElementNameValuePairGen nvGen = new ElementNameValuePairGen("fruit",evg,cp);
ObjectType t = new ObjectType("SimpleStringAnnotation");
- List elements = new ArrayList();
+ List<ElementNameValuePairGen> elements = new ArrayList<ElementNameValuePairGen>();
elements.add(nvGen);
return new AnnotationGen(t,elements,visibility,cp);
}
assertTrue("Expected annotation to have name "+name+" but it had name "+a.getTypeName(),
a.getTypeName().equals(name));
assertTrue("Expected annotation to have one element but it had "+a.getValues().size(),a.getValues().size()==1);
- ElementNameValuePairGen envp = (ElementNameValuePairGen)a.getValues().get(0);
+ ElementNameValuePairGen envp = a.getValues().get(0);
assertTrue("Expected element name "+elementname+" but was "+envp.getNameString(),
elementname.equals(envp.getNameString()));
assertTrue("Expected element value "+elementvalue+" but was "+envp.getValue().stringifyValue(),
// helper methods
public void checkValue(AnnotationGen a,String name,String tostring) {
- for (Iterator i = a.getValues().iterator(); i.hasNext();) {
- ElementNameValuePairGen element = (ElementNameValuePairGen) i.next();
+ for (Iterator<ElementNameValuePairGen> i = a.getValues().iterator(); i.hasNext();) {
+ ElementNameValuePairGen element = i.next();
if (element.getNameString().equals(name)) {
if (!element.getValue().stringifyValue().equals(tostring)) {
fail("Expected element "+name+" to have value "+tostring+" but it had value "+element.getValue().stringifyValue());
as[0].getTypeName().equals("SimpleAnnotation"));
assertTrue("Name of annotation 2 should be SimpleAnnotation but it is "+as[1].getTypeName(),
as[1].getTypeName().equals("SimpleAnnotation"));
- List vals = as[0].getValues();
- ElementNameValuePairGen nvp = (ElementNameValuePairGen) vals.get(0);
+ List<ElementNameValuePairGen> vals = as[0].getValues();
+ ElementNameValuePairGen nvp = vals.get(0);
assertTrue("Name of element in SimpleAnnotation should be 'id' but it is "+
nvp.getNameString(),nvp.getNameString().equals("id"));
ElementValueGen ev = nvp.getValue();
annotations.length==1);
AnnotationGen a = annotations[0];
assertTrue("That annotation should only have one value but has "+a.getValues().size(),a.getValues().size()==1);
- ElementNameValuePairGen nvp = (ElementNameValuePairGen)a.getValues().get(0);
+ ElementNameValuePairGen nvp = a.getValues().get(0);
ElementValueGen value = (ElementValueGen)nvp.getValue();
assertTrue("Value should be ArrayElementValueGen but is "+value,value instanceof ArrayElementValueGen);
ArrayElementValueGen arrayValue = (ArrayElementValueGen)value;
AnnotationGen[] annotations = cgen.getAnnotations();
assertTrue("Expected one annotation but found "+annotations.length,
annotations.length==1);
- List l = annotations[0].getValues();
+ List<ElementNameValuePairGen> l = annotations[0].getValues();
boolean found = false;
- for (Iterator iter = l.iterator(); iter.hasNext();) {
- ElementNameValuePairGen element = (ElementNameValuePairGen) iter.next();
+ for (Iterator<ElementNameValuePairGen> iter = l.iterator(); iter.hasNext();) {
+ ElementNameValuePairGen element = iter.next();
if (element.getNameString().equals("dval")) {
if (((SimpleElementValueGen)element.getValue()).stringifyValue().equals("33.4"))
found = true;
ObjectType t = new ObjectType("SimpleAnnotation");
- List elements = new ArrayList();
+ List<ElementNameValuePairGen> elements = new ArrayList<ElementNameValuePairGen>();
elements.add(nvGen);
AnnotationGen a = new AnnotationGen(t, elements,true, cp);
SimpleElementValueGen evg = new SimpleElementValueGen(ElementValueGen.STRING,cp,aFruit);
ElementNameValuePairGen nvGen = new ElementNameValuePairGen("fruit",evg,cp);
ObjectType t = new ObjectType("SimpleStringAnnotation");
- List elements = new ArrayList();
+ List<ElementNameValuePairGen> elements = new ArrayList<ElementNameValuePairGen>();
elements.add(nvGen);
return new AnnotationGen(t,elements,true,cp);
}
ArrayElementValueGen array = new ArrayElementValueGen(cp);
array.addElement(new AnnotationElementValueGen(a,cp));
ElementNameValuePairGen nvp = new ElementNameValuePairGen("value",array,cp);
- List elements = new ArrayList();
+ List<ElementNameValuePairGen> elements = new ArrayList<ElementNameValuePairGen>();
elements.add(nvp);
return new AnnotationGen(new ObjectType("CombinedAnnotation"),elements,true,cp);
}
ObjectType t = new ObjectType("SimpleAnnotation");
- List elements = new ArrayList();
+ List<ElementNameValuePairGen> elements = new ArrayList<ElementNameValuePairGen>();
elements.add(nvGen);
AnnotationGen a = new AnnotationGen(t, elements,false, cp);
* @return Array of argument types
*/
public static final String[] methodSignatureArgumentTypes(String signature,boolean chopit) throws ClassFormatException {
- ArrayList vec = new ArrayList();
+ ArrayList<String> vec = new ArrayList<String>();
int index;
String[] types;
assertTrue("Expected annotation to have name "+name+" but it had name "+a.getTypeName(),
a.getTypeName().equals(name));
assertTrue("Expected annotation to have one element but it had "+a.getValues().size(),a.getValues().size()==1);
- ElementNameValuePairGen envp = (ElementNameValuePairGen)a.getValues().get(0);
+ ElementNameValuePairGen envp = a.getValues().get(0);
assertTrue("Expected element name "+elementname+" but was "+envp.getNameString(),
elementname.equals(envp.getNameString()));
assertTrue("Expected element value "+elementvalue+" but was "+envp.getValue().stringifyValue(),
// helper methods
public void checkValue(AnnotationGen a,String name,String tostring) {
- for (Iterator i = a.getValues().iterator(); i.hasNext();) {
- ElementNameValuePairGen element = (ElementNameValuePairGen) i.next();
+ for (Iterator<ElementNameValuePairGen> i = a.getValues().iterator(); i.hasNext();) {
+ ElementNameValuePairGen element = i.next();
if (element.getNameString().equals(name)) {
if (!element.getValue().stringifyValue().equals(tostring)) {
fail("Expected element "+name+" to have value "+tostring+" but it had value "+element.getValue().stringifyValue());
}
public void testConcurrency() throws ClassNotFoundException, InterruptedException {
- List loaders = new ArrayList();
+ List<DoneChecker> loaders = new ArrayList<DoneChecker>();
int i1 = 1000;
for (int i = 0; i < i1; i++) {
DoneChecker loader = new Loader();
}
for (int i = 0; i < i1 * 2; i++) {
- DoneChecker loader = (DoneChecker) loaders.get(i);
+ DoneChecker loader = loaders.get(i);
while (!loader.isDone()) {
Thread.sleep(10);
}
import java.util.List;
import org.aspectj.apache.bcel.Constants;
+import org.aspectj.apache.bcel.classfile.Attribute;
import org.aspectj.apache.bcel.classfile.ConstantPool;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
// attributes vanish !
clg = new ClassGen(jc2);
mg = new MethodGen(m,clg.getClassName(),clg.getConstantPool());
- List as = mg.getAttributes();
+ List<Attribute> as = mg.getAttributes();
assertTrue("Should be 2 (RIPA and RVPA) but there are "+mg.getAttributes().size(),mg.getAttributes().size()==2);
List l = mg.getAnnotationsOnParameter(0);
assertTrue("Should be 2 annotations on first parameter but there is only "+l.size()+":"+l.toString(),
ObjectType t = new ObjectType("SimpleAnnotation");
- List elements = new ArrayList();
+ List<ElementNameValuePairGen> elements = new ArrayList<ElementNameValuePairGen>();
elements.add(nvGen);
AnnotationGen a = new AnnotationGen(t, elements,true, cp);
ArrayElementValueGen array = new ArrayElementValueGen(cp);
array.addElement(new AnnotationElementValueGen(a,cp));
ElementNameValuePairGen nvp = new ElementNameValuePairGen("value",array,cp);
- List elements = new ArrayList();
+ List<ElementNameValuePairGen> elements = new ArrayList<ElementNameValuePairGen>();
elements.add(nvp);
return new AnnotationGen(new ObjectType("CombinedAnnotation"),elements,true,cp);
}
ObjectType t = new ObjectType("SimpleAnnotation");
- List elements = new ArrayList();
+ List<ElementNameValuePairGen> elements = new ArrayList<ElementNameValuePairGen>();
elements.add(nvGen);
AnnotationGen a = new AnnotationGen(t, elements,false, cp);
ConstantPool pool = clazz.getConstantPool();
Attribute[] rvaAttr = findAttribute("RuntimeVisibleAnnotations",clazz);
RuntimeVisibleAnnotations rva = (RuntimeVisibleAnnotations) rvaAttr[0];
- List anns = rva.getAnnotations();
+ List<AnnotationGen> anns = rva.getAnnotations();
assertTrue("Should be one annotation but found "+anns.size(),
anns.size()==1);
- AnnotationGen ann = (AnnotationGen) anns.get(0);
+ AnnotationGen ann = anns.get(0);
assertTrue("Should be called 'SimpleAnnotation' but was called "+ann.getTypeName(),
ann.getTypeName().equals("SimpleAnnotation"));
- List l = ann.getValues();
+ List<ElementNameValuePairGen> l = ann.getValues();
assertTrue("Should be one value for annotation 'SimpleAnnotation' but found "+l.size(),
l.size()==1);
- ElementNameValuePairGen envp = (ElementNameValuePairGen)l.get(0);
+ ElementNameValuePairGen envp = l.get(0);
assertTrue("Name of element in SimpleAnnotation should be 'id' but it is "+envp.getNameString(),
envp.getNameString().equals("id"));
SimpleElementValueGen evalue = (SimpleElementValueGen)envp.getValue();
AnnotationGen ann = anns[0];
assertTrue("should be called 'AnnotationStringElement' but was called "+ann.getTypeName(),
ann.getTypeName().equals("AnnotationStringElement"));
- List l = ann.getValues();
+ List<ElementNameValuePairGen> l = ann.getValues();
assertTrue("Should be one value but there were "+l.size(),l.size()==1);
- ElementNameValuePairGen nvp = (ElementNameValuePairGen)l.get(0);
+ ElementNameValuePairGen nvp = l.get(0);
assertTrue("Name of element should be 'stringval' but was "+nvp.getNameString(),
nvp.getNameString().equals("stringval"));
SimpleElementValueGen ev = (SimpleElementValueGen)nvp.getValue();
AnnotationGen ann = anns[0];
assertTrue("Should be called 'ComplexAnnotation' but was called "+ann.getTypeName(),
ann.getTypeName().equals("ComplexAnnotation"));
- List l = ann.getValues();
+ List<ElementNameValuePairGen> l = ann.getValues();
assertTrue("Should be eight values for annotation 'ComplexAnnotation' but found "+l.size(),
l.size()==8);
- List names = RuntimeVisibleAnnotationAttributeTest.getListOfAnnotationNames(ann);
+ List<String> names = RuntimeVisibleAnnotationAttributeTest.getListOfAnnotationNames(ann);
assertTrue("Cant find expected element ",names.contains("ival"));
assertTrue("Cant find expected element ",names.contains("dval"));
assertTrue("Cant find expected element ",names.contains("zval"));
}
private void checkValue(AnnotationGen a,String name,String tostring) {
- for (Iterator i = a.getValues().iterator(); i.hasNext();) {
- ElementNameValuePairGen element = (ElementNameValuePairGen) i.next();
+ for (Iterator<ElementNameValuePairGen> i = a.getValues().iterator(); i.hasNext();) {
+ ElementNameValuePairGen element = i.next();
if (element.getNameString().equals(name)) {
if (!element.getValue().stringifyValue().equals(tostring)) {
fail("Expected element "+name+" to have value "+tostring+" but it had value "+element.getValue().stringifyValue());
AnnotationGen ann = anns[0];
assertTrue("should be called 'AnnotationClassElement' but was called "+ann.getTypeName(),
ann.getTypeName().equals("AnnotationClassElement"));
- List l = ann.getValues();
+ List<ElementNameValuePairGen> l = ann.getValues();
assertTrue("Should be one value but there were "+l.size(),l.size()==1);
- ElementNameValuePairGen nvp = (ElementNameValuePairGen)l.get(0);
+ ElementNameValuePairGen nvp = l.get(0);
assertTrue("Name of element should be 'clz' but was "+nvp.getNameString(),
nvp.getNameString().equals("clz"));
ClassElementValueGen ev = (ClassElementValueGen)nvp.getValue();
AnnotationGen ann = anns[0];
assertTrue("should be called 'AnnotationEnumElement' but was called "+ann.getTypeName(),
ann.getTypeName().equals("AnnotationEnumElement"));
- List l = ann.getValues();
+ List<ElementNameValuePairGen> l = ann.getValues();
assertTrue("Should be one value but there were "+l.size(),l.size()==1);
- ElementNameValuePairGen nvp = (ElementNameValuePairGen)l.get(0);
+ ElementNameValuePairGen nvp = l.get(0);
assertTrue("Name of element should be 'enumval' but was "+nvp.getNameString(),
nvp.getNameString().equals("enumval"));
ElementValueGen ev = nvp.getValue();
private void checkCombinedAnnotation(AnnotationGen ann) {
assertTrue("should be called 'CombinedAnnotation' but was called "+ann.getTypeName(),
ann.getTypeName().equals("CombinedAnnotation"));
- List l = ann.getValues();
+ List<ElementNameValuePairGen> l = ann.getValues();
assertTrue("Should be one value but there were "+l.size(),l.size()==1);
- ElementNameValuePairGen nvp = (ElementNameValuePairGen)l.get(0);
+ ElementNameValuePairGen nvp = l.get(0);
assertTrue("Name of element should be 'value' but was "+nvp.getNameString(),
nvp.getNameString().equals("value"));
ElementValueGen ev = nvp.getValue();
AnnotationElementValueGen inner_ev = (AnnotationElementValueGen)evs[0];
AnnotationGen a = inner_ev.getAnnotation();
assertTrue("Should be SimpleAnnotation but is "+a.getTypeName(),a.getTypeName().equals("SimpleAnnotation"));
- List envps = a.getValues();
+ List<ElementNameValuePairGen> envps = a.getValues();
assertTrue("Should be one name value pair but found "+envps.size(),envps.size()==1);
- ElementNameValuePairGen envp = (ElementNameValuePairGen) envps.get(0);
+ ElementNameValuePairGen envp = envps.get(0);
assertTrue("Name should be 'id' but it is "+envp.getNameString(),envp.getNameString().equals("id"));
assertTrue("Value of 'id' should be 4 but it is "+envp.getValue().stringifyValue(),
envp.getValue().stringifyValue().equals("4"));
super.tearDown();
}
- public static List getListOfAnnotationNames(AnnotationGen a) {
- List l = a.getValues();
- List names = new ArrayList();
- for (Iterator i = l.iterator(); i.hasNext();) {
- ElementNameValuePairGen element = (ElementNameValuePairGen) i.next();
+ public static List<String> getListOfAnnotationNames(AnnotationGen a) {
+ List<ElementNameValuePairGen> l = a.getValues();
+ List<String> names = new ArrayList<String>();
+ for (Iterator<ElementNameValuePairGen> i = l.iterator(); i.hasNext();) {
+ ElementNameValuePairGen element = i.next();
names.add(element.getNameString());
}
return names;
assertTrue("Expected annotation to have name "+name+" but it had name "+a.getTypeName(),
a.getTypeName().equals(name));
assertTrue("Expected annotation to have one element but it had "+a.getValues().size(),a.getValues().size()==1);
- ElementNameValuePairGen envp = (ElementNameValuePairGen)a.getValues().get(0);
+ ElementNameValuePairGen envp = a.getValues().get(0);
assertTrue("Expected element name "+elementname+" but was "+envp.getNameString(),
elementname.equals(envp.getNameString()));
assertTrue("Expected element value "+elementvalue+" but was "+envp.getValue().stringifyValue(),
// helper methods
public void checkValue(AnnotationGen a,String name,String tostring) {
- for (Iterator i = a.getValues().iterator(); i.hasNext();) {
- ElementNameValuePairGen element = (ElementNameValuePairGen) i.next();
+ for (Iterator<ElementNameValuePairGen> i = a.getValues().iterator(); i.hasNext();) {
+ ElementNameValuePairGen element = i.next();
if (element.getNameString().equals(name)) {
if (!element.getValue().stringifyValue().equals(tostring)) {
fail("Expected element "+name+" to have value "+tostring+" but it had value "+element.getValue().stringifyValue());
// helper methods
public void checkValue(AnnotationGen a,String name,String tostring) {
- for (Iterator i = a.getValues().iterator(); i.hasNext();) {
- ElementNameValuePairGen element = (ElementNameValuePairGen) i.next();
+ for (Iterator<ElementNameValuePairGen> i = a.getValues().iterator(); i.hasNext();) {
+ ElementNameValuePairGen element = i.next();
if (element.getNameString().equals(name)) {
if (!element.getValue().stringifyValue().equals(tostring)) {
fail("Expected element "+name+" to have value "+tostring+" but it had value "+element.getValue().stringifyValue());
* class supplies the traversal strategy, other classes can make use
* of it.
*
- * @version $Id: DescendingVisitor.java,v 1.2 2008/05/28 23:53:00 aclement Exp $
+ * @version $Id: DescendingVisitor.java,v 1.3 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
*/
public class DescendingVisitor implements ClassVisitor {
private JavaClass clazz;
private ClassVisitor visitor;
- private Stack stack = new Stack();
+ private Stack<Object> stack = new Stack<Object>();
/** @return container of current entitity, i.e., predecessor during traversal
*/
* That means, if you really want a new verification run of a certain
* pass you must use a new instance of a given PassVerifier.
*
- * @version $Id: PassVerifier.java,v 1.2 2008/05/28 23:53:00 aclement Exp $
+ * @version $Id: PassVerifier.java,v 1.3 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="http://www.inf.fu-berlin.de/~ehaase"/>Enver Haase</A>
* @see org.aspectj.apache.bcel.verifier.Verifier
* @see #verify()
public abstract class PassVerifier{
/** The (warning) messages. */
- private ArrayList messages = new ArrayList(); //Type of elements: String
+ private ArrayList<String> messages = new ArrayList<String>(); //Type of elements: String
/** The VerificationResult cache. */
private VerificationResult verificationResult = null;
verify(); // create messages if not already done (cached!)
String[] ret = new String[messages.size()];
for (int i=0; i<messages.size(); i++){
- ret[i] = (String) messages.get(i);
+ ret[i] = messages.get(i);
}
return ret;
}
* A Verifier creates PassVerifier instances to perform the actual verification.
* Verifier instances are usually generated by the VerifierFactory.
*
- * @version $Id: Verifier.java,v 1.2 2008/05/28 23:53:01 aclement Exp $
+ * @version $Id: Verifier.java,v 1.3 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="http://www.inf.fu-berlin.de/~ehaase"/>Enver Haase</A>
* @see org.aspectj.apache.bcel.verifier.VerifierFactory
* @see org.aspectj.apache.bcel.verifier.PassVerifier
/** A Pass2Verifier for this Verifier instance. */
private Pass2Verifier p2v;
/** The Pass3aVerifiers for this Verifier instance. Key: Interned string specifying the method number. */
- private HashMap p3avs = new HashMap();
+ private HashMap<String, Pass3aVerifier> p3avs = new HashMap<String, Pass3aVerifier>();
/** The Pass3bVerifiers for this Verifier instance. Key: Interned string specifying the method number. */
- private HashMap p3bvs = new HashMap();
+ private HashMap<String, Pass3bVerifier> p3bvs = new HashMap<String, Pass3bVerifier>();
/** Returns the VerificationResult for the given pass. */
public VerificationResult doPass1(){
public VerificationResult doPass3a(int method_no){
String key = Integer.toString(method_no);
Pass3aVerifier p3av;
- p3av = (Pass3aVerifier) (p3avs.get(key));
+ p3av = (p3avs.get(key));
if (p3avs.get(key) == null){
p3av = new Pass3aVerifier(this, method_no);
p3avs.put(key, p3av);
public VerificationResult doPass3b(int method_no){
String key = Integer.toString(method_no);
Pass3bVerifier p3bv;
- p3bv = (Pass3bVerifier) (p3bvs.get(key));
+ p3bv = (p3bvs.get(key));
if (p3bvs.get(key) == null){
p3bv = new Pass3bVerifier(this, method_no);
p3bvs.put(key, p3bv);
messages.add("Pass 2: "+p2m[i]);
}
}
- Iterator p3as = p3avs.values().iterator();
+ Iterator<Pass3aVerifier> p3as = p3avs.values().iterator();
while (p3as.hasNext()){
- Pass3aVerifier pv = (Pass3aVerifier) p3as.next();
+ Pass3aVerifier pv = p3as.next();
String[] p3am = pv.getMessages();
int meth = pv.getMethodNo();
for (int i=0; i<p3am.length; i++){
"'): "+p3am[i]);
}
}
- Iterator p3bs = p3bvs.values().iterator();
+ Iterator<Pass3bVerifier> p3bs = p3bvs.values().iterator();
while (p3bs.hasNext()){
- Pass3bVerifier pv = (Pass3bVerifier) p3bs.next();
+ Pass3bVerifier pv = p3bs.next();
String[] p3bm = pv.getMessages();
int meth = pv.getMethodNo();
for (int i=0; i<p3bm.length; i++){
* operate on. That means, for every class (represented by a unique fully qualified
* class name) there is exactly one Verifier.
*
- * @version $Id: VerifierFactory.java,v 1.2 2008/05/28 23:53:00 aclement Exp $
+ * @version $Id: VerifierFactory.java,v 1.3 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="http://www.inf.fu-berlin.de/~ehaase"/>Enver Haase</A>
* @see org.aspectj.apache.bcel.verifier.Verifier
*/
/**
* The HashMap that holds the data about the already-constructed Verifier instances.
*/
- private static HashMap hashMap = new HashMap();
+ private static HashMap<String, Verifier> hashMap = new HashMap<String, Verifier>();
/**
* The VerifierFactoryObserver instances that observe the VerifierFactory.
*/
- private static Vector observers = new Vector();
+ private static Vector<VerifierFactoryObserver> observers = new Vector<VerifierFactoryObserver>();
/**
* The VerifierFactory is not instantiable.
public static Verifier getVerifier(String fully_qualified_classname){
// fully_qualified_classname = fully_qualified_classname;
- Verifier v = (Verifier) (hashMap.get(fully_qualified_classname));
+ Verifier v = (hashMap.get(fully_qualified_classname));
if (v==null){
v = new Verifier(fully_qualified_classname);
hashMap.put(fully_qualified_classname, v);
*/
private static void notify(String fully_qualified_classname){
// notify the observers
- Iterator i = observers.iterator();
+ Iterator<VerifierFactoryObserver> i = observers.iterator();
while (i.hasNext()){
- VerifierFactoryObserver vfo = (VerifierFactoryObserver) i.next();
+ VerifierFactoryObserver vfo = i.next();
vfo.update(fully_qualified_classname);
}
}
*/
public static Verifier[] getVerifiers(){
Verifier[] vs = new Verifier[hashMap.values().size()];
- return (Verifier[]) (hashMap.values().toArray(vs)); // Because vs is big enough, vs is used to store the values into and returned!
+ return (hashMap.values().toArray(vs)); // Because vs is big enough, vs is used to store the values into and returned!
}
/**
* <http://www.apache.org/>.
*/
import javax.swing.event.ListDataEvent;
+import javax.swing.event.ListDataListener;
/**
* This class implements an adapter; it implements both a Swing ListModel and
* a VerifierFactoryObserver.
*
- * @version $Id: VerifierFactoryListModel.java,v 1.2 2008/05/28 23:53:01 aclement Exp $
+ * @version $Id: VerifierFactoryListModel.java,v 1.3 2009/09/09 19:56:20 aclement Exp $
* @author Enver Haase
*/
public class VerifierFactoryListModel implements org.aspectj.apache.bcel.verifier.VerifierFactoryObserver, javax.swing.ListModel{
- private java.util.ArrayList listeners = new java.util.ArrayList();
+ private java.util.ArrayList<ListDataListener> listeners = new java.util.ArrayList<ListDataListener>();
- private java.util.TreeSet cache = new java.util.TreeSet();
+ private java.util.TreeSet<String> cache = new java.util.TreeSet<String>();
public VerifierFactoryListModel() {
VerifierFactory.attach(this);
for (int i=0; i<size; i++){
ListDataEvent e = new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, num_of_verifiers-1);
- ((javax.swing.event.ListDataListener) (listeners.get(i))).contentsChanged(e);
+ (listeners.get(i)).contentsChanged(e);
}
}
/**
* A small utility class representing a set of basic int values.
*
- * @version $Id: IntList.java,v 1.2 2008/05/28 23:52:53 aclement Exp $
+ * @version $Id: IntList.java,v 1.3 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="http://www.inf.fu-berlin.de/~ehaase"/>Enver Haase</A>
*/
public class IntList{
/** The int are stored as Integer objects here. */
- private ArrayList theList;
+ private ArrayList<Integer> theList;
/** This constructor creates an empty list. */
IntList(){
- theList = new ArrayList();
+ theList = new ArrayList<Integer>();
}
/** Adds an element to the list. */
void add(int i){
* a given slot (== index). This information
* often changes in course of byte code offsets.
*
- * @version $Id: LocalVariableInfo.java,v 1.2 2008/05/28 23:52:54 aclement Exp $
+ * @version $Id: LocalVariableInfo.java,v 1.3 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="http://www.inf.fu-berlin.de/~ehaase"/>Enver Haase</A>
*/
public class LocalVariableInfo{
/** The types database. KEY: String representing the offset integer. */
- private Hashtable types = new Hashtable();
+ private Hashtable<String, Type> types = new Hashtable<String, Type>();
/** The names database. KEY: String representing the offset integer. */
- private Hashtable names = new Hashtable();
+ private Hashtable<String, String> names = new Hashtable<String, String>();
/**
* Adds a name of a local variable and a certain slot to our 'names'
* variable slot at the given bytecode offset.
*/
public Type getType(int offset){
- return (Type) types.get(Integer.toString(offset));
+ return types.get(Integer.toString(offset));
}
/**
* Returns the name of the local variable that uses this local
* variable slot at the given bytecode offset.
*/
public String getName(int offset){
- return (String) (names.get(Integer.toString(offset)));
+ return (names.get(Integer.toString(offset)));
}
/**
* Adds some information about this local variable (slot).
* More detailed information is to be found at the do_verify()
* method's documentation.
*
- * @version $Id: Pass2Verifier.java,v 1.3 2008/08/28 00:02:14 aclement Exp $
+ * @version $Id: Pass2Verifier.java,v 1.4 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="http://www.inf.fu-berlin.de/~ehaase"/>Enver Haase</A>
* @see #do_verify()
*/
* @throws ClassConstraintException otherwise.
*/
private void every_class_has_an_accessible_superclass(){
- HashSet hs = new HashSet(); // save class names to detect circular inheritance
+ HashSet<String> hs = new HashSet<String>(); // save class names to detect circular inheritance
JavaClass jc = Repository.lookupClass(myOwner.getClassName());
int supidx = -1;
* @see #every_class_has_an_accessible_superclass()
*/
private void final_methods_are_not_overridden(){
- HashMap hashmap = new HashMap();
+ HashMap<String, String> hashmap = new HashMap<String, String>();
JavaClass jc = Repository.lookupClass(myOwner.getClassName());
int supidx = -1;
private Class CONST_Methodref;
private Class CONST_InterfaceMethodref;
*/
- private Class CONST_String;
- private Class CONST_Integer;
- private Class CONST_Float;
- private Class CONST_Long;
- private Class CONST_Double;
+ private Class<ConstantString> CONST_String;
+ private Class<ConstantInteger> CONST_Integer;
+ private Class<ConstantFloat> CONST_Float;
+ private Class<ConstantLong> CONST_Long;
+ private Class<ConstantDouble> CONST_Double;
private Class CONST_NameAndType;
private Class CONST_Utf8;
private final int cplen; // == cp.getLength() -- to save computing power.
private DescendingVisitor carrier;
- private HashSet field_names = new HashSet();
- private HashSet field_names_and_desc = new HashSet();
- private HashSet method_names_and_desc = new HashSet();
+ private HashSet<String> field_names = new HashSet<String>();
+ private HashSet<String> field_names_and_desc = new HashSet<String>();
+ private HashSet<String> method_names_and_desc = new HashSet<String>();
private CPESSC_Visitor(JavaClass _jc){
jc = _jc;
/**
* This class represents a control flow graph of a method.
*
- * @version $Id: ControlFlowGraph.java,v 1.3 2008/08/28 00:02:13 aclement Exp $
+ * @version $Id: ControlFlowGraph.java,v 1.4 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="http://www.inf.fu-berlin.de/~ehaase"/>Enver Haase</A>
*/
public class ControlFlowGraph {
/**
* The 'incoming' execution Frames.
*/
- private final HashMap inFrames; // key: the last-executed JSR
+ private final HashMap<InstructionContextImpl, Frame> inFrames; // key: the last-executed JSR
/**
* The 'outgoing' execution Frames.
*/
- private final HashMap outFrames; // key: the last-executed JSR
+ private final HashMap<InstructionContextImpl, Frame> outFrames; // key: the last-executed JSR
/**
* The 'execution predecessors' - a list of type InstructionContext of those instances that have been execute()d before in
* that order.
*/
- private ArrayList executionPredecessors = null; // Type: InstructionContext
+ private ArrayList<InstructionContext> executionPredecessors = null; // Type: InstructionContext
/**
* Creates an InstructionHandleImpl object from an InstructionHandle. Creation of one per InstructionHandle suffices. Don't
}
instruction = inst;
- inFrames = new java.util.HashMap();
- outFrames = new java.util.HashMap();
+ inFrames = new java.util.HashMap<InstructionContextImpl, Frame>();
+ outFrames = new java.util.HashMap<InstructionContextImpl, Frame>();
}
/* Satisfies InstructionContext.getTag(). */
/**
* Returns a clone of the "outgoing" frame situation with respect to the given ExecutionChain.
*/
- public Frame getOutFrame(ArrayList execChain) {
+ public Frame getOutFrame(ArrayList<InstructionContext> execChain) {
executionPredecessors = execChain;
Frame org;
InstructionContext jsr = lastExecutionJSR();
- org = (Frame) outFrames.get(jsr);
+ org = outFrames.get(jsr);
if (org == null) {
throw new AssertionViolatedException("outFrame not set! This:\n" + this + "\nExecutionChain: "
*
* @return true - if and only if the "outgoing" frame situation changed from the one before execute()ing.
*/
- public boolean execute(Frame inFrame, ArrayList execPreds, InstConstraintVisitor icv, ExecutionVisitor ev) {
+ public boolean execute(Frame inFrame, ArrayList<InstructionContext> execPreds, InstConstraintVisitor icv, ExecutionVisitor ev) {
- executionPredecessors = (ArrayList) execPreds.clone();
+ executionPredecessors = (ArrayList<InstructionContext>) execPreds.clone();
// sanity check
if (lastExecutionJSR() == null && subroutines.subroutineOf(getInstruction()) != subroutines.getTopLevel()) {
throw new AssertionViolatedException("Huh?! Am I '" + this + "' part of a subroutine or not?");
}
- Frame inF = (Frame) inFrames.get(lastExecutionJSR());
+ Frame inF = inFrames.get(lastExecutionJSR());
if (inF == null) {// no incoming frame was set, so set it.
inFrames.put(lastExecutionJSR(), inFrame);
inF = inFrame;
*/
private boolean mergeInFrames(Frame inFrame) {
// TODO: Can be performance-improved.
- Frame inF = (Frame) inFrames.get(lastExecutionJSR());
+ Frame inF = inFrames.get(lastExecutionJSR());
OperandStack oldstack = inF.getStack().getClone();
LocalVariables oldlocals = inF.getLocals().getClone();
try {
private final ExceptionHandlers exceptionhandlers;
/** All InstructionContext instances of this ControlFlowGraph. */
- private final Hashtable instructionContexts = new Hashtable(); // keys: InstructionHandle, values: InstructionContextImpl
+ private final Hashtable<InstructionHandle, InstructionContextImpl> instructionContexts = new Hashtable<InstructionHandle, InstructionContextImpl>(); // keys: InstructionHandle, values: InstructionContextImpl
/**
* A Control Flow Graph.
* Returns the InstructionContext of a given instruction.
*/
public InstructionContext contextOf(InstructionHandle inst) {
- InstructionContext ic = (InstructionContext) instructionContexts.get(inst);
+ InstructionContext ic = instructionContexts.get(inst);
if (ic == null) {
throw new AssertionViolatedException("InstructionContext requested for an InstructionHandle that's not known!");
}
*/
public InstructionContext[] getInstructionContexts() {
InstructionContext[] ret = new InstructionContext[instructionContexts.values().size()];
- return (InstructionContext[]) instructionContexts.values().toArray(ret);
+ return instructionContexts.values().toArray(ret);
}
/**
*/
import org.aspectj.apache.bcel.generic.*;
+
import java.util.HashSet;
import java.util.Hashtable;
/**
* This class allows easy access to ExceptionHandler objects.
*
- * @version $Id: ExceptionHandlers.java,v 1.2 2008/05/28 23:53:02 aclement Exp $
+ * @version $Id: ExceptionHandlers.java,v 1.3 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="http://www.inf.fu-berlin.de/~ehaase"/>Enver Haase</A>
*/
public class ExceptionHandlers{
* The ExceptionHandler instances.
* Key: InstructionHandle objects, Values: HashSet<ExceptionHandler> instances.
*/
- private Hashtable exceptionhandlers;
+ private Hashtable<InstructionHandle, HashSet<ExceptionHandler>> exceptionhandlers;
/**
* Constructor. Creates a new ExceptionHandlers instance.
*/
public ExceptionHandlers(MethodGen mg){
- exceptionhandlers = new Hashtable();
+ exceptionhandlers = new Hashtable<InstructionHandle, HashSet<ExceptionHandler>>();
CodeExceptionGen[] cegs = mg.getExceptionHandlers();
for (int i=0; i<cegs.length; i++){
ExceptionHandler eh = new ExceptionHandler(cegs[i].getCatchType(), cegs[i].getHandlerPC());
for (InstructionHandle ih=cegs[i].getStartPC(); ih != cegs[i].getEndPC().getNext(); ih=ih.getNext()){
- HashSet hs;
- hs = (HashSet) exceptionhandlers.get(ih);
+ HashSet<ExceptionHandler> hs;
+ hs = exceptionhandlers.get(ih);
if (hs == null){
- hs = new HashSet();
+ hs = new HashSet<ExceptionHandler>();
exceptionhandlers.put(ih, hs);
}
hs.add(eh);
* handlers that protect the instruction ih.
*/
public ExceptionHandler[] getExceptionHandlers(InstructionHandle ih){
- HashSet hs = (HashSet) exceptionhandlers.get(ih);
+ HashSet hs = exceptionhandlers.get(ih);
if (hs == null) return new ExceptionHandler[0];
else{
ExceptionHandler[] ret = new ExceptionHandler[hs.size()];
* to information like control flow successors and
* such.
*
- * @version $Id: InstructionContext.java,v 1.2 2008/05/28 23:53:03 aclement Exp $
+ * @version $Id: InstructionContext.java,v 1.3 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="http://www.inf.fu-berlin.de/~ehaase"/>Enver Haase</A>
*/
public interface InstructionContext{
* @return true - if and only if the "outgoing" frame situation
* changed from the one before execute()ing.
*/
- boolean execute(Frame inFrame, ArrayList executionPredecessors, InstConstraintVisitor icv, ExecutionVisitor ev);
+ boolean execute(Frame inFrame, ArrayList<InstructionContext> executionPredecessors, InstConstraintVisitor icv, ExecutionVisitor ev);
/**
* This method returns the outgoing execution frame situation;
*
* @see #execute(Frame, ArrayList, InstConstraintVisitor, ExecutionVisitor)
*/
- Frame getOutFrame(ArrayList executionPredecessors);
+ Frame getOutFrame(ArrayList<InstructionContext> executionPredecessors);
/**
* Returns the InstructionHandle this InstructionContext is wrapped around.
* [It's used an an operand stack substitute.]
* Elements of this stack are org.aspectj.apache.bcel.generic.Type objects.
*
- * @version $Id: OperandStack.java,v 1.2 2008/05/28 23:53:02 aclement Exp $
+ * @version $Id: OperandStack.java,v 1.3 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="http://www.inf.fu-berlin.de/~ehaase"/>Enver Haase</A>
*/
public class OperandStack{
/** We hold the stack information here. */
- private ArrayList stack = new ArrayList();
+ private ArrayList<Type> stack = new ArrayList<Type>();
/** The maximum number of stack slots this OperandStack instance may hold. */
private int maxStack;
*/
protected Object clone(){
OperandStack newstack = new OperandStack(this.maxStack);
- newstack.stack = (ArrayList) this.stack.clone();
+ newstack.stack = (ArrayList<Type>) this.stack.clone();
return newstack;
}
* Clears the stack.
*/
public void clear(){
- stack = new ArrayList();
+ stack = new ArrayList<Type>();
}
/**
* iff i==0 the top element is returned. The element is not popped off the stack!
*/
public Type peek(int i){
- return (Type) stack.get(size()-i-1);
+ return stack.get(size()-i-1);
}
/**
* Returns the element on top of the stack. The element is popped off the stack.
*/
public Type pop(){
- Type e = (Type) stack.remove(size()-1);
+ Type e = stack.remove(size()-1);
return e;
}
* More detailed information is to be found at the do_verify() method's
* documentation.
*
- * @version $Id: Pass3bVerifier.java,v 1.2 2008/05/28 23:53:03 aclement Exp $
+ * @version $Id: Pass3bVerifier.java,v 1.3 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="http://www.inf.fu-berlin.de/~ehaase"/>Enver Haase</A>
* @see #do_verify()
*/
* we have about its symbolic execution predecessors.
*/
private static final class InstructionContextQueue{
- private Vector ics = new Vector(); // Type: InstructionContext
- private Vector ecs = new Vector(); // Type: ArrayList (of InstructionContext)
- public void add(InstructionContext ic, ArrayList executionChain){
+ private Vector<InstructionContext> ics = new Vector<InstructionContext>(); // Type: InstructionContext
+ private Vector<ArrayList<InstructionContext>> ecs = new Vector<ArrayList<InstructionContext>>(); // Type: ArrayList (of InstructionContext)
+ public void add(InstructionContext ic, ArrayList<InstructionContext> executionChain){
ics.add(ic);
ecs.add(executionChain);
}
ecs.remove(i);
}
public InstructionContext getIC(int i){
- return (InstructionContext) ics.get(i);
+ return ics.get(i);
}
- public ArrayList getEC(int i){
- return (ArrayList) ecs.get(i);
+ public ArrayList<InstructionContext> getEC(int i){
+ return ecs.get(i);
}
public int size(){
return ics.size();
final Random random = new Random();
InstructionContextQueue icq = new InstructionContextQueue();
- start.execute(vanillaFrame, new ArrayList(), icv, ev); // new ArrayList() <=> no Instruction was executed before
+ start.execute(vanillaFrame, new ArrayList<InstructionContext>(), icv, ev); // new ArrayList() <=> no Instruction was executed before
// => Top-Level routine (no jsr call before)
- icq.add(start, new ArrayList());
+ icq.add(start, new ArrayList<InstructionContext>());
// LOOP!
while (!icq.isEmpty()){
InstructionContext u;
- ArrayList ec;
+ ArrayList<InstructionContext> ec;
if (!DEBUG){
int r = random.nextInt(icq.size());
u = icq.getIC(r);
icq.remove(0);
}
- ArrayList oldchain = (ArrayList) (ec.clone());
- ArrayList newchain = (ArrayList) (ec.clone());
+ ArrayList<InstructionContext> oldchain = (ArrayList<InstructionContext>) (ec.clone());
+ ArrayList<InstructionContext> newchain = (ArrayList<InstructionContext>) (ec.clone());
newchain.add(u);
if ((u.getInstruction().getInstruction()) instanceof RET){
throw new AssertionViolatedException("More RET than JSR in execution chain?!");
}
//System.err.println("+"+oldchain.get(ss));
- if (((InstructionContext) oldchain.get(ss)).getInstruction().getInstruction().isJsrInstruction()) {
+ if (oldchain.get(ss).getInstruction().getInstruction().isJsrInstruction()) {
if (skip_jsr == 0){
- lastJSR = (InstructionContext) oldchain.get(ss);
+ lastJSR = oldchain.get(ss);
break;
}
else{
skip_jsr--;
}
}
- if (((InstructionContext) oldchain.get(ss)).getInstruction().getInstruction() instanceof RET){
+ if (oldchain.get(ss).getInstruction().getInstruction() instanceof RET){
skip_jsr++;
}
}
}
if (theSuccessor.execute(u.getOutFrame(oldchain), newchain, icv, ev)){
- icq.add(theSuccessor, (ArrayList) newchain.clone());
+ icq.add(theSuccessor, (ArrayList<InstructionContext>) newchain.clone());
}
}
else{// "not a ret"
for (int s=0; s<succs.length; s++){
InstructionContext v = succs[s];
if (v.execute(u.getOutFrame(oldchain), newchain, icv, ev)){
- icq.add(v, (ArrayList) newchain.clone());
+ icq.add(v, (ArrayList<InstructionContext>) newchain.clone());
}
}
}// end "not a ret"
// by using an empty chain for the exception handlers.
//if (v.execute(new Frame(u.getOutFrame(oldchain).getLocals(), new OperandStack (u.getOutFrame().getStack().maxStack(), (exc_hds[s].getExceptionType()==null? Type.THROWABLE : exc_hds[s].getExceptionType())) ), newchain), icv, ev){
//icq.add(v, (ArrayList) newchain.clone());
- if (v.execute(new Frame(u.getOutFrame(oldchain).getLocals(), new OperandStack (u.getOutFrame(oldchain).getStack().maxStack(), (exc_hds[s].getExceptionType()==null? Type.THROWABLE : exc_hds[s].getExceptionType())) ), new ArrayList(), icv, ev)){
- icq.add(v, new ArrayList());
+ if (v.execute(new Frame(u.getOutFrame(oldchain).getLocals(), new OperandStack (u.getOutFrame(oldchain).getStack().maxStack(), (exc_hds[s].getExceptionType()==null? Type.THROWABLE : exc_hds[s].getExceptionType())) ), new ArrayList<InstructionContext>(), icv, ev)){
+ icq.add(v, new ArrayList<InstructionContext>());
}
}
do{
if ((ih.getInstruction().isReturnInstruction()) && (!(cfg.isDead(ih)))) {
InstructionContext ic = cfg.contextOf(ih);
- Frame f = ic.getOutFrame(new ArrayList()); // TODO: This is buggy, we check only the top-level return instructions this way. Maybe some maniac returns from a method when in a subroutine?
+ Frame f = ic.getOutFrame(new ArrayList<InstructionContext>()); // TODO: This is buggy, we check only the top-level return instructions this way. Maybe some maniac returns from a method when in a subroutine?
LocalVariables lvs = f.getLocals();
for (int i=0; i<lvs.maxLocals(); i++){
if (lvs.get(i) instanceof UninitializedObjectType){
import org.aspectj.apache.bcel.generic.*;
import org.aspectj.apache.bcel.verifier.exc.*;
import java.awt.Color;
+import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
*
* TODO: refer to the paper.
*
- * @version $Id: Subroutines.java,v 1.3 2008/08/28 00:02:13 aclement Exp $
+ * @version $Id: Subroutines.java,v 1.4 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="http://www.inf.fu-berlin.de/~ehaase"/>Enver Haase</A>
* @see #getTopLevel()
*/
private int localVariable = UNSET;
/** The instructions that belong to this subroutine. */
- private HashSet instructions = new HashSet(); // Elements: InstructionHandle
+ private HashSet<Serializable> instructions = new HashSet<Serializable>(); // Elements: InstructionHandle
/*
* Refer to the Subroutine interface for documentation.
* The JSR or JSR_W instructions that define this
* subroutine by targeting it.
*/
- private HashSet theJSRs = new HashSet();
+ private HashSet<InstructionHandle> theJSRs = new HashSet<InstructionHandle>();
/**
* The RET instruction that leaves this subroutine.
if (localVariable == UNSET){
throw new AssertionViolatedException("setLeavingRET() called for top-level 'subroutine' or forgot to set local variable first.");
}
- Iterator iter = instructions.iterator();
+ Iterator<Serializable> iter = instructions.iterator();
InstructionHandle ret = null;
while(iter.hasNext()){
InstructionHandle actual = (InstructionHandle) iter.next();
throw new AssertionViolatedException("getLeavingRET() called on top level pseudo-subroutine.");
}
InstructionHandle[] jsrs = new InstructionHandle[theJSRs.size()];
- return (InstructionHandle[]) (theJSRs.toArray(jsrs));
+ return (theJSRs.toArray(jsrs));
}
/**
*/
public InstructionHandle[] getInstructions(){
InstructionHandle[] ret = new InstructionHandle[instructions.size()];
- return (InstructionHandle[]) instructions.toArray(ret);
+ return instructions.toArray(ret);
}
/*
/* Satisfies Subroutine.getRecursivelyAccessedLocalsIndices(). */
public int[] getRecursivelyAccessedLocalsIndices(){
- HashSet s = new HashSet();
+ HashSet<Integer> s = new HashSet<Integer>();
int[] lvs = getAccessedLocalsIndices();
for (int j=0; j<lvs.length; j++){
s.add(new Integer(lvs[j]));
}
_getRecursivelyAccessedLocalsIndicesHelper(s, this.subSubs());
int[] ret = new int[s.size()];
- Iterator i = s.iterator();
+ Iterator<Integer> i = s.iterator();
int j=-1;
while (i.hasNext()){
j++;
- ret[j] = ((Integer) i.next()).intValue();
+ ret[j] = i.next().intValue();
}
return ret;
}
* A recursive helper method for getRecursivelyAccessedLocalsIndices().
* @see #getRecursivelyAccessedLocalsIndices()
*/
- private void _getRecursivelyAccessedLocalsIndicesHelper(HashSet s, Subroutine[] subs){
+ private void _getRecursivelyAccessedLocalsIndicesHelper(HashSet<Integer> s, Subroutine[] subs){
for (int i=0; i<subs.length; i++){
int[] lvs = subs[i].getAccessedLocalsIndices();
for (int j=0; j<lvs.length; j++){
*/
public int[] getAccessedLocalsIndices(){
//TODO: Implement caching.
- HashSet acc = new HashSet();
+ HashSet<Serializable> acc = new HashSet<Serializable>();
if (theRET == null && this != TOPLEVEL){
throw new AssertionViolatedException("This subroutine object must be built up completely before calculating accessed locals.");
}
- Iterator i = instructions.iterator();
+ Iterator<Serializable> i = instructions.iterator();
while (i.hasNext()){
InstructionHandle ih = (InstructionHandle) i.next();
// RET is not a LocalVariableInstruction in the current version of BCEL.
* Satisfies Subroutine.subSubs().
*/
public Subroutine[] subSubs(){
- HashSet h = new HashSet();
+ HashSet<Subroutine> h = new HashSet<Subroutine>();
- Iterator i = instructions.iterator();
+ Iterator<Serializable> i = instructions.iterator();
while (i.hasNext()){
Instruction inst = ((InstructionHandle) i.next()).getInstruction();
if (inst.isJsrInstruction()){
}
}
Subroutine[] ret = new Subroutine[h.size()];
- return (Subroutine[]) h.toArray(ret);
+ return h.toArray(ret);
}
/*
* Key: InstructionHandle of the leader of the subroutine.
* Elements: SubroutineImpl objects.
*/
- private Hashtable subroutines = new Hashtable();
+ private Hashtable<InstructionHandle, Subroutine> subroutines = new Hashtable<InstructionHandle, Subroutine>();
/**
* This is referring to a special subroutine, namely the
TOPLEVEL = new SubroutineImpl();
// Calculate "real" subroutines.
- HashSet sub_leaders = new HashSet(); // Elements: InstructionHandle
+ HashSet<InstructionHandle> sub_leaders = new HashSet<InstructionHandle>(); // Elements: InstructionHandle
InstructionHandle ih = all[0];
for (int i=0; i<all.length; i++){
Instruction inst = all[i].getInstruction();
}
// Build up the database.
- Iterator iter = sub_leaders.iterator();
+ Iterator<InstructionHandle> iter = sub_leaders.iterator();
while (iter.hasNext()){
SubroutineImpl sr = new SubroutineImpl();
- InstructionHandle astore = (InstructionHandle) (iter.next());
+ InstructionHandle astore = (iter.next());
sr.setLocalVariable( ( (astore.getInstruction())).getIndex() );
subroutines.put(astore, sr);
}
// Now do a BFS from every subroutine leader to find all the
// instructions that belong to a subroutine.
- HashSet instructions_assigned = new HashSet(); // we don't want to assign an instruction to two or more Subroutine objects.
+ HashSet<InstructionHandle> instructions_assigned = new HashSet<InstructionHandle>(); // we don't want to assign an instruction to two or more Subroutine objects.
- Hashtable colors = new Hashtable(); //Graph colouring. Key: InstructionHandle, Value: java.awt.Color .
+ Hashtable<InstructionHandle, Color> colors = new Hashtable<InstructionHandle, Color>(); //Graph colouring. Key: InstructionHandle, Value: java.awt.Color .
iter = sub_leaders.iterator();
while (iter.hasNext()){
// Do some BFS with "actual" as the root of the graph.
- InstructionHandle actual = (InstructionHandle) (iter.next());
+ InstructionHandle actual = (iter.next());
// Init colors
for (int i=0; i<all.length; i++){
colors.put(all[i], Color.white);
}
colors.put(actual, Color.gray);
// Init Queue
- ArrayList Q = new ArrayList();
+ ArrayList<InstructionHandle> Q = new ArrayList<InstructionHandle>();
Q.add(actual); // add(Obj) adds to the end, remove(0) removes from the start.
/* BFS ALGORITHM MODIFICATION: Start out with multiple "root" nodes, as exception handlers are starting points of top-level code, too. [why top-level? TODO: Refer to the special JustIce notion of subroutines.]*/
// Loop until Queue is empty
while (Q.size() != 0){
- InstructionHandle u = (InstructionHandle) Q.remove(0);
+ InstructionHandle u = Q.remove(0);
InstructionHandle[] successors = getSuccessors(u);
for (int i=0; i<successors.length; i++){
- if (((Color) colors.get(successors[i])) == Color.white){
+ if (colors.get(successors[i]) == Color.white){
colors.put(successors[i], Color.gray);
Q.add(successors[i]);
}
for (int i=0; i<handlers.length; i++){
InstructionHandle _protected = handlers[i].getStartPC();
while (_protected != handlers[i].getEndPC().getNext()){// Note the inclusive/inclusive notation of "generic API" exception handlers!
- Enumeration subs = subroutines.elements();
+ Enumeration<Subroutine> subs = subroutines.elements();
while (subs.hasMoreElements()){
- Subroutine sub = (Subroutine) subs.nextElement();
+ Subroutine sub = subs.nextElement();
if (sub != subroutines.get(all[0])){ // We don't want to forbid top-level exception handlers.
if (sub.contains(_protected)){
throw new StructuralCodeConstraintException("Subroutine instruction '"+_protected+"' is protected by an exception handler, '"+handlers[i]+"'. This is forbidden by the JustIce verifier due to its clear definition of subroutines.");
// This includes that subroutines may not call themselves
// recursively, even not through intermediate calls to other
// subroutines.
- noRecursiveCalls(getTopLevel(), new HashSet());
+ noRecursiveCalls(getTopLevel(), new HashSet<Integer>());
}
*
* @throws StructuralCodeConstraintException if the above constraint is not satisfied.
*/
- private void noRecursiveCalls(Subroutine sub, HashSet set){
+ private void noRecursiveCalls(Subroutine sub, HashSet<Integer> set){
Subroutine[] subs = sub.subSubs();
for (int i=0; i<subs.length; i++){
* @see #getTopLevel()
*/
public Subroutine getSubroutine(InstructionHandle leader){
- Subroutine ret = (Subroutine) subroutines.get(leader);
+ Subroutine ret = subroutines.get(leader);
if (ret == null){
throw new AssertionViolatedException("Subroutine requested for an InstructionHandle that is not a leader of a subroutine.");
* @see #getTopLevel()
*/
public Subroutine subroutineOf(InstructionHandle any){
- Iterator i = subroutines.values().iterator();
+ Iterator<Subroutine> i = subroutines.values().iterator();
while (i.hasNext()){
- Subroutine s = (Subroutine) i.next();
+ Subroutine s = i.next();
if (s.contains(any)) return s;
}
System.err.println("DEBUG: Please verify '"+any+"' lies in dead code.");
* Factory creates il.append() statements, and sets instruction targets. A helper class for BCELifier.
*
* @see BCELifier
- * @version $Id: BCELFactory.java,v 1.4 2008/08/28 00:02:14 aclement Exp $
+ * @version $Id: BCELFactory.java,v 1.5 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
*/
class BCELFactory extends org.aspectj.apache.bcel.verifier.EmptyInstVisitor {
_out = out;
}
- private final HashMap branch_map = new HashMap(); // Map<Instruction, InstructionHandle>
+ private final HashMap<Instruction, InstructionHandle> branch_map = new HashMap<Instruction, InstructionHandle>(); // Map<Instruction, InstructionHandle>
public void start() {
if (!_mg.isAbstract() && !_mg.isNative()) {
}
// Memorize BranchInstructions that need an update
- private final ArrayList branches = new ArrayList();
+ private final ArrayList<InstructionBranch> branches = new ArrayList<InstructionBranch>();
public void visitBranchInstruction(InstructionBranch bi) {
BranchHandle bh = (BranchHandle) branch_map.get(bi);
}
private void updateBranchTargets() {
- for (Iterator i = branches.iterator(); i.hasNext();) {
- InstructionBranch bi = (InstructionBranch) i.next();
+ for (Iterator<InstructionBranch> i = branches.iterator(); i.hasNext();) {
+ InstructionBranch bi = i.next();
BranchHandle bh = (BranchHandle) branch_map.get(bi);
int pos = bh.getPosition();
String name = bi.getName() + "_" + pos;
...
}
</pre>
- * @version $Id: InstructionFinder.java,v 1.3 2008/08/28 00:02:14 aclement Exp $
+ * @version $Id: InstructionFinder.java,v 1.4 2009/09/09 19:56:20 aclement Exp $
* @author <A HREF="http://www.berlin.de/~markus.dahm/">M. Dahm</A>
* @see Instruction
* @see InstructionList
private static final int OFFSET = 32767; // char + OFFSET is outside of LATIN-1
private static final int NO_OPCODES = 256; // Potential number, some are not used
- private static final HashMap map = new HashMap(); // Map<String,Pattern>
+ private static final HashMap<String, String> map = new HashMap<String, String>(); // Map<String,Pattern>
private InstructionList il;
private String il_string; // instruction list as string
* @return encoded string for a pattern such as "BranchInstruction".
*/
private static final String mapName(String pattern) {
- String result = (String)map.get(pattern);
+ String result = map.get(pattern);
if(result != null)
return result;
* @return iterator of matches where e.nextElement() returns an array of instruction handles
* describing the matched area
*/
- public final Iterator search(String pattern, InstructionHandle from,
+ public final Iterator<InstructionHandle[]> search(String pattern, InstructionHandle from,
CodeConstraint constraint)
{
String search = compilePattern(pattern);
" not found in instruction list.");
try {
RE regex = new RE(search);
- ArrayList matches = new ArrayList();
+ ArrayList<InstructionHandle[]> matches = new ArrayList<InstructionHandle[]>();
while(start < il_string.length() && regex.match(il_string, start)) {
int startExpr = regex.getParenStart(0);
* returns an array of instruction handles describing the matched
* area
*/
- public final Iterator search(String pattern) {
+ public final Iterator<InstructionHandle[]> search(String pattern) {
return search(pattern, il.getStart(), null);
}
* @return iterator of matches where e.nextElement() returns an array of instruction handles
* describing the matched area
*/
- public final Iterator search(String pattern, InstructionHandle from) {
+ public final Iterator<InstructionHandle[]> search(String pattern, InstructionHandle from) {
return search(pattern, from, null);
}
* @param constraint constraints to be checked on matching code
* @return instruction handle or `null' if the match failed
*/
- public final Iterator search(String pattern, CodeConstraint constraint) {
+ public final Iterator<InstructionHandle[]> search(String pattern, CodeConstraint constraint) {
return search(pattern, il.getStart(), constraint);
}
// Compile strings
- for(Iterator i = map.keySet().iterator(); i.hasNext(); ) {
- String key = (String)i.next();
- String value = (String)map.get(key);
+ for(Iterator<String> i = map.keySet().iterator(); i.hasNext(); ) {
+ String key = i.next();
+ String value = map.get(key);
char ch = value.charAt(1); // Omit already precompiled patterns
if(ch < OFFSET) {