proj_name
stringclasses 157
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
49
| masked_class
stringlengths 68
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 27
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
---|---|---|---|---|---|---|---|---|---|
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/analysis/MultiType.java | MultiType | isAssignableTo | class MultiType extends Type {
private Map<String,CtClass> interfaces;
private Type resolved;
private Type potentialClass;
private MultiType mergeSource;
private boolean changed = false;
public MultiType(Map<String,CtClass> interfaces) {
this(interfaces, null);
}
public MultiType(Map<String,CtClass> interfaces, Type potentialClass) {
super(null);
this.interfaces = interfaces;
this.potentialClass = potentialClass;
}
/**
* Gets the class that corresponds with this type. If this information
* is not yet known, java.lang.Object will be returned.
*/
@Override
public CtClass getCtClass() {
if (resolved != null)
return resolved.getCtClass();
return Type.OBJECT.getCtClass();
}
/**
* Always returns null since this type is never used for an array.
*/
@Override
public Type getComponent() {
return null;
}
/**
* Always returns 1, since this type is a reference.
*/
@Override
public int getSize() {
return 1;
}
/**
* Always reutnrs false since this type is never used for an array
*/
@Override
public boolean isArray() {
return false;
}
/**
* Returns true if the internal state has changed.
*/
@Override
boolean popChanged() {
boolean changed = this.changed;
this.changed = false;
return changed;
}
@Override
public boolean isAssignableFrom(Type type) {
throw new UnsupportedOperationException("Not implemented");
}
public boolean isAssignableTo(Type type) {<FILL_FUNCTION_BODY>}
private void propogateState() {
MultiType source = mergeSource;
while (source != null) {
source.interfaces = interfaces;
source.potentialClass = potentialClass;
source = source.mergeSource;
}
}
private void propogateResolved() {
MultiType source = mergeSource;
while (source != null) {
source.resolved = resolved;
source = source.mergeSource;
}
}
/**
* Always returns true, since this type is always a reference.
*
* @return true
*/
@Override
public boolean isReference() {
return true;
}
private Map<String,CtClass> getAllMultiInterfaces(MultiType type) {
Map<String,CtClass> map = new HashMap<String,CtClass>();
for (CtClass intf:type.interfaces.values()) {
map.put(intf.getName(), intf);
getAllInterfaces(intf, map);
}
return map;
}
private Map<String,CtClass> mergeMultiInterfaces(MultiType type1, MultiType type2) {
Map<String,CtClass> map1 = getAllMultiInterfaces(type1);
Map<String,CtClass> map2 = getAllMultiInterfaces(type2);
return findCommonInterfaces(map1, map2);
}
private Map<String,CtClass> mergeMultiAndSingle(MultiType multi, Type single) {
Map<String,CtClass> map1 = getAllMultiInterfaces(multi);
Map<String,CtClass> map2 = getAllInterfaces(single.getCtClass(), null);
return findCommonInterfaces(map1, map2);
}
private boolean inMergeSource(MultiType source) {
while (source != null) {
if (source == this)
return true;
source = source.mergeSource;
}
return false;
}
@Override
public Type merge(Type type) {
if (this == type)
return this;
if (type == UNINIT)
return this;
if (type == BOGUS)
return BOGUS;
if (type == null)
return this;
if (resolved != null)
return resolved.merge(type);
if (potentialClass != null) {
Type mergePotential = potentialClass.merge(type);
if (! mergePotential.equals(potentialClass) || mergePotential.popChanged()) {
potentialClass = Type.OBJECT.equals(mergePotential) ? null : mergePotential;
changed = true;
}
}
Map<String,CtClass> merged;
if (type instanceof MultiType) {
MultiType multi = (MultiType)type;
if (multi.resolved != null) {
merged = mergeMultiAndSingle(this, multi.resolved);
} else {
merged = mergeMultiInterfaces(multi, this);
if (! inMergeSource(multi))
mergeSource = multi;
}
} else {
merged = mergeMultiAndSingle(this, type);
}
// Keep all previous merge paths up to date
if (merged.size() > 1 || (merged.size() == 1 && potentialClass != null)) {
// Check for changes
if (merged.size() != interfaces.size())
changed = true;
else if (changed == false)
for (String key:merged.keySet())
if (!interfaces.containsKey(key))
changed = true;
interfaces = merged;
propogateState();
return this;
}
if (merged.size() == 1)
resolved = Type.get(merged.values().iterator().next());
else if (potentialClass != null)
resolved = potentialClass;
else
resolved = OBJECT;
propogateResolved();
return resolved;
}
@Override
public int hashCode() {
if (resolved != null)
return resolved.hashCode();
return interfaces.keySet().hashCode();
}
@Override
public boolean equals(Object o) {
if (! (o instanceof MultiType))
return false;
MultiType multi = (MultiType) o;
if (resolved != null)
return resolved.equals(multi.resolved);
else if (multi.resolved != null)
return false;
return interfaces.keySet().equals(multi.interfaces.keySet());
}
@Override
public String toString() {
if (resolved != null)
return resolved.toString();
StringBuffer buffer = new StringBuffer("{");
for (String key:interfaces.keySet())
buffer.append(key).append(", ");
if (potentialClass != null)
buffer.append("*").append(potentialClass.toString());
else
buffer.setLength(buffer.length() - 2);
buffer.append("}");
return buffer.toString();
}
} |
if (resolved != null)
return type.isAssignableFrom(resolved);
if (Type.OBJECT.equals(type))
return true;
if (potentialClass != null && !type.isAssignableFrom(potentialClass))
potentialClass = null;
Map<String,CtClass> map = mergeMultiAndSingle(this, type);
if (map.size() == 1 && potentialClass == null) {
// Update previous merge paths to the same resolved type
resolved = Type.get(map.values().iterator().next());
propogateResolved();
return true;
}
// Keep all previous merge paths up to date
if (map.size() >= 1) {
interfaces = map;
propogateState();
return true;
}
if (potentialClass != null) {
resolved = potentialClass;
propogateResolved();
return true;
}
return false;
| 1,780 | 250 | 2,030 | <methods>public boolean equals(java.lang.Object) ,public static org.hotswap.agent.javassist.bytecode.analysis.Type get(org.hotswap.agent.javassist.CtClass) ,public org.hotswap.agent.javassist.bytecode.analysis.Type getComponent() ,public org.hotswap.agent.javassist.CtClass getCtClass() ,public int getDimensions() ,public int getSize() ,public int hashCode() ,public boolean isArray() ,public boolean isAssignableFrom(org.hotswap.agent.javassist.bytecode.analysis.Type) ,public boolean isReference() ,public boolean isSpecial() ,public org.hotswap.agent.javassist.bytecode.analysis.Type merge(org.hotswap.agent.javassist.bytecode.analysis.Type) ,public java.lang.String toString() <variables>public static final org.hotswap.agent.javassist.bytecode.analysis.Type BOGUS,public static final org.hotswap.agent.javassist.bytecode.analysis.Type BOOLEAN,public static final org.hotswap.agent.javassist.bytecode.analysis.Type BYTE,public static final org.hotswap.agent.javassist.bytecode.analysis.Type CHAR,public static final org.hotswap.agent.javassist.bytecode.analysis.Type CLONEABLE,public static final org.hotswap.agent.javassist.bytecode.analysis.Type DOUBLE,public static final org.hotswap.agent.javassist.bytecode.analysis.Type FLOAT,public static final org.hotswap.agent.javassist.bytecode.analysis.Type INTEGER,public static final org.hotswap.agent.javassist.bytecode.analysis.Type LONG,public static final org.hotswap.agent.javassist.bytecode.analysis.Type OBJECT,public static final org.hotswap.agent.javassist.bytecode.analysis.Type RETURN_ADDRESS,public static final org.hotswap.agent.javassist.bytecode.analysis.Type SERIALIZABLE,public static final org.hotswap.agent.javassist.bytecode.analysis.Type SHORT,public static final org.hotswap.agent.javassist.bytecode.analysis.Type THROWABLE,public static final org.hotswap.agent.javassist.bytecode.analysis.Type TOP,public static final org.hotswap.agent.javassist.bytecode.analysis.Type UNINIT,public static final org.hotswap.agent.javassist.bytecode.analysis.Type VOID,private final non-sealed org.hotswap.agent.javassist.CtClass clazz,private static final Map<org.hotswap.agent.javassist.CtClass,org.hotswap.agent.javassist.bytecode.analysis.Type> prims,private final non-sealed boolean special |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/analysis/Subroutine.java | Subroutine | toString | class Subroutine {
//private Set callers = new HashSet();
private List<Integer> callers = new ArrayList<Integer>();
private Set<Integer> access = new HashSet<Integer>();
private int start;
public Subroutine(int start, int caller) {
this.start = start;
callers.add(caller);
}
public void addCaller(int caller) {
callers.add(caller);
}
public int start() {
return start;
}
public void access(int index) {
access.add(index);
}
public boolean isAccessed(int index) {
return access.contains(index);
}
public Collection<Integer> accessed() {
return access;
}
public Collection<Integer> callers() {
return callers;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
} |
return "start = " + start + " callers = " + callers.toString();
| 250 | 24 | 274 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/analysis/SubroutineScanner.java | SubroutineScanner | scanTableSwitch | class SubroutineScanner implements Opcode {
private Subroutine[] subroutines;
Map<Integer,Subroutine> subTable = new HashMap<Integer,Subroutine>();
Set<Integer> done = new HashSet<Integer>();
public Subroutine[] scan(MethodInfo method) throws BadBytecode {
CodeAttribute code = method.getCodeAttribute();
CodeIterator iter = code.iterator();
subroutines = new Subroutine[code.getCodeLength()];
subTable.clear();
done.clear();
scan(0, iter, null);
ExceptionTable exceptions = code.getExceptionTable();
for (int i = 0; i < exceptions.size(); i++) {
int handler = exceptions.handlerPc(i);
// If an exception is thrown in subroutine, the handler
// is part of the same subroutine.
scan(handler, iter, subroutines[exceptions.startPc(i)]);
}
return subroutines;
}
private void scan(int pos, CodeIterator iter, Subroutine sub) throws BadBytecode {
// Skip already processed blocks
if (done.contains(pos))
return;
done.add(pos);
int old = iter.lookAhead();
iter.move(pos);
boolean next;
do {
pos = iter.next();
next = scanOp(pos, iter, sub) && iter.hasNext();
} while (next);
iter.move(old);
}
private boolean scanOp(int pos, CodeIterator iter, Subroutine sub) throws BadBytecode {
subroutines[pos] = sub;
int opcode = iter.byteAt(pos);
if (opcode == TABLESWITCH) {
scanTableSwitch(pos, iter, sub);
return false;
}
if (opcode == LOOKUPSWITCH) {
scanLookupSwitch(pos, iter, sub);
return false;
}
// All forms of return and throw end current code flow
if (Util.isReturn(opcode) || opcode == RET || opcode == ATHROW)
return false;
if (Util.isJumpInstruction(opcode)) {
int target = Util.getJumpTarget(pos, iter);
if (opcode == JSR || opcode == JSR_W) {
Subroutine s = subTable.get(target);
if (s == null) {
s = new Subroutine(target, pos);
subTable.put(target, s);
scan(target, iter, s);
} else {
s.addCaller(pos);
}
} else {
scan(target, iter, sub);
// GOTO ends current code flow
if (Util.isGoto(opcode))
return false;
}
}
return true;
}
private void scanLookupSwitch(int pos, CodeIterator iter, Subroutine sub) throws BadBytecode {
int index = (pos & ~3) + 4;
// default
scan(pos + iter.s32bitAt(index), iter, sub);
int npairs = iter.s32bitAt(index += 4);
int end = npairs * 8 + (index += 4);
// skip "match"
for (index += 4; index < end; index += 8) {
int target = iter.s32bitAt(index) + pos;
scan(target, iter, sub);
}
}
private void scanTableSwitch(int pos, CodeIterator iter, Subroutine sub) throws BadBytecode {<FILL_FUNCTION_BODY>}
} |
// Skip 4 byte alignment padding
int index = (pos & ~3) + 4;
// default
scan(pos + iter.s32bitAt(index), iter, sub);
int low = iter.s32bitAt(index += 4);
int high = iter.s32bitAt(index += 4);
int end = (high - low + 1) * 4 + (index += 4);
// Offset table
for (; index < end; index += 4) {
int target = iter.s32bitAt(index) + pos;
scan(target, iter, sub);
}
| 941 | 157 | 1,098 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/analysis/Util.java | Util | isJumpInstruction | class Util implements Opcode {
public static int getJumpTarget(int pos, CodeIterator iter) {
int opcode = iter.byteAt(pos);
pos += (opcode == JSR_W || opcode == GOTO_W) ? iter.s32bitAt(pos + 1) : iter.s16bitAt(pos + 1);
return pos;
}
public static boolean isJumpInstruction(int opcode) {<FILL_FUNCTION_BODY>}
public static boolean isGoto(int opcode) {
return opcode == GOTO || opcode == GOTO_W;
}
public static boolean isJsr(int opcode) {
return opcode == JSR || opcode == JSR_W;
}
public static boolean isReturn(int opcode) {
return (opcode >= IRETURN && opcode <= RETURN);
}
} |
return (opcode >= IFEQ && opcode <= JSR) || opcode == IFNULL || opcode == IFNONNULL || opcode == JSR_W || opcode == GOTO_W;
| 232 | 52 | 284 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/annotation/Annotation.java | Pair | addMemberValue | class Pair {
int name;
MemberValue value;
}
ConstPool pool;
int typeIndex;
Map<String,Pair> members; // this sould be LinkedHashMap
// but it is not supported by JDK 1.3.
/**
* Constructs an annotation including no members. A member can be
* later added to the created annotation by <code>addMemberValue()</code>.
*
* @param type the index into the constant pool table.
* the entry at that index must be the
* <code>CONSTANT_Utf8_Info</code> structure
* repreenting the name of the annotation interface type.
* @param cp the constant pool table.
*
* @see #addMemberValue(String, MemberValue)
*/
public Annotation(int type, ConstPool cp) {
pool = cp;
typeIndex = type;
members = null;
}
/**
* Constructs an annotation including no members. A member can be
* later added to the created annotation by <code>addMemberValue()</code>.
*
* @param typeName the fully-qualified name of the annotation interface type.
* @param cp the constant pool table.
*
* @see #addMemberValue(String, MemberValue)
*/
public Annotation(String typeName, ConstPool cp) {
this(cp.addUtf8Info(Descriptor.of(typeName)), cp);
}
/**
* Constructs an annotation that can be accessed through the interface
* represented by <code>clazz</code>. The values of the members are
* not specified.
*
* @param cp the constant pool table.
* @param clazz the interface.
* @throws NotFoundException when the clazz is not found
*/
public Annotation(ConstPool cp, CtClass clazz)
throws NotFoundException
{
// todo Enums are not supported right now.
this(cp.addUtf8Info(Descriptor.of(clazz.getName())), cp);
if (!clazz.isInterface())
throw new RuntimeException(
"Only interfaces are allowed for Annotation creation.");
CtMethod[] methods = clazz.getDeclaredMethods();
if (methods.length > 0)
members = new LinkedHashMap<String,Pair>();
for (CtMethod m:methods)
addMemberValue(m.getName(),
createMemberValue(cp, m.getReturnType()));
}
/**
* Makes an instance of <code>MemberValue</code>.
*
* @param cp the constant pool table.
* @param type the type of the member.
* @return the member value
* @throws NotFoundException when the type is not found
*/
public static MemberValue createMemberValue(ConstPool cp, CtClass type)
throws NotFoundException
{
if (type == CtClass.booleanType)
return new BooleanMemberValue(cp);
else if (type == CtClass.byteType)
return new ByteMemberValue(cp);
else if (type == CtClass.charType)
return new CharMemberValue(cp);
else if (type == CtClass.shortType)
return new ShortMemberValue(cp);
else if (type == CtClass.intType)
return new IntegerMemberValue(cp);
else if (type == CtClass.longType)
return new LongMemberValue(cp);
else if (type == CtClass.floatType)
return new FloatMemberValue(cp);
else if (type == CtClass.doubleType)
return new DoubleMemberValue(cp);
else if (type.getName().equals("java.lang.Class"))
return new ClassMemberValue(cp);
else if (type.getName().equals("java.lang.String"))
return new StringMemberValue(cp);
else if (type.isArray()) {
CtClass arrayType = type.getComponentType();
MemberValue member = createMemberValue(cp, arrayType);
return new ArrayMemberValue(member, cp);
}
else if (type.isInterface()) {
Annotation info = new Annotation(cp, type);
return new AnnotationMemberValue(info, cp);
}
else {
// treat as enum. I know this is not typed,
// but JBoss has an Annotation Compiler for JDK 1.4
// and I want it to work with that. - Bill Burke
EnumMemberValue emv = new EnumMemberValue(cp);
emv.setType(type.getName());
return emv;
}
}
/**
* Adds a new member.
*
* @param nameIndex the index into the constant pool table.
* The entry at that index must be
* a <code>CONSTANT_Utf8_info</code> structure.
* structure representing the member name.
* @param value the member value.
*/
public void addMemberValue(int nameIndex, MemberValue value) {<FILL_FUNCTION_BODY> |
Pair p = new Pair();
p.name = nameIndex;
p.value = value;
addMemberValue(p);
| 1,304 | 38 | 1,342 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/annotation/AnnotationMemberValue.java | AnnotationMemberValue | getType | class AnnotationMemberValue extends MemberValue {
Annotation value;
/**
* Constructs an annotation member. The initial value is not specified.
*/
public AnnotationMemberValue(ConstPool cp) {
this(null, cp);
}
/**
* Constructs an annotation member. The initial value is specified by
* the first parameter.
*/
public AnnotationMemberValue(Annotation a, ConstPool cp) {
super('@', cp);
value = a;
}
@Override
Object getValue(ClassLoader cl, ClassPool cp, Method m)
throws ClassNotFoundException
{
return AnnotationImpl.make(cl, getType(cl), cp, value);
}
@Override
Class<?> getType(ClassLoader cl) throws ClassNotFoundException {<FILL_FUNCTION_BODY>}
/**
* Obtains the value.
*/
public Annotation getValue() {
return value;
}
/**
* Sets the value of this member.
*/
public void setValue(Annotation newValue) {
value = newValue;
}
/**
* Obtains the string representation of this object.
*/
@Override
public String toString() {
return value.toString();
}
/**
* Writes the value.
*/
@Override
public void write(AnnotationsWriter writer) throws IOException {
writer.annotationValue();
value.write(writer);
}
/**
* Accepts a visitor.
*/
@Override
public void accept(MemberValueVisitor visitor) {
visitor.visitAnnotationMemberValue(this);
}
} |
if (value == null)
throw new ClassNotFoundException("no type specified");
return loadClass(cl, value.getTypeName());
| 431 | 37 | 468 | <methods>public abstract void accept(org.hotswap.agent.javassist.bytecode.annotation.MemberValueVisitor) ,public abstract void write(org.hotswap.agent.javassist.bytecode.annotation.AnnotationsWriter) throws java.io.IOException<variables>org.hotswap.agent.javassist.bytecode.ConstPool cp,char tag |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/annotation/ArrayMemberValue.java | ArrayMemberValue | getValue | class ArrayMemberValue extends MemberValue {
MemberValue type;
MemberValue[] values;
/**
* Constructs an array. The initial value or type are not specified.
*/
public ArrayMemberValue(ConstPool cp) {
super('[', cp);
type = null;
values = null;
}
/**
* Constructs an array. The initial value is not specified.
*
* @param t the type of the array elements.
*/
public ArrayMemberValue(MemberValue t, ConstPool cp) {
super('[', cp);
type = t;
values = null;
}
@Override
Object getValue(ClassLoader cl, ClassPool cp, Method method)
throws ClassNotFoundException
{<FILL_FUNCTION_BODY>}
@Override
Class<?> getType(ClassLoader cl) throws ClassNotFoundException {
if (type == null)
throw new ClassNotFoundException("no array type specified");
Object a = Array.newInstance(type.getType(cl), 0);
return a.getClass();
}
/**
* Obtains the type of the elements.
*
* @return null if the type is not specified.
*/
public MemberValue getType() {
return type;
}
/**
* Obtains the elements of the array.
*/
public MemberValue[] getValue() {
return values;
}
/**
* Sets the elements of the array.
*/
public void setValue(MemberValue[] elements) {
values = elements;
if (elements != null && elements.length > 0)
type = elements[0];
}
/**
* Obtains the string representation of this object.
*/
@Override
public String toString() {
StringBuffer buf = new StringBuffer("{");
if (values != null) {
for (int i = 0; i < values.length; i++) {
buf.append(values[i].toString());
if (i + 1 < values.length)
buf.append(", ");
}
}
buf.append("}");
return buf.toString();
}
/**
* Writes the value.
*/
@Override
public void write(AnnotationsWriter writer) throws IOException {
int num = values == null ? 0 : values.length;
writer.arrayValue(num);
for (int i = 0; i < num; ++i)
values[i].write(writer);
}
/**
* Accepts a visitor.
*/
@Override
public void accept(MemberValueVisitor visitor) {
visitor.visitArrayMemberValue(this);
}
} |
if (values == null)
throw new ClassNotFoundException(
"no array elements found: " + method.getName());
int size = values.length;
Class<?> clazz;
if (type == null) {
clazz = method.getReturnType().getComponentType();
if (clazz == null || size > 0)
throw new ClassNotFoundException("broken array type: "
+ method.getName());
}
else
clazz = type.getType(cl);
Object a = Array.newInstance(clazz, size);
for (int i = 0; i < size; i++)
Array.set(a, i, values[i].getValue(cl, cp, method));
return a;
| 698 | 188 | 886 | <methods>public abstract void accept(org.hotswap.agent.javassist.bytecode.annotation.MemberValueVisitor) ,public abstract void write(org.hotswap.agent.javassist.bytecode.annotation.AnnotationsWriter) throws java.io.IOException<variables>org.hotswap.agent.javassist.bytecode.ConstPool cp,char tag |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/annotation/ClassMemberValue.java | ClassMemberValue | getValue | class ClassMemberValue extends MemberValue {
int valueIndex;
/**
* Constructs a class value. The initial value is specified
* by the constant pool entry at the given index.
*
* @param index the index of a CONSTANT_Utf8_info structure.
*/
public ClassMemberValue(int index, ConstPool cp) {
super('c', cp);
this.valueIndex = index;
}
/**
* Constructs a class value.
*
* @param className the initial value.
*/
public ClassMemberValue(String className, ConstPool cp) {
super('c', cp);
setValue(className);
}
/**
* Constructs a class value.
* The initial value is java.lang.Class.
*/
public ClassMemberValue(ConstPool cp) {
super('c', cp);
setValue("java.lang.Class");
}
@Override
Object getValue(ClassLoader cl, ClassPool cp, Method m)
throws ClassNotFoundException {
final String classname = getValue();
if (classname.equals("void"))
return void.class;
else if (classname.equals("int"))
return int.class;
else if (classname.equals("byte"))
return byte.class;
else if (classname.equals("long"))
return long.class;
else if (classname.equals("double"))
return double.class;
else if (classname.equals("float"))
return float.class;
else if (classname.equals("char"))
return char.class;
else if (classname.equals("short"))
return short.class;
else if (classname.equals("boolean"))
return boolean.class;
else
return loadClass(cl, classname);
}
@Override
Class<?> getType(ClassLoader cl) throws ClassNotFoundException {
return loadClass(cl, "java.lang.Class");
}
/**
* Obtains the value of the member.
*
* @return fully-qualified class name.
*/
public String getValue() {<FILL_FUNCTION_BODY>}
/**
* Sets the value of the member.
*
* @param newClassName fully-qualified class name.
*/
public void setValue(String newClassName) {
String setTo = Descriptor.of(newClassName);
valueIndex = cp.addUtf8Info(setTo);
}
/**
* Obtains the string representation of this object.
*/
@Override
public String toString() {
return getValue().replace('$', '.') + ".class";
}
/**
* Writes the value.
*/
@Override
public void write(AnnotationsWriter writer) throws IOException {
writer.classInfoIndex(cp.getUtf8Info(valueIndex));
}
/**
* Accepts a visitor.
*/
@Override
public void accept(MemberValueVisitor visitor) {
visitor.visitClassMemberValue(this);
}
} |
String v = cp.getUtf8Info(valueIndex);
try {
return SignatureAttribute.toTypeSignature(v).jvmTypeName();
} catch (BadBytecode e) {
throw new RuntimeException(e);
}
| 795 | 64 | 859 | <methods>public abstract void accept(org.hotswap.agent.javassist.bytecode.annotation.MemberValueVisitor) ,public abstract void write(org.hotswap.agent.javassist.bytecode.annotation.AnnotationsWriter) throws java.io.IOException<variables>org.hotswap.agent.javassist.bytecode.ConstPool cp,char tag |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/annotation/EnumMemberValue.java | EnumMemberValue | getValue | class EnumMemberValue extends MemberValue {
int typeIndex, valueIndex;
/**
* Constructs an enum constant value. The initial value is specified
* by the constant pool entries at the given indexes.
*
* @param type the index of a CONSTANT_Utf8_info structure
* representing the enum type.
* @param value the index of a CONSTANT_Utf8_info structure.
* representing the enum value.
*/
public EnumMemberValue(int type, int value, ConstPool cp) {
super('e', cp);
this.typeIndex = type;
this.valueIndex = value;
}
/**
* Constructs an enum constant value.
* The initial value is not specified.
*/
public EnumMemberValue(ConstPool cp) {
super('e', cp);
typeIndex = valueIndex = 0;
}
@Override
Object getValue(ClassLoader cl, ClassPool cp, Method m)
throws ClassNotFoundException
{<FILL_FUNCTION_BODY>}
@Override
Class<?> getType(ClassLoader cl) throws ClassNotFoundException {
return loadClass(cl, getType());
}
/**
* Obtains the enum type name.
*
* @return a fully-qualified type name.
*/
public String getType() {
return Descriptor.toClassName(cp.getUtf8Info(typeIndex));
}
/**
* Changes the enum type name.
*
* @param typename a fully-qualified type name.
*/
public void setType(String typename) {
typeIndex = cp.addUtf8Info(Descriptor.of(typename));
}
/**
* Obtains the name of the enum constant value.
*/
public String getValue() {
return cp.getUtf8Info(valueIndex);
}
/**
* Changes the name of the enum constant value.
*/
public void setValue(String name) {
valueIndex = cp.addUtf8Info(name);
}
@Override
public String toString() {
return getType() + "." + getValue();
}
/**
* Writes the value.
*/
@Override
public void write(AnnotationsWriter writer) throws IOException {
writer.enumConstValue(cp.getUtf8Info(typeIndex), getValue());
}
/**
* Accepts a visitor.
*/
@Override
public void accept(MemberValueVisitor visitor) {
visitor.visitEnumMemberValue(this);
}
} |
try {
return getType(cl).getField(getValue()).get(null);
}
catch (NoSuchFieldException e) {
throw new ClassNotFoundException(getType() + "." + getValue());
}
catch (IllegalAccessException e) {
throw new ClassNotFoundException(getType() + "." + getValue());
}
| 673 | 91 | 764 | <methods>public abstract void accept(org.hotswap.agent.javassist.bytecode.annotation.MemberValueVisitor) ,public abstract void write(org.hotswap.agent.javassist.bytecode.annotation.AnnotationsWriter) throws java.io.IOException<variables>org.hotswap.agent.javassist.bytecode.ConstPool cp,char tag |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/annotation/MemberValue.java | MemberValue | loadClass | class MemberValue {
ConstPool cp;
char tag;
MemberValue(char tag, ConstPool cp) {
this.cp = cp;
this.tag = tag;
}
/**
* Returns the value. If the value type is a primitive type, the
* returned value is boxed.
*/
abstract Object getValue(ClassLoader cl, ClassPool cp, Method m)
throws ClassNotFoundException;
abstract Class<?> getType(ClassLoader cl) throws ClassNotFoundException;
static Class<?> loadClass(ClassLoader cl, String classname)
throws ClassNotFoundException, NoSuchClassError
{<FILL_FUNCTION_BODY>}
private static String convertFromArray(String classname)
{
int index = classname.indexOf("[]");
if (index != -1) {
String rawType = classname.substring(0, index);
StringBuffer sb = new StringBuffer(Descriptor.of(rawType));
while (index != -1) {
sb.insert(0, "[");
index = classname.indexOf("[]", index + 1);
}
return sb.toString().replace('/', '.');
}
return classname;
}
/**
* Accepts a visitor.
*/
public abstract void accept(MemberValueVisitor visitor);
/**
* Writes the value.
*/
public abstract void write(AnnotationsWriter w) throws IOException;
} |
try {
return Class.forName(convertFromArray(classname), true, cl);
}
catch (LinkageError e) {
throw new NoSuchClassError(classname, e);
}
| 370 | 56 | 426 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/stackmap/TypeData.java | ClassName | getArrayType | class ClassName extends TypeData {
private String name; // dot separated.
public ClassName(String n) {
name = n;
}
@Override
public String getName() {
return name;
}
@Override
public BasicType isBasicType() { return null; }
@Override
public boolean is2WordType() { return false; }
@Override
public int getTypeTag() { return StackMapTable.OBJECT; }
@Override
public int getTypeData(ConstPool cp) {
return cp.addClassInfo(getName());
}
@Override
public boolean eq(TypeData d) { return name.equals(d.getName()); }
@Override
public void setType(String typeName, ClassPool cp) throws BadBytecode {}
@Override
public TypeData getArrayType(int dim) throws NotFoundException {<FILL_FUNCTION_BODY>}
@Override
String toString2(Set<TypeData> set) {
return name;
}
} |
if (dim == 0)
return this;
else if (dim > 0) {
char[] dimType = new char[dim];
for (int i = 0; i < dim; i++)
dimType[i] = '[';
String elementType = getName();
if (elementType.charAt(0) != '[')
elementType = "L" + elementType.replace('.', '/') + ";";
return new ClassName(new String(dimType) + elementType);
}
else {
for (int i = 0; i < -dim; i++)
if (name.charAt(i) != '[')
throw new NotFoundException("no " + dim + " dimensional array type: " + getName());
char type = name.charAt(-dim);
if (type == '[')
return new ClassName(name.substring(-dim));
else if (type == 'L')
return new ClassName(name.substring(-dim + 1, name.length() - 1).replace('/', '.'));
else if (type == TypeTag.DOUBLE.decodedName)
return TypeTag.DOUBLE;
else if (type == TypeTag.FLOAT.decodedName)
return TypeTag.FLOAT;
else if (type == TypeTag.LONG.decodedName)
return TypeTag.LONG;
else
return TypeTag.INTEGER;
}
| 268 | 366 | 634 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/stackmap/TypedBlock.java | Maker | initFirstBlock | class Maker extends BasicBlock.Maker {
@Override
protected BasicBlock makeBlock(int pos) {
return new TypedBlock(pos);
}
@Override
protected BasicBlock[] makeArray(int size) {
return new TypedBlock[size];
}
}
/**
* Initializes the first block by the given method descriptor.
*
* @param block the first basic block that this method initializes.
* @param className a dot-separated fully qualified class name.
* For example, <code>javassist.bytecode.stackmap.BasicBlock</code>.
* @param methodDesc method descriptor.
* @param isStatic true if the method is a static method.
* @param isConstructor true if the method is a constructor.
*/
void initFirstBlock(int maxStack, int maxLocals, String className,
String methodDesc, boolean isStatic, boolean isConstructor)
throws BadBytecode
{<FILL_FUNCTION_BODY> |
if (methodDesc.charAt(0) != '(')
throw new BadBytecode("no method descriptor: " + methodDesc);
stackTop = 0;
stackTypes = TypeData.make(maxStack);
TypeData[] locals = TypeData.make(maxLocals);
if (isConstructor)
locals[0] = new TypeData.UninitThis(className);
else if (!isStatic)
locals[0] = new TypeData.ClassName(className);
int n = isStatic ? -1 : 0;
int i = 1;
try {
while ((i = descToTag(methodDesc, i, ++n, locals)) > 0)
if (locals[n].is2WordType())
locals[++n] = TypeTag.TOP;
}
catch (StringIndexOutOfBoundsException e) {
throw new BadBytecode("bad method descriptor: "
+ methodDesc);
}
numLocals = n;
localsTypes = locals;
| 256 | 253 | 509 | <methods>public static org.hotswap.agent.javassist.bytecode.stackmap.BasicBlock find(org.hotswap.agent.javassist.bytecode.stackmap.BasicBlock[], int) throws org.hotswap.agent.javassist.bytecode.BadBytecode,public java.lang.String toString() <variables>protected org.hotswap.agent.javassist.bytecode.stackmap.BasicBlock[] exit,protected int incoming,protected int length,protected int position,protected boolean stop,protected org.hotswap.agent.javassist.bytecode.stackmap.BasicBlock.Catch toCatch |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/MemberResolver.java | Method | compareSignature | class Method {
public CtClass declaring;
public MethodInfo info;
public int notmatch;
public Method(CtClass c, MethodInfo i, int n) {
declaring = c;
info = i;
notmatch = n;
}
/**
* Returns true if the invoked method is static.
*/
public boolean isStatic() {
int acc = info.getAccessFlags();
return (acc & AccessFlag.STATIC) != 0;
}
}
public Method lookupMethod(CtClass clazz, CtClass currentClass, MethodInfo current,
String methodName,
int[] argTypes, int[] argDims,
String[] argClassNames)
throws CompileError
{
Method maybe = null;
// to enable the creation of a recursively called method
if (current != null && clazz == currentClass)
if (current.getName().equals(methodName)) {
int res = compareSignature(current.getDescriptor(),
argTypes, argDims, argClassNames);
if (res != NO) {
Method r = new Method(clazz, current, res);
if (res == YES)
return r;
maybe = r;
}
}
Method m = lookupMethod(clazz, methodName, argTypes, argDims,
argClassNames, maybe != null);
if (m != null)
return m;
return maybe;
}
private Method lookupMethod(CtClass clazz, String methodName,
int[] argTypes, int[] argDims,
String[] argClassNames, boolean onlyExact)
throws CompileError
{
Method maybe = null;
ClassFile cf = clazz.getClassFile2();
// If the class is an array type, the class file is null.
// If so, search the super class java.lang.Object for clone() etc.
if (cf != null) {
List<MethodInfo> list = cf.getMethods();
for (MethodInfo minfo:list) {
if (minfo.getName().equals(methodName)
&& (minfo.getAccessFlags() & AccessFlag.BRIDGE) == 0) {
int res = compareSignature(minfo.getDescriptor(),
argTypes, argDims, argClassNames);
if (res != NO) {
Method r = new Method(clazz, minfo, res);
if (res == YES)
return r;
else if (maybe == null || maybe.notmatch > res)
maybe = r;
}
}
}
}
if (onlyExact)
maybe = null;
else
if (maybe != null)
return maybe;
int mod = clazz.getModifiers();
boolean isIntf = Modifier.isInterface(mod);
try {
// skip searching java.lang.Object if clazz is an interface type.
if (!isIntf) {
CtClass pclazz = clazz.getSuperclass();
if (pclazz != null) {
Method r = lookupMethod(pclazz, methodName, argTypes,
argDims, argClassNames, onlyExact);
if (r != null)
return r;
}
}
}
catch (NotFoundException e) {}
try {
CtClass[] ifs = clazz.getInterfaces();
for (CtClass intf:ifs) {
Method r = lookupMethod(intf, methodName,
argTypes, argDims, argClassNames,
onlyExact);
if (r != null)
return r;
}
if (isIntf) {
// finally search java.lang.Object.
CtClass pclazz = clazz.getSuperclass();
if (pclazz != null) {
Method r = lookupMethod(pclazz, methodName, argTypes,
argDims, argClassNames, onlyExact);
if (r != null)
return r;
}
}
}
catch (NotFoundException e) {}
return maybe;
}
private static final int YES = 0;
private static final int NO = -1;
/*
* Returns YES if actual parameter types matches the given signature.
*
* argTypes, argDims, and argClassNames represent actual parameters.
*
* This method does not correctly implement the Java method dispatch
* algorithm.
*
* If some of the parameter types exactly match but others are subtypes of
* the corresponding type in the signature, this method returns the number
* of parameter types that do not exactly match.
*/
private int compareSignature(String desc, int[] argTypes,
int[] argDims, String[] argClassNames)
throws CompileError
{<FILL_FUNCTION_BODY> |
int result = YES;
int i = 1;
int nArgs = argTypes.length;
if (nArgs != Descriptor.numOfParameters(desc))
return NO;
int len = desc.length();
for (int n = 0; i < len; ++n) {
char c = desc.charAt(i++);
if (c == ')')
return (n == nArgs ? result : NO);
else if (n >= nArgs)
return NO;
int dim = 0;
while (c == '[') {
++dim;
c = desc.charAt(i++);
}
if (argTypes[n] == NULL) {
if (dim == 0 && c != 'L')
return NO;
if (c == 'L')
i = desc.indexOf(';', i) + 1;
}
else if (argDims[n] != dim) {
if (!(dim == 0 && c == 'L'
&& desc.startsWith("java/lang/Object;", i)))
return NO;
// if the thread reaches here, c must be 'L'.
i = desc.indexOf(';', i) + 1;
result++;
if (i <= 0)
return NO; // invalid descriptor?
}
else if (c == 'L') { // not compare
int j = desc.indexOf(';', i);
if (j < 0 || argTypes[n] != CLASS)
return NO;
String cname = desc.substring(i, j);
if (!cname.equals(argClassNames[n])) {
CtClass clazz = lookupClassByJvmName(argClassNames[n]);
try {
if (clazz.subtypeOf(lookupClassByJvmName(cname)))
result++;
else
return NO;
}
catch (NotFoundException e) {
result++; // should be NO?
}
}
i = j + 1;
}
else {
int t = descToType(c);
int at = argTypes[n];
if (t != at)
if (t == INT
&& (at == SHORT || at == BYTE || at == CHAR))
result++;
else
return NO;
}
}
return NO;
| 1,231 | 603 | 1,834 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/SymbolTable.java | SymbolTable | lookup | class SymbolTable extends HashMap<String,Declarator> {
/** default serialVersionUID */
private static final long serialVersionUID = 1L;
private SymbolTable parent;
public SymbolTable() { this(null); }
public SymbolTable(SymbolTable p) {
super();
parent = p;
}
public SymbolTable getParent() { return parent; }
public Declarator lookup(String name) {<FILL_FUNCTION_BODY>}
public void append(String name, Declarator value) {
put(name, value);
}
} |
Declarator found = get(name);
if (found == null && parent != null)
return parent.lookup(name);
return found;
| 149 | 42 | 191 | <methods>public void <init>() ,public void <init>(int) ,public void <init>(Map<? extends java.lang.String,? extends org.hotswap.agent.javassist.compiler.ast.Declarator>) ,public void <init>(int, float) ,public void clear() ,public java.lang.Object clone() ,public org.hotswap.agent.javassist.compiler.ast.Declarator compute(java.lang.String, BiFunction<? super java.lang.String,? super org.hotswap.agent.javassist.compiler.ast.Declarator,? extends org.hotswap.agent.javassist.compiler.ast.Declarator>) ,public org.hotswap.agent.javassist.compiler.ast.Declarator computeIfAbsent(java.lang.String, Function<? super java.lang.String,? extends org.hotswap.agent.javassist.compiler.ast.Declarator>) ,public org.hotswap.agent.javassist.compiler.ast.Declarator computeIfPresent(java.lang.String, BiFunction<? super java.lang.String,? super org.hotswap.agent.javassist.compiler.ast.Declarator,? extends org.hotswap.agent.javassist.compiler.ast.Declarator>) ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public Set<Entry<java.lang.String,org.hotswap.agent.javassist.compiler.ast.Declarator>> entrySet() ,public void forEach(BiConsumer<? super java.lang.String,? super org.hotswap.agent.javassist.compiler.ast.Declarator>) ,public org.hotswap.agent.javassist.compiler.ast.Declarator get(java.lang.Object) ,public org.hotswap.agent.javassist.compiler.ast.Declarator getOrDefault(java.lang.Object, org.hotswap.agent.javassist.compiler.ast.Declarator) ,public boolean isEmpty() ,public Set<java.lang.String> keySet() ,public org.hotswap.agent.javassist.compiler.ast.Declarator merge(java.lang.String, org.hotswap.agent.javassist.compiler.ast.Declarator, BiFunction<? super org.hotswap.agent.javassist.compiler.ast.Declarator,? super org.hotswap.agent.javassist.compiler.ast.Declarator,? extends org.hotswap.agent.javassist.compiler.ast.Declarator>) ,public org.hotswap.agent.javassist.compiler.ast.Declarator put(java.lang.String, org.hotswap.agent.javassist.compiler.ast.Declarator) ,public void putAll(Map<? extends java.lang.String,? extends org.hotswap.agent.javassist.compiler.ast.Declarator>) ,public org.hotswap.agent.javassist.compiler.ast.Declarator putIfAbsent(java.lang.String, org.hotswap.agent.javassist.compiler.ast.Declarator) ,public org.hotswap.agent.javassist.compiler.ast.Declarator remove(java.lang.Object) ,public boolean remove(java.lang.Object, java.lang.Object) ,public org.hotswap.agent.javassist.compiler.ast.Declarator replace(java.lang.String, org.hotswap.agent.javassist.compiler.ast.Declarator) ,public boolean replace(java.lang.String, org.hotswap.agent.javassist.compiler.ast.Declarator, org.hotswap.agent.javassist.compiler.ast.Declarator) ,public void replaceAll(BiFunction<? super java.lang.String,? super org.hotswap.agent.javassist.compiler.ast.Declarator,? extends org.hotswap.agent.javassist.compiler.ast.Declarator>) ,public int size() ,public Collection<org.hotswap.agent.javassist.compiler.ast.Declarator> values() <variables>static final int DEFAULT_INITIAL_CAPACITY,static final float DEFAULT_LOAD_FACTOR,static final int MAXIMUM_CAPACITY,static final int MIN_TREEIFY_CAPACITY,static final int TREEIFY_THRESHOLD,static final int UNTREEIFY_THRESHOLD,transient Set<Entry<java.lang.String,org.hotswap.agent.javassist.compiler.ast.Declarator>> entrySet,final float loadFactor,transient int modCount,private static final long serialVersionUID,transient int size,transient Node<java.lang.String,org.hotswap.agent.javassist.compiler.ast.Declarator>[] table,int threshold |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/ast/ASTList.java | ASTList | toString | class ASTList extends ASTree {
/** default serialVersionUID */
private static final long serialVersionUID = 1L;
private ASTree left;
private ASTList right;
public ASTList(ASTree _head, ASTList _tail) {
left = _head;
right = _tail;
}
public ASTList(ASTree _head) {
left = _head;
right = null;
}
public static ASTList make(ASTree e1, ASTree e2, ASTree e3) {
return new ASTList(e1, new ASTList(e2, new ASTList(e3)));
}
@Override
public ASTree getLeft() { return left; }
@Override
public ASTree getRight() { return right; }
@Override
public void setLeft(ASTree _left) { left = _left; }
@Override
public void setRight(ASTree _right) {
right = (ASTList)_right;
}
/**
* Returns the car part of the list.
*/
public ASTree head() { return left; }
public void setHead(ASTree _head) {
left = _head;
}
/**
* Returns the cdr part of the list.
*/
public ASTList tail() { return right; }
public void setTail(ASTList _tail) {
right = _tail;
}
@Override
public void accept(Visitor v) throws CompileError { v.atASTList(this); }
@Override
public String toString() {<FILL_FUNCTION_BODY>}
/**
* Returns the number of the elements in this list.
*/
public int length() {
return length(this);
}
public static int length(ASTList list) {
if (list == null)
return 0;
int n = 0;
while (list != null) {
list = list.right;
++n;
}
return n;
}
/**
* Returns a sub list of the list. The sub list begins with the
* n-th element of the list.
*
* @param nth zero or more than zero.
*/
public ASTList sublist(int nth) {
ASTList list = this;
while (nth-- > 0)
list = list.right;
return list;
}
/**
* Substitutes <code>newObj</code> for <code>oldObj</code> in the
* list.
*/
public boolean subst(ASTree newObj, ASTree oldObj) {
for (ASTList list = this; list != null; list = list.right)
if (list.left == oldObj) {
list.left = newObj;
return true;
}
return false;
}
/**
* Appends an object to a list.
*/
public static ASTList append(ASTList a, ASTree b) {
return concat(a, new ASTList(b));
}
/**
* Concatenates two lists.
*/
public static ASTList concat(ASTList a, ASTList b) {
if (a == null)
return b;
ASTList list = a;
while (list.right != null)
list = list.right;
list.right = b;
return a;
}
} |
StringBuffer sbuf = new StringBuffer();
sbuf.append("(<");
sbuf.append(getTag());
sbuf.append('>');
ASTList list = this;
while (list != null) {
sbuf.append(' ');
ASTree a = list.left;
sbuf.append(a == null ? "<null>" : a.toString());
list = list.right;
}
sbuf.append(')');
return sbuf.toString();
| 911 | 132 | 1,043 | <methods>public non-sealed void <init>() ,public abstract void accept(org.hotswap.agent.javassist.compiler.ast.Visitor) throws org.hotswap.agent.javassist.compiler.CompileError,public org.hotswap.agent.javassist.compiler.ast.ASTree getLeft() ,public org.hotswap.agent.javassist.compiler.ast.ASTree getRight() ,public void setLeft(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setRight(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public java.lang.String toString() <variables>private static final long serialVersionUID |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/ast/ASTree.java | ASTree | toString | class ASTree implements Serializable {
/** default serialVersionUID */
private static final long serialVersionUID = 1L;
public ASTree getLeft() { return null; }
public ASTree getRight() { return null; }
public void setLeft(ASTree _left) {}
public void setRight(ASTree _right) {}
/**
* Is a method for the visitor pattern. It calls
* <code>atXXX()</code> on the given visitor, where
* <code>XXX</code> is the class name of the node object.
*/
public abstract void accept(Visitor v) throws CompileError;
@Override
public String toString() {<FILL_FUNCTION_BODY>}
/**
* Returns the type of this node. This method is used by
* <code>toString()</code>.
*/
protected String getTag() {
String name = getClass().getName();
return name.substring(name.lastIndexOf('.') + 1);
}
} |
StringBuffer sbuf = new StringBuffer();
sbuf.append('<');
sbuf.append(getTag());
sbuf.append('>');
return sbuf.toString();
| 268 | 50 | 318 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/ast/Declarator.java | Declarator | astToClassName | class Declarator extends ASTList implements TokenId {
/** default serialVersionUID */
private static final long serialVersionUID = 1L;
protected int varType;
protected int arrayDim;
protected int localVar;
protected String qualifiedClass; // JVM-internal representation
public Declarator(int type, int dim) {
super(null);
varType = type;
arrayDim = dim;
localVar = -1;
qualifiedClass = null;
}
public Declarator(ASTList className, int dim) {
super(null);
varType = CLASS;
arrayDim = dim;
localVar = -1;
qualifiedClass = astToClassName(className, '/');
}
/* For declaring a pre-defined? local variable.
*/
public Declarator(int type, String jvmClassName, int dim,
int var, Symbol sym) {
super(null);
varType = type;
arrayDim = dim;
localVar = var;
qualifiedClass = jvmClassName;
setLeft(sym);
append(this, null); // initializer
}
public Declarator make(Symbol sym, int dim, ASTree init) {
Declarator d = new Declarator(this.varType, this.arrayDim + dim);
d.qualifiedClass = this.qualifiedClass;
d.setLeft(sym);
append(d, init);
return d;
}
/* Returns CLASS, BOOLEAN, BYTE, CHAR, SHORT, INT, LONG, FLOAT,
* or DOUBLE (or VOID)
*/
public int getType() { return varType; }
public int getArrayDim() { return arrayDim; }
public void addArrayDim(int d) { arrayDim += d; }
public String getClassName() { return qualifiedClass; }
public void setClassName(String s) { qualifiedClass = s; }
public Symbol getVariable() { return (Symbol)getLeft(); }
public void setVariable(Symbol sym) { setLeft(sym); }
public ASTree getInitializer() {
ASTList t = tail();
if (t != null)
return t.head();
return null;
}
public void setLocalVar(int n) { localVar = n; }
public int getLocalVar() { return localVar; }
@Override
public String getTag() { return "decl"; }
@Override
public void accept(Visitor v) throws CompileError {
v.atDeclarator(this);
}
public static String astToClassName(ASTList name, char sep) {
if (name == null)
return null;
StringBuffer sbuf = new StringBuffer();
astToClassName(sbuf, name, sep);
return sbuf.toString();
}
private static void astToClassName(StringBuffer sbuf, ASTList name,
char sep) {<FILL_FUNCTION_BODY>}
} |
for (;;) {
ASTree h = name.head();
if (h instanceof Symbol)
sbuf.append(((Symbol)h).get());
else if (h instanceof ASTList)
astToClassName(sbuf, (ASTList)h, sep);
name = name.tail();
if (name == null)
break;
sbuf.append(sep);
}
| 775 | 105 | 880 | <methods>public void <init>(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTList) ,public void <init>(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void accept(org.hotswap.agent.javassist.compiler.ast.Visitor) throws org.hotswap.agent.javassist.compiler.CompileError,public static org.hotswap.agent.javassist.compiler.ast.ASTList append(org.hotswap.agent.javassist.compiler.ast.ASTList, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public static org.hotswap.agent.javassist.compiler.ast.ASTList concat(org.hotswap.agent.javassist.compiler.ast.ASTList, org.hotswap.agent.javassist.compiler.ast.ASTList) ,public org.hotswap.agent.javassist.compiler.ast.ASTree getLeft() ,public org.hotswap.agent.javassist.compiler.ast.ASTree getRight() ,public org.hotswap.agent.javassist.compiler.ast.ASTree head() ,public int length() ,public static int length(org.hotswap.agent.javassist.compiler.ast.ASTList) ,public static org.hotswap.agent.javassist.compiler.ast.ASTList make(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setHead(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setLeft(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setRight(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setTail(org.hotswap.agent.javassist.compiler.ast.ASTList) ,public org.hotswap.agent.javassist.compiler.ast.ASTList sublist(int) ,public boolean subst(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public org.hotswap.agent.javassist.compiler.ast.ASTList tail() ,public java.lang.String toString() <variables>private org.hotswap.agent.javassist.compiler.ast.ASTree left,private org.hotswap.agent.javassist.compiler.ast.ASTList right,private static final long serialVersionUID |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/ast/DoubleConst.java | DoubleConst | compute | class DoubleConst extends ASTree {
/** default serialVersionUID */
private static final long serialVersionUID = 1L;
protected double value;
protected int type;
public DoubleConst(double v, int tokenId) { value = v; type = tokenId; }
public double get() { return value; }
public void set(double v) { value = v; }
/* Returns DoubleConstant or FloatConstant
*/
public int getType() { return type; }
@Override
public String toString() { return Double.toString(value); }
@Override
public void accept(Visitor v) throws CompileError {
v.atDoubleConst(this);
}
public ASTree compute(int op, ASTree right) {
if (right instanceof IntConst)
return compute0(op, (IntConst)right);
else if (right instanceof DoubleConst)
return compute0(op, (DoubleConst)right);
else
return null;
}
private DoubleConst compute0(int op, DoubleConst right) {
int newType;
if (this.type == TokenId.DoubleConstant
|| right.type == TokenId.DoubleConstant)
newType = TokenId.DoubleConstant;
else
newType = TokenId.FloatConstant;
return compute(op, this.value, right.value, newType);
}
private DoubleConst compute0(int op, IntConst right) {
return compute(op, this.value, right.value, this.type);
}
private static DoubleConst compute(int op, double value1, double value2,
int newType)
{<FILL_FUNCTION_BODY>}
} |
double newValue;
switch (op) {
case '+' :
newValue = value1 + value2;
break;
case '-' :
newValue = value1 - value2;
break;
case '*' :
newValue = value1 * value2;
break;
case '/' :
newValue = value1 / value2;
break;
case '%' :
newValue = value1 % value2;
break;
default :
return null;
}
return new DoubleConst(newValue, newType);
| 433 | 149 | 582 | <methods>public non-sealed void <init>() ,public abstract void accept(org.hotswap.agent.javassist.compiler.ast.Visitor) throws org.hotswap.agent.javassist.compiler.CompileError,public org.hotswap.agent.javassist.compiler.ast.ASTree getLeft() ,public org.hotswap.agent.javassist.compiler.ast.ASTree getRight() ,public void setLeft(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setRight(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public java.lang.String toString() <variables>private static final long serialVersionUID |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/ast/Expr.java | Expr | getName | class Expr extends ASTList implements TokenId {
/* operator must be either of:
* (unary) +, (unary) -, ++, --, !, ~,
* ARRAY, . (dot), MEMBER (static member access).
* Otherwise, the object should be an instance of a subclass.
*/
/** default serialVersionUID */
private static final long serialVersionUID = 1L;
protected int operatorId;
Expr(int op, ASTree _head, ASTList _tail) {
super(_head, _tail);
operatorId = op;
}
Expr(int op, ASTree _head) {
super(_head);
operatorId = op;
}
public static Expr make(int op, ASTree oprand1, ASTree oprand2) {
return new Expr(op, oprand1, new ASTList(oprand2));
}
public static Expr make(int op, ASTree oprand1) {
return new Expr(op, oprand1);
}
public int getOperator() { return operatorId; }
public void setOperator(int op) { operatorId = op; }
public ASTree oprand1() { return getLeft(); }
public void setOprand1(ASTree expr) {
setLeft(expr);
}
public ASTree oprand2() { return getRight().getLeft(); }
public void setOprand2(ASTree expr) {
getRight().setLeft(expr);
}
@Override
public void accept(Visitor v) throws CompileError { v.atExpr(this); }
public String getName() {<FILL_FUNCTION_BODY>}
@Override
protected String getTag() {
return "op:" + getName();
}
} |
int id = operatorId;
if (id < 128)
return String.valueOf((char)id);
else if (NEQ <= id && id <= ARSHIFT_E)
return opNames[id - NEQ];
else if (id == INSTANCEOF)
return "instanceof";
else
return String.valueOf(id);
| 482 | 95 | 577 | <methods>public void <init>(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTList) ,public void <init>(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void accept(org.hotswap.agent.javassist.compiler.ast.Visitor) throws org.hotswap.agent.javassist.compiler.CompileError,public static org.hotswap.agent.javassist.compiler.ast.ASTList append(org.hotswap.agent.javassist.compiler.ast.ASTList, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public static org.hotswap.agent.javassist.compiler.ast.ASTList concat(org.hotswap.agent.javassist.compiler.ast.ASTList, org.hotswap.agent.javassist.compiler.ast.ASTList) ,public org.hotswap.agent.javassist.compiler.ast.ASTree getLeft() ,public org.hotswap.agent.javassist.compiler.ast.ASTree getRight() ,public org.hotswap.agent.javassist.compiler.ast.ASTree head() ,public int length() ,public static int length(org.hotswap.agent.javassist.compiler.ast.ASTList) ,public static org.hotswap.agent.javassist.compiler.ast.ASTList make(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setHead(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setLeft(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setRight(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setTail(org.hotswap.agent.javassist.compiler.ast.ASTList) ,public org.hotswap.agent.javassist.compiler.ast.ASTList sublist(int) ,public boolean subst(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public org.hotswap.agent.javassist.compiler.ast.ASTList tail() ,public java.lang.String toString() <variables>private org.hotswap.agent.javassist.compiler.ast.ASTree left,private org.hotswap.agent.javassist.compiler.ast.ASTList right,private static final long serialVersionUID |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/ast/IntConst.java | IntConst | compute0 | class IntConst extends ASTree {
/** default serialVersionUID */
private static final long serialVersionUID = 1L;
protected long value;
protected int type;
public IntConst(long v, int tokenId) { value = v; type = tokenId; }
public long get() { return value; }
public void set(long v) { value = v; }
/* Returns IntConstant, CharConstant, or LongConstant.
*/
public int getType() { return type; }
@Override
public String toString() { return Long.toString(value); }
@Override
public void accept(Visitor v) throws CompileError {
v.atIntConst(this);
}
public ASTree compute(int op, ASTree right) {
if (right instanceof IntConst)
return compute0(op, (IntConst)right);
else if (right instanceof DoubleConst)
return compute0(op, (DoubleConst)right);
else
return null;
}
private IntConst compute0(int op, IntConst right) {<FILL_FUNCTION_BODY>}
private DoubleConst compute0(int op, DoubleConst right) {
double value1 = this.value;
double value2 = right.value;
double newValue;
switch (op) {
case '+' :
newValue = value1 + value2;
break;
case '-' :
newValue = value1 - value2;
break;
case '*' :
newValue = value1 * value2;
break;
case '/' :
newValue = value1 / value2;
break;
case '%' :
newValue = value1 % value2;
break;
default :
return null;
}
return new DoubleConst(newValue, right.type);
}
} |
int type1 = this.type;
int type2 = right.type;
int newType;
if (type1 == TokenId.LongConstant || type2 == TokenId.LongConstant)
newType = TokenId.LongConstant;
else if (type1 == TokenId.CharConstant
&& type2 == TokenId.CharConstant)
newType = TokenId.CharConstant;
else
newType = TokenId.IntConstant;
long value1 = this.value;
long value2 = right.value;
long newValue;
switch (op) {
case '+' :
newValue = value1 + value2;
break;
case '-' :
newValue = value1 - value2;
break;
case '*' :
newValue = value1 * value2;
break;
case '/' :
newValue = value1 / value2;
break;
case '%' :
newValue = value1 % value2;
break;
case '|' :
newValue = value1 | value2;
break;
case '^' :
newValue = value1 ^ value2;
break;
case '&' :
newValue = value1 & value2;
break;
case TokenId.LSHIFT :
newValue = value << (int)value2;
newType = type1;
break;
case TokenId.RSHIFT :
newValue = value >> (int)value2;
newType = type1;
break;
case TokenId.ARSHIFT :
newValue = value >>> (int)value2;
newType = type1;
break;
default :
return null;
}
return new IntConst(newValue, newType);
| 473 | 464 | 937 | <methods>public non-sealed void <init>() ,public abstract void accept(org.hotswap.agent.javassist.compiler.ast.Visitor) throws org.hotswap.agent.javassist.compiler.CompileError,public org.hotswap.agent.javassist.compiler.ast.ASTree getLeft() ,public org.hotswap.agent.javassist.compiler.ast.ASTree getRight() ,public void setLeft(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setRight(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public java.lang.String toString() <variables>private static final long serialVersionUID |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/ast/MethodDecl.java | MethodDecl | isConstructor | class MethodDecl extends ASTList {
/** default serialVersionUID */
private static final long serialVersionUID = 1L;
public static final String initName = "<init>";
public MethodDecl(ASTree _head, ASTList _tail) {
super(_head, _tail);
}
public boolean isConstructor() {<FILL_FUNCTION_BODY>}
public ASTList getModifiers() { return (ASTList)getLeft(); }
public Declarator getReturn() { return (Declarator)tail().head(); }
public ASTList getParams() { return (ASTList)sublist(2).head(); }
public ASTList getThrows() { return (ASTList)sublist(3).head(); }
public Stmnt getBody() { return (Stmnt)sublist(4).head(); }
@Override
public void accept(Visitor v) throws CompileError {
v.atMethodDecl(this);
}
} |
Symbol sym = getReturn().getVariable();
return sym != null && initName.equals(sym.get());
| 246 | 31 | 277 | <methods>public void <init>(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTList) ,public void <init>(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void accept(org.hotswap.agent.javassist.compiler.ast.Visitor) throws org.hotswap.agent.javassist.compiler.CompileError,public static org.hotswap.agent.javassist.compiler.ast.ASTList append(org.hotswap.agent.javassist.compiler.ast.ASTList, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public static org.hotswap.agent.javassist.compiler.ast.ASTList concat(org.hotswap.agent.javassist.compiler.ast.ASTList, org.hotswap.agent.javassist.compiler.ast.ASTList) ,public org.hotswap.agent.javassist.compiler.ast.ASTree getLeft() ,public org.hotswap.agent.javassist.compiler.ast.ASTree getRight() ,public org.hotswap.agent.javassist.compiler.ast.ASTree head() ,public int length() ,public static int length(org.hotswap.agent.javassist.compiler.ast.ASTList) ,public static org.hotswap.agent.javassist.compiler.ast.ASTList make(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setHead(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setLeft(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setRight(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setTail(org.hotswap.agent.javassist.compiler.ast.ASTList) ,public org.hotswap.agent.javassist.compiler.ast.ASTList sublist(int) ,public boolean subst(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public org.hotswap.agent.javassist.compiler.ast.ASTList tail() ,public java.lang.String toString() <variables>private org.hotswap.agent.javassist.compiler.ast.ASTree left,private org.hotswap.agent.javassist.compiler.ast.ASTList right,private static final long serialVersionUID |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/ast/NewExpr.java | NewExpr | getInitializer | class NewExpr extends ASTList implements TokenId {
/** default serialVersionUID */
private static final long serialVersionUID = 1L;
protected boolean newArray;
protected int arrayType;
public NewExpr(ASTList className, ASTList args) {
super(className, new ASTList(args));
newArray = false;
arrayType = CLASS;
}
public NewExpr(int type, ASTList arraySize, ArrayInit init) {
super(null, new ASTList(arraySize));
newArray = true;
arrayType = type;
if (init != null)
append(this, init);
}
public static NewExpr makeObjectArray(ASTList className,
ASTList arraySize, ArrayInit init) {
NewExpr e = new NewExpr(className, arraySize);
e.newArray = true;
if (init != null)
append(e, init);
return e;
}
public boolean isArray() { return newArray; }
/* TokenId.CLASS, TokenId.INT, ...
*/
public int getArrayType() { return arrayType; }
public ASTList getClassName() { return (ASTList)getLeft(); }
public ASTList getArguments() { return (ASTList)getRight().getLeft(); }
public ASTList getArraySize() { return getArguments(); }
public ArrayInit getInitializer() {<FILL_FUNCTION_BODY>}
@Override
public void accept(Visitor v) throws CompileError { v.atNewExpr(this); }
@Override
protected String getTag() {
return newArray ? "new[]" : "new";
}
} |
ASTree t = getRight().getRight();
if (t == null)
return null;
return (ArrayInit)t.getLeft();
| 435 | 41 | 476 | <methods>public void <init>(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTList) ,public void <init>(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void accept(org.hotswap.agent.javassist.compiler.ast.Visitor) throws org.hotswap.agent.javassist.compiler.CompileError,public static org.hotswap.agent.javassist.compiler.ast.ASTList append(org.hotswap.agent.javassist.compiler.ast.ASTList, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public static org.hotswap.agent.javassist.compiler.ast.ASTList concat(org.hotswap.agent.javassist.compiler.ast.ASTList, org.hotswap.agent.javassist.compiler.ast.ASTList) ,public org.hotswap.agent.javassist.compiler.ast.ASTree getLeft() ,public org.hotswap.agent.javassist.compiler.ast.ASTree getRight() ,public org.hotswap.agent.javassist.compiler.ast.ASTree head() ,public int length() ,public static int length(org.hotswap.agent.javassist.compiler.ast.ASTList) ,public static org.hotswap.agent.javassist.compiler.ast.ASTList make(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setHead(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setLeft(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setRight(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setTail(org.hotswap.agent.javassist.compiler.ast.ASTList) ,public org.hotswap.agent.javassist.compiler.ast.ASTList sublist(int) ,public boolean subst(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public org.hotswap.agent.javassist.compiler.ast.ASTList tail() ,public java.lang.String toString() <variables>private org.hotswap.agent.javassist.compiler.ast.ASTree left,private org.hotswap.agent.javassist.compiler.ast.ASTList right,private static final long serialVersionUID |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/ast/Pair.java | Pair | toString | class Pair extends ASTree {
/** default serialVersionUID */
private static final long serialVersionUID = 1L;
protected ASTree left, right;
public Pair(ASTree _left, ASTree _right) {
left = _left;
right = _right;
}
@Override
public void accept(Visitor v) throws CompileError { v.atPair(this); }
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public ASTree getLeft() { return left; }
@Override
public ASTree getRight() { return right; }
@Override
public void setLeft(ASTree _left) { left = _left; }
@Override
public void setRight(ASTree _right) { right = _right; }
} |
StringBuffer sbuf = new StringBuffer();
sbuf.append("(<Pair> ");
sbuf.append(left == null ? "<null>" : left.toString());
sbuf.append(" . ");
sbuf.append(right == null ? "<null>" : right.toString());
sbuf.append(')');
return sbuf.toString();
| 217 | 94 | 311 | <methods>public non-sealed void <init>() ,public abstract void accept(org.hotswap.agent.javassist.compiler.ast.Visitor) throws org.hotswap.agent.javassist.compiler.CompileError,public org.hotswap.agent.javassist.compiler.ast.ASTree getLeft() ,public org.hotswap.agent.javassist.compiler.ast.ASTree getRight() ,public void setLeft(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setRight(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public java.lang.String toString() <variables>private static final long serialVersionUID |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/compiler/ast/Stmnt.java | Stmnt | getTag | class Stmnt extends ASTList implements TokenId {
/** default serialVersionUID */
private static final long serialVersionUID = 1L;
protected int operatorId;
public Stmnt(int op, ASTree _head, ASTList _tail) {
super(_head, _tail);
operatorId = op;
}
public Stmnt(int op, ASTree _head) {
super(_head);
operatorId = op;
}
public Stmnt(int op) {
this(op, null);
}
public static Stmnt make(int op, ASTree oprand1, ASTree oprand2) {
return new Stmnt(op, oprand1, new ASTList(oprand2));
}
public static Stmnt make(int op, ASTree op1, ASTree op2, ASTree op3) {
return new Stmnt(op, op1, new ASTList(op2, new ASTList(op3)));
}
@Override
public void accept(Visitor v) throws CompileError { v.atStmnt(this); }
public int getOperator() { return operatorId; }
@Override
protected String getTag() {<FILL_FUNCTION_BODY>}
} |
if (operatorId < 128)
return "stmnt:" + (char)operatorId;
return "stmnt:" + operatorId;
| 325 | 39 | 364 | <methods>public void <init>(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTList) ,public void <init>(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void accept(org.hotswap.agent.javassist.compiler.ast.Visitor) throws org.hotswap.agent.javassist.compiler.CompileError,public static org.hotswap.agent.javassist.compiler.ast.ASTList append(org.hotswap.agent.javassist.compiler.ast.ASTList, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public static org.hotswap.agent.javassist.compiler.ast.ASTList concat(org.hotswap.agent.javassist.compiler.ast.ASTList, org.hotswap.agent.javassist.compiler.ast.ASTList) ,public org.hotswap.agent.javassist.compiler.ast.ASTree getLeft() ,public org.hotswap.agent.javassist.compiler.ast.ASTree getRight() ,public org.hotswap.agent.javassist.compiler.ast.ASTree head() ,public int length() ,public static int length(org.hotswap.agent.javassist.compiler.ast.ASTList) ,public static org.hotswap.agent.javassist.compiler.ast.ASTList make(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setHead(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setLeft(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setRight(org.hotswap.agent.javassist.compiler.ast.ASTree) ,public void setTail(org.hotswap.agent.javassist.compiler.ast.ASTList) ,public org.hotswap.agent.javassist.compiler.ast.ASTList sublist(int) ,public boolean subst(org.hotswap.agent.javassist.compiler.ast.ASTree, org.hotswap.agent.javassist.compiler.ast.ASTree) ,public org.hotswap.agent.javassist.compiler.ast.ASTList tail() ,public java.lang.String toString() <variables>private org.hotswap.agent.javassist.compiler.ast.ASTree left,private org.hotswap.agent.javassist.compiler.ast.ASTList right,private static final long serialVersionUID |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/convert/TransformAfter.java | TransformAfter | match2 | class TransformAfter extends TransformBefore {
public TransformAfter(Transformer next,
CtMethod origMethod, CtMethod afterMethod)
throws NotFoundException
{
super(next, origMethod, afterMethod);
}
@Override
protected int match2(int pos, CodeIterator iterator) throws BadBytecode {<FILL_FUNCTION_BODY>}
} |
iterator.move(pos);
iterator.insert(saveCode);
iterator.insert(loadCode);
int p = iterator.insertGap(3);
iterator.setMark(p);
iterator.insert(loadCode);
pos = iterator.next();
p = iterator.getMark();
iterator.writeByte(iterator.byteAt(pos), p);
iterator.write16bit(iterator.u16bitAt(pos + 1), p + 1);
iterator.writeByte(INVOKESTATIC, pos);
iterator.write16bit(newIndex, pos + 1);
iterator.move(p);
return iterator.next();
| 98 | 178 | 276 | <methods>public void <init>(org.hotswap.agent.javassist.convert.Transformer, org.hotswap.agent.javassist.CtMethod, org.hotswap.agent.javassist.CtMethod) throws org.hotswap.agent.javassist.NotFoundException,public int extraLocals() ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.bytecode.CodeAttribute) <variables>protected byte[] loadCode,protected int locals,protected int maxLocals,protected org.hotswap.agent.javassist.CtClass[] parameterTypes,protected byte[] saveCode |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/convert/TransformBefore.java | TransformBefore | match2 | class TransformBefore extends TransformCall {
protected CtClass[] parameterTypes;
protected int locals;
protected int maxLocals;
protected byte[] saveCode, loadCode;
public TransformBefore(Transformer next,
CtMethod origMethod, CtMethod beforeMethod)
throws NotFoundException
{
super(next, origMethod, beforeMethod);
// override
methodDescriptor = origMethod.getMethodInfo2().getDescriptor();
parameterTypes = origMethod.getParameterTypes();
locals = 0;
maxLocals = 0;
saveCode = loadCode = null;
}
@Override
public void initialize(ConstPool cp, CodeAttribute attr) {
super.initialize(cp, attr);
locals = 0;
maxLocals = attr.getMaxLocals();
saveCode = loadCode = null;
}
@Override
protected int match(int c, int pos, CodeIterator iterator,
int typedesc, ConstPool cp) throws BadBytecode
{
if (newIndex == 0) {
String desc = Descriptor.ofParameters(parameterTypes) + 'V';
desc = Descriptor.insertParameter(classname, desc);
int nt = cp.addNameAndTypeInfo(newMethodname, desc);
int ci = cp.addClassInfo(newClassname);
newIndex = cp.addMethodrefInfo(ci, nt);
constPool = cp;
}
if (saveCode == null)
makeCode(parameterTypes, cp);
return match2(pos, iterator);
}
protected int match2(int pos, CodeIterator iterator) throws BadBytecode {<FILL_FUNCTION_BODY>}
@Override
public int extraLocals() { return locals; }
protected void makeCode(CtClass[] paramTypes, ConstPool cp) {
Bytecode save = new Bytecode(cp, 0, 0);
Bytecode load = new Bytecode(cp, 0, 0);
int var = maxLocals;
int len = (paramTypes == null) ? 0 : paramTypes.length;
load.addAload(var);
makeCode2(save, load, 0, len, paramTypes, var + 1);
save.addAstore(var);
saveCode = save.get();
loadCode = load.get();
}
private void makeCode2(Bytecode save, Bytecode load,
int i, int n, CtClass[] paramTypes, int var)
{
if (i < n) {
int size = load.addLoad(var, paramTypes[i]);
makeCode2(save, load, i + 1, n, paramTypes, var + size);
save.addStore(var, paramTypes[i]);
}
else
locals = var - maxLocals;
}
} |
iterator.move(pos);
iterator.insert(saveCode);
iterator.insert(loadCode);
int p = iterator.insertGap(3);
iterator.writeByte(INVOKESTATIC, p);
iterator.write16bit(newIndex, p + 1);
iterator.insert(loadCode);
return iterator.next();
| 717 | 97 | 814 | <methods>public void <init>(org.hotswap.agent.javassist.convert.Transformer, org.hotswap.agent.javassist.CtMethod, org.hotswap.agent.javassist.CtMethod) ,public void <init>(org.hotswap.agent.javassist.convert.Transformer, java.lang.String, org.hotswap.agent.javassist.CtMethod) ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.bytecode.CodeAttribute) ,public int transform(org.hotswap.agent.javassist.CtClass, int, org.hotswap.agent.javassist.bytecode.CodeIterator, org.hotswap.agent.javassist.bytecode.ConstPool) throws org.hotswap.agent.javassist.bytecode.BadBytecode<variables>protected java.lang.String classname,protected org.hotswap.agent.javassist.bytecode.ConstPool constPool,protected java.lang.String methodDescriptor,protected java.lang.String methodname,protected java.lang.String newClassname,protected int newIndex,protected boolean newMethodIsPrivate,protected java.lang.String newMethodname |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/convert/TransformCall.java | TransformCall | transform | class TransformCall extends Transformer {
protected String classname, methodname, methodDescriptor;
protected String newClassname, newMethodname;
protected boolean newMethodIsPrivate;
/* cache */
protected int newIndex;
protected ConstPool constPool;
public TransformCall(Transformer next, CtMethod origMethod,
CtMethod substMethod)
{
this(next, origMethod.getName(), substMethod);
classname = origMethod.getDeclaringClass().getName();
}
public TransformCall(Transformer next, String oldMethodName,
CtMethod substMethod)
{
super(next);
methodname = oldMethodName;
methodDescriptor = substMethod.getMethodInfo2().getDescriptor();
classname = newClassname = substMethod.getDeclaringClass().getName();
newMethodname = substMethod.getName();
constPool = null;
newMethodIsPrivate = Modifier.isPrivate(substMethod.getModifiers());
}
@Override
public void initialize(ConstPool cp, CodeAttribute attr) {
if (constPool != cp)
newIndex = 0;
}
/**
* Modify INVOKEINTERFACE, INVOKESPECIAL, INVOKESTATIC and INVOKEVIRTUAL
* so that a different method is invoked. The class name in the operand
* of these instructions might be a subclass of the target class specified
* by <code>classname</code>. This method transforms the instruction
* in that case unless the subclass overrides the target method.
*/
@Override
public int transform(CtClass clazz, int pos, CodeIterator iterator,
ConstPool cp) throws BadBytecode
{<FILL_FUNCTION_BODY>}
private boolean matchClass(String name, ClassPool pool) {
if (classname.equals(name))
return true;
try {
CtClass clazz = pool.get(name);
CtClass declClazz = pool.get(classname);
if (clazz.subtypeOf(declClazz))
try {
CtMethod m = clazz.getMethod(methodname, methodDescriptor);
return m.getDeclaringClass().getName().equals(classname);
}
catch (NotFoundException e) {
// maybe the original method has been removed.
return true;
}
}
catch (NotFoundException e) {
return false;
}
return false;
}
protected int match(int c, int pos, CodeIterator iterator,
int typedesc, ConstPool cp) throws BadBytecode
{
if (newIndex == 0) {
int nt = cp.addNameAndTypeInfo(cp.addUtf8Info(newMethodname),
typedesc);
int ci = cp.addClassInfo(newClassname);
if (c == INVOKEINTERFACE)
newIndex = cp.addInterfaceMethodrefInfo(ci, nt);
else {
if (newMethodIsPrivate && c == INVOKEVIRTUAL)
iterator.writeByte(INVOKESPECIAL, pos);
newIndex = cp.addMethodrefInfo(ci, nt);
}
constPool = cp;
}
iterator.write16bit(newIndex, pos + 1);
return pos;
}
} |
int c = iterator.byteAt(pos);
if (c == INVOKEINTERFACE || c == INVOKESPECIAL
|| c == INVOKESTATIC || c == INVOKEVIRTUAL) {
int index = iterator.u16bitAt(pos + 1);
String cname = cp.eqMember(methodname, methodDescriptor, index);
if (cname != null && matchClass(cname, clazz.getClassPool())) {
int ntinfo = cp.getMemberNameAndType(index);
pos = match(c, pos, iterator,
cp.getNameAndTypeDescriptor(ntinfo), cp);
}
}
return pos;
| 854 | 178 | 1,032 | <methods>public void <init>(org.hotswap.agent.javassist.convert.Transformer) ,public void clean() ,public int extraLocals() ,public int extraStack() ,public org.hotswap.agent.javassist.convert.Transformer getNext() ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.bytecode.CodeAttribute) ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.CtClass, org.hotswap.agent.javassist.bytecode.MethodInfo) throws org.hotswap.agent.javassist.CannotCompileException,public abstract int transform(org.hotswap.agent.javassist.CtClass, int, org.hotswap.agent.javassist.bytecode.CodeIterator, org.hotswap.agent.javassist.bytecode.ConstPool) throws org.hotswap.agent.javassist.CannotCompileException, org.hotswap.agent.javassist.bytecode.BadBytecode<variables>private org.hotswap.agent.javassist.convert.Transformer next |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/convert/TransformFieldAccess.java | TransformFieldAccess | transform | class TransformFieldAccess extends Transformer {
private String newClassname, newFieldname;
private String fieldname;
private CtClass fieldClass;
private boolean isPrivate;
/* cache */
private int newIndex;
private ConstPool constPool;
public TransformFieldAccess(Transformer next, CtField field,
String newClassname, String newFieldname)
{
super(next);
this.fieldClass = field.getDeclaringClass();
this.fieldname = field.getName();
this.isPrivate = Modifier.isPrivate(field.getModifiers());
this.newClassname = newClassname;
this.newFieldname = newFieldname;
this.constPool = null;
}
@Override
public void initialize(ConstPool cp, CodeAttribute attr) {
if (constPool != cp)
newIndex = 0;
}
/**
* Modify GETFIELD, GETSTATIC, PUTFIELD, and PUTSTATIC so that
* a different field is accessed. The new field must be declared
* in a superclass of the class in which the original field is
* declared.
*/
@Override
public int transform(CtClass clazz, int pos,
CodeIterator iterator, ConstPool cp)
{<FILL_FUNCTION_BODY>}
} |
int c = iterator.byteAt(pos);
if (c == GETFIELD || c == GETSTATIC
|| c == PUTFIELD || c == PUTSTATIC) {
int index = iterator.u16bitAt(pos + 1);
String typedesc
= TransformReadField.isField(clazz.getClassPool(), cp,
fieldClass, fieldname, isPrivate, index);
if (typedesc != null) {
if (newIndex == 0) {
int nt = cp.addNameAndTypeInfo(newFieldname,
typedesc);
newIndex = cp.addFieldrefInfo(
cp.addClassInfo(newClassname), nt);
constPool = cp;
}
iterator.write16bit(newIndex, pos + 1);
}
}
return pos;
| 339 | 214 | 553 | <methods>public void <init>(org.hotswap.agent.javassist.convert.Transformer) ,public void clean() ,public int extraLocals() ,public int extraStack() ,public org.hotswap.agent.javassist.convert.Transformer getNext() ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.bytecode.CodeAttribute) ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.CtClass, org.hotswap.agent.javassist.bytecode.MethodInfo) throws org.hotswap.agent.javassist.CannotCompileException,public abstract int transform(org.hotswap.agent.javassist.CtClass, int, org.hotswap.agent.javassist.bytecode.CodeIterator, org.hotswap.agent.javassist.bytecode.ConstPool) throws org.hotswap.agent.javassist.CannotCompileException, org.hotswap.agent.javassist.bytecode.BadBytecode<variables>private org.hotswap.agent.javassist.convert.Transformer next |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/convert/TransformNew.java | TransformNew | transform | class TransformNew extends Transformer {
private int nested;
private String classname, trapClass, trapMethod;
public TransformNew(Transformer next,
String classname, String trapClass, String trapMethod) {
super(next);
this.classname = classname;
this.trapClass = trapClass;
this.trapMethod = trapMethod;
}
@Override
public void initialize(ConstPool cp, CodeAttribute attr) {
nested = 0;
}
/**
* Replace a sequence of
* NEW classname
* DUP
* ...
* INVOKESPECIAL
* with
* NOP
* NOP
* ...
* INVOKESTATIC trapMethod in trapClass
*/
@Override
public int transform(CtClass clazz, int pos, CodeIterator iterator,
ConstPool cp) throws CannotCompileException
{<FILL_FUNCTION_BODY>}
private int computeMethodref(int typedesc, ConstPool cp) {
int classIndex = cp.addClassInfo(trapClass);
int mnameIndex = cp.addUtf8Info(trapMethod);
typedesc = cp.addUtf8Info(
Descriptor.changeReturnType(classname,
cp.getUtf8Info(typedesc)));
return cp.addMethodrefInfo(classIndex,
cp.addNameAndTypeInfo(mnameIndex, typedesc));
}
} |
int index;
int c = iterator.byteAt(pos);
if (c == NEW) {
index = iterator.u16bitAt(pos + 1);
if (cp.getClassInfo(index).equals(classname)) {
if (iterator.byteAt(pos + 3) != DUP)
throw new CannotCompileException(
"NEW followed by no DUP was found");
iterator.writeByte(NOP, pos);
iterator.writeByte(NOP, pos + 1);
iterator.writeByte(NOP, pos + 2);
iterator.writeByte(NOP, pos + 3);
++nested;
StackMapTable smt
= (StackMapTable)iterator.get().getAttribute(StackMapTable.tag);
if (smt != null)
smt.removeNew(pos);
StackMap sm
= (StackMap)iterator.get().getAttribute(StackMap.tag);
if (sm != null)
sm.removeNew(pos);
}
}
else if (c == INVOKESPECIAL) {
index = iterator.u16bitAt(pos + 1);
int typedesc = cp.isConstructor(classname, index);
if (typedesc != 0 && nested > 0) {
int methodref = computeMethodref(typedesc, cp);
iterator.writeByte(INVOKESTATIC, pos);
iterator.write16bit(methodref, pos + 1);
--nested;
}
}
return pos;
| 379 | 397 | 776 | <methods>public void <init>(org.hotswap.agent.javassist.convert.Transformer) ,public void clean() ,public int extraLocals() ,public int extraStack() ,public org.hotswap.agent.javassist.convert.Transformer getNext() ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.bytecode.CodeAttribute) ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.CtClass, org.hotswap.agent.javassist.bytecode.MethodInfo) throws org.hotswap.agent.javassist.CannotCompileException,public abstract int transform(org.hotswap.agent.javassist.CtClass, int, org.hotswap.agent.javassist.bytecode.CodeIterator, org.hotswap.agent.javassist.bytecode.ConstPool) throws org.hotswap.agent.javassist.CannotCompileException, org.hotswap.agent.javassist.bytecode.BadBytecode<variables>private org.hotswap.agent.javassist.convert.Transformer next |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/convert/TransformNewClass.java | TransformNewClass | transform | class TransformNewClass extends Transformer {
private int nested;
private String classname, newClassName;
private int newClassIndex, newMethodNTIndex, newMethodIndex;
public TransformNewClass(Transformer next,
String classname, String newClassName) {
super(next);
this.classname = classname;
this.newClassName = newClassName;
}
@Override
public void initialize(ConstPool cp, CodeAttribute attr) {
nested = 0;
newClassIndex = newMethodNTIndex = newMethodIndex = 0;
}
/**
* Modifies a sequence of
* NEW classname
* DUP
* ...
* INVOKESPECIAL classname:method
*/
@Override
public int transform(CtClass clazz, int pos, CodeIterator iterator,
ConstPool cp) throws CannotCompileException
{<FILL_FUNCTION_BODY>}
} |
int index;
int c = iterator.byteAt(pos);
if (c == NEW) {
index = iterator.u16bitAt(pos + 1);
if (cp.getClassInfo(index).equals(classname)) {
if (iterator.byteAt(pos + 3) != DUP)
throw new CannotCompileException(
"NEW followed by no DUP was found");
if (newClassIndex == 0)
newClassIndex = cp.addClassInfo(newClassName);
iterator.write16bit(newClassIndex, pos + 1);
++nested;
}
}
else if (c == INVOKESPECIAL) {
index = iterator.u16bitAt(pos + 1);
int typedesc = cp.isConstructor(classname, index);
if (typedesc != 0 && nested > 0) {
int nt = cp.getMethodrefNameAndType(index);
if (newMethodNTIndex != nt) {
newMethodNTIndex = nt;
newMethodIndex = cp.addMethodrefInfo(newClassIndex, nt);
}
iterator.write16bit(newMethodIndex, pos + 1);
--nested;
}
}
return pos;
| 246 | 326 | 572 | <methods>public void <init>(org.hotswap.agent.javassist.convert.Transformer) ,public void clean() ,public int extraLocals() ,public int extraStack() ,public org.hotswap.agent.javassist.convert.Transformer getNext() ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.bytecode.CodeAttribute) ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.CtClass, org.hotswap.agent.javassist.bytecode.MethodInfo) throws org.hotswap.agent.javassist.CannotCompileException,public abstract int transform(org.hotswap.agent.javassist.CtClass, int, org.hotswap.agent.javassist.bytecode.CodeIterator, org.hotswap.agent.javassist.bytecode.ConstPool) throws org.hotswap.agent.javassist.CannotCompileException, org.hotswap.agent.javassist.bytecode.BadBytecode<variables>private org.hotswap.agent.javassist.convert.Transformer next |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/convert/TransformReadField.java | TransformReadField | transform | class TransformReadField extends Transformer {
protected String fieldname;
protected CtClass fieldClass;
protected boolean isPrivate;
protected String methodClassname, methodName;
public TransformReadField(Transformer next, CtField field,
String methodClassname, String methodName)
{
super(next);
this.fieldClass = field.getDeclaringClass();
this.fieldname = field.getName();
this.methodClassname = methodClassname;
this.methodName = methodName;
this.isPrivate = Modifier.isPrivate(field.getModifiers());
}
static String isField(ClassPool pool, ConstPool cp, CtClass fclass,
String fname, boolean is_private, int index) {
if (!cp.getFieldrefName(index).equals(fname))
return null;
try {
CtClass c = pool.get(cp.getFieldrefClassName(index));
if (c == fclass || (!is_private && isFieldInSuper(c, fclass, fname)))
return cp.getFieldrefType(index);
}
catch (NotFoundException e) {}
return null;
}
static boolean isFieldInSuper(CtClass clazz, CtClass fclass, String fname) {
if (!clazz.subclassOf(fclass))
return false;
try {
CtField f = clazz.getField(fname);
return f.getDeclaringClass() == fclass;
}
catch (NotFoundException e) {}
return false;
}
@Override
public int transform(CtClass tclazz, int pos, CodeIterator iterator,
ConstPool cp) throws BadBytecode
{<FILL_FUNCTION_BODY>}
} |
int c = iterator.byteAt(pos);
if (c == GETFIELD || c == GETSTATIC) {
int index = iterator.u16bitAt(pos + 1);
String typedesc = isField(tclazz.getClassPool(), cp,
fieldClass, fieldname, isPrivate, index);
if (typedesc != null) {
if (c == GETSTATIC) {
iterator.move(pos);
pos = iterator.insertGap(1); // insertGap() may insert 4 bytes.
iterator.writeByte(ACONST_NULL, pos);
pos = iterator.next();
}
String type = "(Ljava/lang/Object;)" + typedesc;
int mi = cp.addClassInfo(methodClassname);
int methodref = cp.addMethodrefInfo(mi, methodName, type);
iterator.writeByte(INVOKESTATIC, pos);
iterator.write16bit(methodref, pos + 1);
return pos;
}
}
return pos;
| 450 | 268 | 718 | <methods>public void <init>(org.hotswap.agent.javassist.convert.Transformer) ,public void clean() ,public int extraLocals() ,public int extraStack() ,public org.hotswap.agent.javassist.convert.Transformer getNext() ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.bytecode.CodeAttribute) ,public void initialize(org.hotswap.agent.javassist.bytecode.ConstPool, org.hotswap.agent.javassist.CtClass, org.hotswap.agent.javassist.bytecode.MethodInfo) throws org.hotswap.agent.javassist.CannotCompileException,public abstract int transform(org.hotswap.agent.javassist.CtClass, int, org.hotswap.agent.javassist.bytecode.CodeIterator, org.hotswap.agent.javassist.bytecode.ConstPool) throws org.hotswap.agent.javassist.CannotCompileException, org.hotswap.agent.javassist.bytecode.BadBytecode<variables>private org.hotswap.agent.javassist.convert.Transformer next |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/convert/TransformWriteField.java | TransformWriteField | transform | class TransformWriteField extends TransformReadField {
public TransformWriteField(Transformer next, CtField field,
String methodClassname, String methodName)
{
super(next, field, methodClassname, methodName);
}
@Override
public int transform(CtClass tclazz, int pos, CodeIterator iterator,
ConstPool cp) throws BadBytecode
{<FILL_FUNCTION_BODY>}
} |
int c = iterator.byteAt(pos);
if (c == PUTFIELD || c == PUTSTATIC) {
int index = iterator.u16bitAt(pos + 1);
String typedesc = isField(tclazz.getClassPool(), cp,
fieldClass, fieldname, isPrivate, index);
if (typedesc != null) {
if (c == PUTSTATIC) {
CodeAttribute ca = iterator.get();
iterator.move(pos);
char c0 = typedesc.charAt(0);
if (c0 == 'J' || c0 == 'D') { // long or double
// insertGap() may insert 4 bytes.
pos = iterator.insertGap(3);
iterator.writeByte(ACONST_NULL, pos);
iterator.writeByte(DUP_X2, pos + 1);
iterator.writeByte(POP, pos + 2);
ca.setMaxStack(ca.getMaxStack() + 2);
}
else {
// insertGap() may insert 4 bytes.
pos = iterator.insertGap(2);
iterator.writeByte(ACONST_NULL, pos);
iterator.writeByte(SWAP, pos + 1);
ca.setMaxStack(ca.getMaxStack() + 1);
}
pos = iterator.next();
}
int mi = cp.addClassInfo(methodClassname);
String type = "(Ljava/lang/Object;" + typedesc + ")V";
int methodref = cp.addMethodrefInfo(mi, methodName, type);
iterator.writeByte(INVOKESTATIC, pos);
iterator.write16bit(methodref, pos + 1);
}
}
return pos;
| 114 | 453 | 567 | <methods>public void <init>(org.hotswap.agent.javassist.convert.Transformer, org.hotswap.agent.javassist.CtField, java.lang.String, java.lang.String) ,public int transform(org.hotswap.agent.javassist.CtClass, int, org.hotswap.agent.javassist.bytecode.CodeIterator, org.hotswap.agent.javassist.bytecode.ConstPool) throws org.hotswap.agent.javassist.bytecode.BadBytecode<variables>protected org.hotswap.agent.javassist.CtClass fieldClass,protected java.lang.String fieldname,protected boolean isPrivate,protected java.lang.String methodClassname,protected java.lang.String methodName |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/expr/Cast.java | Cast | replace | class Cast extends Expr {
/**
* Undocumented constructor. Do not use; internal-use only.
*/
protected Cast(int pos, CodeIterator i, CtClass declaring, MethodInfo m) {
super(pos, i, declaring, m);
}
/**
* Returns the method or constructor containing the type cast
* expression represented by this object.
*/
@Override
public CtBehavior where() { return super.where(); }
/**
* Returns the line number of the source line containing the
* type-cast expression.
*
* @return -1 if this information is not available.
*/
@Override
public int getLineNumber() {
return super.getLineNumber();
}
/**
* Returns the source file containing the type-cast expression.
*
* @return null if this information is not available.
*/
@Override
public String getFileName() {
return super.getFileName();
}
/**
* Returns the <code>CtClass</code> object representing
* the type specified by the cast.
*/
public CtClass getType() throws NotFoundException {
ConstPool cp = getConstPool();
int pos = currentPos;
int index = iterator.u16bitAt(pos + 1);
String name = cp.getClassInfo(index);
return thisClass.getClassPool().getCtClass(name);
}
/**
* Returns the list of exceptions that the expression may throw.
* This list includes both the exceptions that the try-catch statements
* including the expression can catch and the exceptions that
* the throws declaration allows the method to throw.
*/
@Override
public CtClass[] mayThrow() {
return super.mayThrow();
}
/**
* Replaces the explicit cast operator with the bytecode derived from
* the given source text.
*
* <p>$0 is available but the value is <code>null</code>.
*
* @param statement a Java statement except try-catch.
*/
@Override
public void replace(String statement) throws CannotCompileException {<FILL_FUNCTION_BODY>}
/* <type> $proceed(Object obj)
*/
static class ProceedForCast implements ProceedHandler {
int index;
CtClass retType;
ProceedForCast(int i, CtClass t) {
index = i;
retType = t;
}
@Override
public void doit(JvstCodeGen gen, Bytecode bytecode, ASTList args)
throws CompileError
{
if (gen.getMethodArgsLength(args) != 1)
throw new CompileError(Javac.proceedName
+ "() cannot take more than one parameter "
+ "for cast");
gen.atMethodArgs(args, new int[1], new int[1], new String[1]);
bytecode.addOpcode(Opcode.CHECKCAST);
bytecode.addIndex(index);
gen.setType(retType);
}
@Override
public void setReturnType(JvstTypeChecker c, ASTList args)
throws CompileError
{
c.atMethodArgs(args, new int[1], new int[1], new String[1]);
c.setType(retType);
}
}
} |
thisClass.getClassFile(); // to call checkModify().
@SuppressWarnings("unused")
ConstPool constPool = getConstPool();
int pos = currentPos;
int index = iterator.u16bitAt(pos + 1);
Javac jc = new Javac(thisClass);
ClassPool cp = thisClass.getClassPool();
CodeAttribute ca = iterator.get();
try {
CtClass[] params
= new CtClass[] { cp.get(javaLangObject) };
CtClass retType = getType();
int paramVar = ca.getMaxLocals();
jc.recordParams(javaLangObject, params, true, paramVar,
withinStatic());
int retVar = jc.recordReturnType(retType, true);
jc.recordProceed(new ProceedForCast(index, retType));
/* Is $_ included in the source code?
*/
checkResultValue(retType, statement);
Bytecode bytecode = jc.getBytecode();
storeStack(params, true, paramVar, bytecode);
jc.recordLocalVariables(ca, pos);
bytecode.addConstZero(retType);
bytecode.addStore(retVar, retType); // initialize $_
jc.compileStmnt(statement);
bytecode.addLoad(retVar, retType);
replace0(pos, bytecode, 3);
}
catch (CompileError e) { throw new CannotCompileException(e); }
catch (NotFoundException e) { throw new CannotCompileException(e); }
catch (BadBytecode e) {
throw new CannotCompileException("broken method");
}
| 865 | 439 | 1,304 | <methods>public org.hotswap.agent.javassist.CtClass getEnclosingClass() ,public java.lang.String getFileName() ,public int getLineNumber() ,public int indexOfBytecode() ,public org.hotswap.agent.javassist.CtClass[] mayThrow() ,public abstract void replace(java.lang.String) throws org.hotswap.agent.javassist.CannotCompileException,public void replace(java.lang.String, org.hotswap.agent.javassist.expr.ExprEditor) throws org.hotswap.agent.javassist.CannotCompileException,public org.hotswap.agent.javassist.CtBehavior where() <variables>int currentPos,boolean edited,org.hotswap.agent.javassist.bytecode.CodeIterator iterator,static final java.lang.String javaLangObject,int maxLocals,int maxStack,org.hotswap.agent.javassist.CtClass thisClass,org.hotswap.agent.javassist.bytecode.MethodInfo thisMethod |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/expr/ExprEditor.java | LoopContext | loopBody | class LoopContext {
NewOp newList;
int maxLocals;
int maxStack;
LoopContext(int locals) {
maxLocals = locals;
maxStack = 0;
newList = null;
}
void updateMax(int locals, int stack) {
if (maxLocals < locals)
maxLocals = locals;
if (maxStack < stack)
maxStack = stack;
}
}
final boolean loopBody(CodeIterator iterator, CtClass clazz,
MethodInfo minfo, LoopContext context)
throws CannotCompileException
{<FILL_FUNCTION_BODY> |
try {
Expr expr = null;
int pos = iterator.next();
int c = iterator.byteAt(pos);
if (c < Opcode.GETSTATIC) // c < 178
/* skip */;
else if (c < Opcode.NEWARRAY) { // c < 188
if (c == Opcode.INVOKESTATIC
|| c == Opcode.INVOKEINTERFACE
|| c == Opcode.INVOKEVIRTUAL) {
expr = new MethodCall(pos, iterator, clazz, minfo);
edit((MethodCall)expr);
}
else if (c == Opcode.GETFIELD || c == Opcode.GETSTATIC
|| c == Opcode.PUTFIELD
|| c == Opcode.PUTSTATIC) {
expr = new FieldAccess(pos, iterator, clazz, minfo, c);
edit((FieldAccess)expr);
}
else if (c == Opcode.NEW) {
int index = iterator.u16bitAt(pos + 1);
context.newList = new NewOp(context.newList, pos,
minfo.getConstPool().getClassInfo(index));
}
else if (c == Opcode.INVOKESPECIAL) {
NewOp newList = context.newList;
if (newList != null
&& minfo.getConstPool().isConstructor(newList.type,
iterator.u16bitAt(pos + 1)) > 0) {
expr = new NewExpr(pos, iterator, clazz, minfo,
newList.type, newList.pos);
edit((NewExpr)expr);
context.newList = newList.next;
}
else {
MethodCall mcall = new MethodCall(pos, iterator, clazz, minfo);
if (mcall.getMethodName().equals(MethodInfo.nameInit)) {
ConstructorCall ccall = new ConstructorCall(pos, iterator, clazz, minfo);
expr = ccall;
edit(ccall);
}
else {
expr = mcall;
edit(mcall);
}
}
}
}
else { // c >= 188
if (c == Opcode.NEWARRAY || c == Opcode.ANEWARRAY
|| c == Opcode.MULTIANEWARRAY) {
expr = new NewArray(pos, iterator, clazz, minfo, c);
edit((NewArray)expr);
}
else if (c == Opcode.INSTANCEOF) {
expr = new Instanceof(pos, iterator, clazz, minfo);
edit((Instanceof)expr);
}
else if (c == Opcode.CHECKCAST) {
expr = new Cast(pos, iterator, clazz, minfo);
edit((Cast)expr);
}
}
if (expr != null && expr.edited()) {
context.updateMax(expr.locals(), expr.stack());
return true;
}
return false;
}
catch (BadBytecode e) {
throw new CannotCompileException(e);
}
| 169 | 818 | 987 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/expr/FieldAccess.java | ProceedForWrite | doit | class ProceedForWrite implements ProceedHandler {
CtClass fieldType;
int opcode;
int targetVar, index;
ProceedForWrite(CtClass type, int op, int i, int var) {
fieldType = type;
targetVar = var;
opcode = op;
index = i;
}
@Override
public void doit(JvstCodeGen gen, Bytecode bytecode, ASTList args)
throws CompileError
{<FILL_FUNCTION_BODY>}
@Override
public void setReturnType(JvstTypeChecker c, ASTList args)
throws CompileError
{
c.atMethodArgs(args, new int[1], new int[1], new String[1]);
c.setType(CtClass.voidType);
c.addNullIfVoid();
}
} |
if (gen.getMethodArgsLength(args) != 1)
throw new CompileError(Javac.proceedName
+ "() cannot take more than one parameter "
+ "for field writing");
int stack;
if (isStatic(opcode))
stack = 0;
else {
stack = -1;
bytecode.addAload(targetVar);
}
gen.atMethodArgs(args, new int[1], new int[1], new String[1]);
gen.doNumCast(fieldType);
if (fieldType instanceof CtPrimitiveType)
stack -= ((CtPrimitiveType)fieldType).getDataSize();
else
--stack;
bytecode.add(opcode);
bytecode.addIndex(index);
bytecode.growStack(stack);
gen.setType(CtClass.voidType);
gen.addNullIfVoid();
| 226 | 235 | 461 | <methods>public org.hotswap.agent.javassist.CtClass getEnclosingClass() ,public java.lang.String getFileName() ,public int getLineNumber() ,public int indexOfBytecode() ,public org.hotswap.agent.javassist.CtClass[] mayThrow() ,public abstract void replace(java.lang.String) throws org.hotswap.agent.javassist.CannotCompileException,public void replace(java.lang.String, org.hotswap.agent.javassist.expr.ExprEditor) throws org.hotswap.agent.javassist.CannotCompileException,public org.hotswap.agent.javassist.CtBehavior where() <variables>int currentPos,boolean edited,org.hotswap.agent.javassist.bytecode.CodeIterator iterator,static final java.lang.String javaLangObject,int maxLocals,int maxStack,org.hotswap.agent.javassist.CtClass thisClass,org.hotswap.agent.javassist.bytecode.MethodInfo thisMethod |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/expr/Handler.java | Handler | getType | class Handler extends Expr {
private static String EXCEPTION_NAME = "$1";
private ExceptionTable etable;
private int index;
/**
* Undocumented constructor. Do not use; internal-use only.
*/
protected Handler(ExceptionTable et, int nth,
CodeIterator it, CtClass declaring, MethodInfo m) {
super(et.handlerPc(nth), it, declaring, m);
etable = et;
index = nth;
}
/**
* Returns the method or constructor containing the catch clause.
*/
@Override
public CtBehavior where() { return super.where(); }
/**
* Returns the source line number of the catch clause.
*
* @return -1 if this information is not available.
*/
@Override
public int getLineNumber() {
return super.getLineNumber();
}
/**
* Returns the source file containing the catch clause.
*
* @return null if this information is not available.
*/
@Override
public String getFileName() {
return super.getFileName();
}
/**
* Returns the list of exceptions that the catch clause may throw.
*/
@Override
public CtClass[] mayThrow() {
return super.mayThrow();
}
/**
* Returns the type handled by the catch clause.
* If this is a <code>finally</code> block, <code>null</code> is returned.
*/
public CtClass getType() throws NotFoundException {<FILL_FUNCTION_BODY>}
/**
* Returns true if this is a <code>finally</code> block.
*/
public boolean isFinally() {
return etable.catchType(index) == 0;
}
/**
* This method has not been implemented yet.
*
* @param statement a Java statement except try-catch.
*/
@Override
public void replace(String statement) throws CannotCompileException {
throw new RuntimeException("not implemented yet");
}
/**
* Inserts bytecode at the beginning of the catch clause.
* The caught exception is stored in <code>$1</code>.
*
* @param src the source code representing the inserted bytecode.
* It must be a single statement or block.
*/
public void insertBefore(String src) throws CannotCompileException {
edited = true;
@SuppressWarnings("unused")
ConstPool cp = getConstPool();
CodeAttribute ca = iterator.get();
Javac jv = new Javac(thisClass);
Bytecode b = jv.getBytecode();
b.setStackDepth(1);
b.setMaxLocals(ca.getMaxLocals());
try {
CtClass type = getType();
int var = jv.recordVariable(type, EXCEPTION_NAME);
jv.recordReturnType(type, false);
b.addAstore(var);
jv.compileStmnt(src);
b.addAload(var);
int oldHandler = etable.handlerPc(index);
b.addOpcode(Opcode.GOTO);
b.addIndex(oldHandler - iterator.getCodeLength()
- b.currentPc() + 1);
maxStack = b.getMaxStack();
maxLocals = b.getMaxLocals();
int pos = iterator.append(b.get());
iterator.append(b.getExceptionTable(), pos);
etable.setHandlerPc(index, pos);
}
catch (NotFoundException e) {
throw new CannotCompileException(e);
}
catch (CompileError e) {
throw new CannotCompileException(e);
}
}
} |
int type = etable.catchType(index);
if (type == 0)
return null;
ConstPool cp = getConstPool();
String name = cp.getClassInfo(type);
return thisClass.getClassPool().getCtClass(name);
| 980 | 69 | 1,049 | <methods>public org.hotswap.agent.javassist.CtClass getEnclosingClass() ,public java.lang.String getFileName() ,public int getLineNumber() ,public int indexOfBytecode() ,public org.hotswap.agent.javassist.CtClass[] mayThrow() ,public abstract void replace(java.lang.String) throws org.hotswap.agent.javassist.CannotCompileException,public void replace(java.lang.String, org.hotswap.agent.javassist.expr.ExprEditor) throws org.hotswap.agent.javassist.CannotCompileException,public org.hotswap.agent.javassist.CtBehavior where() <variables>int currentPos,boolean edited,org.hotswap.agent.javassist.bytecode.CodeIterator iterator,static final java.lang.String javaLangObject,int maxLocals,int maxStack,org.hotswap.agent.javassist.CtClass thisClass,org.hotswap.agent.javassist.bytecode.MethodInfo thisMethod |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/expr/Instanceof.java | Instanceof | replace | class Instanceof extends Expr {
/**
* Undocumented constructor. Do not use; internal-use only.
*/
protected Instanceof(int pos, CodeIterator i, CtClass declaring,
MethodInfo m) {
super(pos, i, declaring, m);
}
/**
* Returns the method or constructor containing the instanceof
* expression represented by this object.
*/
@Override
public CtBehavior where() { return super.where(); }
/**
* Returns the line number of the source line containing the
* instanceof expression.
*
* @return -1 if this information is not available.
*/
@Override
public int getLineNumber() {
return super.getLineNumber();
}
/**
* Returns the source file containing the
* instanceof expression.
*
* @return null if this information is not available.
*/
@Override
public String getFileName() {
return super.getFileName();
}
/**
* Returns the <code>CtClass</code> object representing
* the type name on the right hand side
* of the instanceof operator.
*/
public CtClass getType() throws NotFoundException {
ConstPool cp = getConstPool();
int pos = currentPos;
int index = iterator.u16bitAt(pos + 1);
String name = cp.getClassInfo(index);
return thisClass.getClassPool().getCtClass(name);
}
/**
* Returns the list of exceptions that the expression may throw.
* This list includes both the exceptions that the try-catch statements
* including the expression can catch and the exceptions that
* the throws declaration allows the method to throw.
*/
@Override
public CtClass[] mayThrow() {
return super.mayThrow();
}
/**
* Replaces the instanceof operator with the bytecode derived from
* the given source text.
*
* <p>$0 is available but the value is <code>null</code>.
*
* @param statement a Java statement except try-catch.
*/
@Override
public void replace(String statement) throws CannotCompileException {<FILL_FUNCTION_BODY>}
/* boolean $proceed(Object obj)
*/
static class ProceedForInstanceof implements ProceedHandler {
int index;
ProceedForInstanceof(int i) {
index = i;
}
@Override
public void doit(JvstCodeGen gen, Bytecode bytecode, ASTList args)
throws CompileError
{
if (gen.getMethodArgsLength(args) != 1)
throw new CompileError(Javac.proceedName
+ "() cannot take more than one parameter "
+ "for instanceof");
gen.atMethodArgs(args, new int[1], new int[1], new String[1]);
bytecode.addOpcode(Opcode.INSTANCEOF);
bytecode.addIndex(index);
gen.setType(CtClass.booleanType);
}
@Override
public void setReturnType(JvstTypeChecker c, ASTList args)
throws CompileError
{
c.atMethodArgs(args, new int[1], new int[1], new String[1]);
c.setType(CtClass.booleanType);
}
}
} |
thisClass.getClassFile(); // to call checkModify().
@SuppressWarnings("unused")
ConstPool constPool = getConstPool();
int pos = currentPos;
int index = iterator.u16bitAt(pos + 1);
Javac jc = new Javac(thisClass);
ClassPool cp = thisClass.getClassPool();
CodeAttribute ca = iterator.get();
try {
CtClass[] params
= new CtClass[] { cp.get(javaLangObject) };
CtClass retType = CtClass.booleanType;
int paramVar = ca.getMaxLocals();
jc.recordParams(javaLangObject, params, true, paramVar,
withinStatic());
int retVar = jc.recordReturnType(retType, true);
jc.recordProceed(new ProceedForInstanceof(index));
// because $type is not the return type...
jc.recordType(getType());
/* Is $_ included in the source code?
*/
checkResultValue(retType, statement);
Bytecode bytecode = jc.getBytecode();
storeStack(params, true, paramVar, bytecode);
jc.recordLocalVariables(ca, pos);
bytecode.addConstZero(retType);
bytecode.addStore(retVar, retType); // initialize $_
jc.compileStmnt(statement);
bytecode.addLoad(retVar, retType);
replace0(pos, bytecode, 3);
}
catch (CompileError e) { throw new CannotCompileException(e); }
catch (NotFoundException e) { throw new CannotCompileException(e); }
catch (BadBytecode e) {
throw new CannotCompileException("broken method");
}
| 865 | 465 | 1,330 | <methods>public org.hotswap.agent.javassist.CtClass getEnclosingClass() ,public java.lang.String getFileName() ,public int getLineNumber() ,public int indexOfBytecode() ,public org.hotswap.agent.javassist.CtClass[] mayThrow() ,public abstract void replace(java.lang.String) throws org.hotswap.agent.javassist.CannotCompileException,public void replace(java.lang.String, org.hotswap.agent.javassist.expr.ExprEditor) throws org.hotswap.agent.javassist.CannotCompileException,public org.hotswap.agent.javassist.CtBehavior where() <variables>int currentPos,boolean edited,org.hotswap.agent.javassist.bytecode.CodeIterator iterator,static final java.lang.String javaLangObject,int maxLocals,int maxStack,org.hotswap.agent.javassist.CtClass thisClass,org.hotswap.agent.javassist.bytecode.MethodInfo thisMethod |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/expr/MethodCall.java | MethodCall | replace | class MethodCall extends Expr {
/**
* Undocumented constructor. Do not use; internal-use only.
*/
protected MethodCall(int pos, CodeIterator i, CtClass declaring,
MethodInfo m) {
super(pos, i, declaring, m);
}
private int getNameAndType(ConstPool cp) {
int pos = currentPos;
int c = iterator.byteAt(pos);
int index = iterator.u16bitAt(pos + 1);
if (c == INVOKEINTERFACE)
return cp.getInterfaceMethodrefNameAndType(index);
return cp.getMethodrefNameAndType(index);
}
/**
* Returns the method or constructor containing the method-call
* expression represented by this object.
*/
@Override
public CtBehavior where() { return super.where(); }
/**
* Returns the line number of the source line containing the
* method call.
*
* @return -1 if this information is not available.
*/
@Override
public int getLineNumber() {
return super.getLineNumber();
}
/**
* Returns the source file containing the method call.
*
* @return null if this information is not available.
*/
@Override
public String getFileName() {
return super.getFileName();
}
/**
* Returns the class of the target object,
* which the method is called on.
*/
protected CtClass getCtClass() throws NotFoundException {
return thisClass.getClassPool().get(getClassName());
}
/**
* Returns the class name of the target object,
* which the method is called on.
*/
public String getClassName() {
String cname;
ConstPool cp = getConstPool();
int pos = currentPos;
int c = iterator.byteAt(pos);
int index = iterator.u16bitAt(pos + 1);
if (c == INVOKEINTERFACE)
cname = cp.getInterfaceMethodrefClassName(index);
else
cname = cp.getMethodrefClassName(index);
if (cname.charAt(0) == '[')
cname = Descriptor.toClassName(cname);
return cname;
}
/**
* Returns the name of the called method.
*/
public String getMethodName() {
ConstPool cp = getConstPool();
int nt = getNameAndType(cp);
return cp.getUtf8Info(cp.getNameAndTypeName(nt));
}
/**
* Returns the called method.
*/
public CtMethod getMethod() throws NotFoundException {
return getCtClass().getMethod(getMethodName(), getSignature());
}
/**
* Returns the method signature (the parameter types
* and the return type).
* The method signature is represented by a character string
* called method descriptor, which is defined in the JVM specification.
*
* @see javassist.CtBehavior#getSignature()
* @see javassist.bytecode.Descriptor
* @since 3.1
*/
public String getSignature() {
ConstPool cp = getConstPool();
int nt = getNameAndType(cp);
return cp.getUtf8Info(cp.getNameAndTypeDescriptor(nt));
}
/**
* Returns the list of exceptions that the expression may throw.
* This list includes both the exceptions that the try-catch statements
* including the expression can catch and the exceptions that
* the throws declaration allows the method to throw.
*/
@Override
public CtClass[] mayThrow() {
return super.mayThrow();
}
/**
* Returns true if the called method is of a superclass of the current
* class.
*/
public boolean isSuper() {
return iterator.byteAt(currentPos) == INVOKESPECIAL
&& !where().getDeclaringClass().getName().equals(getClassName());
}
/*
* Returns the parameter types of the called method.
public CtClass[] getParameterTypes() throws NotFoundException {
return Descriptor.getParameterTypes(getMethodDesc(),
thisClass.getClassPool());
}
*/
/*
* Returns the return type of the called method.
public CtClass getReturnType() throws NotFoundException {
return Descriptor.getReturnType(getMethodDesc(),
thisClass.getClassPool());
}
*/
/**
* Replaces the method call with the bytecode derived from
* the given source text.
*
* <p>$0 is available even if the called method is static.
*
* @param statement a Java statement except try-catch.
*/
@Override
public void replace(String statement) throws CannotCompileException {<FILL_FUNCTION_BODY>}
} |
thisClass.getClassFile(); // to call checkModify().
ConstPool constPool = getConstPool();
int pos = currentPos;
int index = iterator.u16bitAt(pos + 1);
String classname, methodname, signature;
int opcodeSize;
int c = iterator.byteAt(pos);
if (c == INVOKEINTERFACE) {
opcodeSize = 5;
classname = constPool.getInterfaceMethodrefClassName(index);
methodname = constPool.getInterfaceMethodrefName(index);
signature = constPool.getInterfaceMethodrefType(index);
}
else if (c == INVOKESTATIC
|| c == INVOKESPECIAL || c == INVOKEVIRTUAL) {
opcodeSize = 3;
classname = constPool.getMethodrefClassName(index);
methodname = constPool.getMethodrefName(index);
signature = constPool.getMethodrefType(index);
}
else
throw new CannotCompileException("not method invocation");
Javac jc = new Javac(thisClass);
ClassPool cp = thisClass.getClassPool();
CodeAttribute ca = iterator.get();
try {
CtClass[] params = Descriptor.getParameterTypes(signature, cp);
CtClass retType = Descriptor.getReturnType(signature, cp);
int paramVar = ca.getMaxLocals();
jc.recordParams(classname, params,
true, paramVar, withinStatic());
int retVar = jc.recordReturnType(retType, true);
if (c == INVOKESTATIC)
jc.recordStaticProceed(classname, methodname);
else if (c == INVOKESPECIAL)
jc.recordSpecialProceed(Javac.param0Name, classname,
methodname, signature, index);
else
jc.recordProceed(Javac.param0Name, methodname);
/* Is $_ included in the source code?
*/
checkResultValue(retType, statement);
Bytecode bytecode = jc.getBytecode();
storeStack(params, c == INVOKESTATIC, paramVar, bytecode);
jc.recordLocalVariables(ca, pos);
if (retType != CtClass.voidType) {
bytecode.addConstZero(retType);
bytecode.addStore(retVar, retType); // initialize $_
}
jc.compileStmnt(statement);
if (retType != CtClass.voidType)
bytecode.addLoad(retVar, retType);
replace0(pos, bytecode, opcodeSize);
}
catch (CompileError e) { throw new CannotCompileException(e); }
catch (NotFoundException e) { throw new CannotCompileException(e); }
catch (BadBytecode e) {
throw new CannotCompileException("broken method");
}
| 1,260 | 756 | 2,016 | <methods>public org.hotswap.agent.javassist.CtClass getEnclosingClass() ,public java.lang.String getFileName() ,public int getLineNumber() ,public int indexOfBytecode() ,public org.hotswap.agent.javassist.CtClass[] mayThrow() ,public abstract void replace(java.lang.String) throws org.hotswap.agent.javassist.CannotCompileException,public void replace(java.lang.String, org.hotswap.agent.javassist.expr.ExprEditor) throws org.hotswap.agent.javassist.CannotCompileException,public org.hotswap.agent.javassist.CtBehavior where() <variables>int currentPos,boolean edited,org.hotswap.agent.javassist.bytecode.CodeIterator iterator,static final java.lang.String javaLangObject,int maxLocals,int maxStack,org.hotswap.agent.javassist.CtClass thisClass,org.hotswap.agent.javassist.bytecode.MethodInfo thisMethod |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/runtime/Desc.java | Desc | getClassType | class Desc {
/**
* Specifies how a <code>java.lang.Class</code> object is loaded.
*
* <p>If true, it is loaded by:
* <pre>Thread.currentThread().getContextClassLoader().loadClass()</pre>
* <p>If false, it is loaded by <code>Class.forName()</code>.
* The default value is false.
*/
public static boolean useContextClassLoader = false;
private static final ThreadLocal<Boolean> USE_CONTEXT_CLASS_LOADER_LOCALLY = new ThreadLocal<Boolean>() {
@Override
protected Boolean initialValue() {
return false;
}
};
public static void setUseContextClassLoaderLocally() {
USE_CONTEXT_CLASS_LOADER_LOCALLY.set(true);
}
public static void resetUseContextClassLoaderLocally() {
USE_CONTEXT_CLASS_LOADER_LOCALLY.remove();
}
private static Class<?> getClassObject(String name)
throws ClassNotFoundException
{
if (useContextClassLoader || USE_CONTEXT_CLASS_LOADER_LOCALLY.get())
return Class.forName(name, true, Thread.currentThread().getContextClassLoader());
return Class.forName(name);
}
/**
* Interprets the given class name.
* It is used for implementing <code>$class</code>.
*/
public static Class<?> getClazz(String name) {
try {
return getClassObject(name);
}
catch (ClassNotFoundException e) {
throw new RuntimeException(
"$class: internal error, could not find class '" + name
+ "' (Desc.useContextClassLoader: "
+ Boolean.toString(useContextClassLoader) + ")", e);
}
}
/**
* Interprets the given type descriptor representing a method
* signature. It is used for implementing <code>$sig</code>.
*/
public static Class<?>[] getParams(String desc) {
if (desc.charAt(0) != '(')
throw new RuntimeException("$sig: internal error");
return getType(desc, desc.length(), 1, 0);
}
/**
* Interprets the given type descriptor.
* It is used for implementing <code>$type</code>.
*/
public static Class<?> getType(String desc) {
Class<?>[] result = getType(desc, desc.length(), 0, 0);
if (result == null || result.length != 1)
throw new RuntimeException("$type: internal error");
return result[0];
}
private static Class<?>[] getType(String desc, int descLen,
int start, int num) {
Class<?> clazz;
if (start >= descLen)
return new Class[num];
char c = desc.charAt(start);
switch (c) {
case 'Z' :
clazz = Boolean.TYPE;
break;
case 'C' :
clazz = Character.TYPE;
break;
case 'B' :
clazz = Byte.TYPE;
break;
case 'S' :
clazz = Short.TYPE;
break;
case 'I' :
clazz = Integer.TYPE;
break;
case 'J' :
clazz = Long.TYPE;
break;
case 'F' :
clazz = Float.TYPE;
break;
case 'D' :
clazz = Double.TYPE;
break;
case 'V' :
clazz = Void.TYPE;
break;
case 'L' :
case '[' :
return getClassType(desc, descLen, start, num);
default :
return new Class[num];
}
Class<?>[] result = getType(desc, descLen, start + 1, num + 1);
result[num] = clazz;
return result;
}
private static Class<?>[] getClassType(String desc, int descLen,
int start, int num) {<FILL_FUNCTION_BODY>}
} |
int end = start;
while (desc.charAt(end) == '[')
++end;
if (desc.charAt(end) == 'L') {
end = desc.indexOf(';', end);
if (end < 0)
throw new IndexOutOfBoundsException("bad descriptor");
}
String cname;
if (desc.charAt(start) == 'L')
cname = desc.substring(start + 1, end);
else
cname = desc.substring(start, end + 1);
Class<?>[] result = getType(desc, descLen, end + 1, num + 1);
try {
result[num] = getClassObject(cname.replace('/', '.'));
}
catch (ClassNotFoundException e) {
// "new RuntimeException(e)" is not available in JDK 1.3.
throw new RuntimeException(e.getMessage());
}
return result;
| 1,081 | 243 | 1,324 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/scopedpool/ScopedClassPoolRepositoryImpl.java | ScopedClassPoolRepositoryImpl | registerClassLoader | class ScopedClassPoolRepositoryImpl implements ScopedClassPoolRepository {
/** The instance */
private static final ScopedClassPoolRepositoryImpl instance = new ScopedClassPoolRepositoryImpl();
/** Whether to prune */
private boolean prune = true;
/** Whether to prune when added to the classpool's cache */
boolean pruneWhenCached;
/** The registered classloaders */
protected Map<ClassLoader,ScopedClassPool> registeredCLs = Collections
.synchronizedMap(new WeakHashMap<ClassLoader,ScopedClassPool>());
/** The default class pool */
protected ClassPool classpool;
/** The factory for creating class pools */
protected ScopedClassPoolFactory factory = new ScopedClassPoolFactoryImpl();
/**
* Get the instance.
*
* @return the instance.
*/
public static ScopedClassPoolRepository getInstance() {
return instance;
}
/**
* Singleton.
*/
private ScopedClassPoolRepositoryImpl() {
classpool = ClassPool.getDefault();
// FIXME This doesn't look correct
ClassLoader cl = Thread.currentThread().getContextClassLoader();
classpool.insertClassPath(new LoaderClassPath(cl));
}
/**
* Returns the value of the prune attribute.
*
* @return the prune.
*/
@Override
public boolean isPrune() {
return prune;
}
/**
* Set the prune attribute.
*
* @param prune a new value.
*/
@Override
public void setPrune(boolean prune) {
this.prune = prune;
}
/**
* Create a scoped classpool.
*
* @param cl the classloader.
* @param src the original classpool.
* @return the classpool
*/
@Override
public ScopedClassPool createScopedClassPool(ClassLoader cl, ClassPool src) {
return factory.create(cl, src, this);
}
@Override
public ClassPool findClassPool(ClassLoader cl) {
if (cl == null)
return registerClassLoader(ClassLoader.getSystemClassLoader());
return registerClassLoader(cl);
}
/**
* Register a classloader.
*
* @param ucl the classloader.
* @return the classpool
*/
@Override
public ClassPool registerClassLoader(ClassLoader ucl) {<FILL_FUNCTION_BODY>}
/**
* Get the registered classloaders.
*/
@Override
public Map<ClassLoader,ScopedClassPool> getRegisteredCLs() {
clearUnregisteredClassLoaders();
return registeredCLs;
}
/**
* This method will check to see if a register classloader has been
* undeployed (as in JBoss)
*/
@Override
public void clearUnregisteredClassLoaders() {
List<ClassLoader> toUnregister = null;
synchronized (registeredCLs) {
for (Map.Entry<ClassLoader,ScopedClassPool> reg:registeredCLs.entrySet()) {
if (reg.getValue().isUnloadedClassLoader()) {
ClassLoader cl = reg.getValue().getClassLoader();
if (cl != null) {
if (toUnregister == null)
toUnregister = new ArrayList<ClassLoader>();
toUnregister.add(cl);
}
registeredCLs.remove(reg.getKey());
}
}
if (toUnregister != null)
for (ClassLoader cl:toUnregister)
unregisterClassLoader(cl);
}
}
@Override
public void unregisterClassLoader(ClassLoader cl) {
synchronized (registeredCLs) {
ScopedClassPool pool = registeredCLs.remove(cl);
if (pool != null)
pool.close();
}
}
public void insertDelegate(ScopedClassPoolRepository delegate) {
// Noop - this is the end
}
@Override
public void setClassPoolFactory(ScopedClassPoolFactory factory) {
this.factory = factory;
}
@Override
public ScopedClassPoolFactory getClassPoolFactory() {
return factory;
}
} |
synchronized (registeredCLs) {
// FIXME: Probably want to take this method out later
// so that AOP framework can be independent of JMX
// This is in here so that we can remove a UCL from the ClassPool as
// a
// ClassPool.classpath
if (registeredCLs.containsKey(ucl)) {
return registeredCLs.get(ucl);
}
ScopedClassPool pool = createScopedClassPool(ucl, classpool);
registeredCLs.put(ucl, pool);
return pool;
}
| 1,106 | 144 | 1,250 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/tools/Dump.java | Dump | main | class Dump {
private Dump() {}
/**
* Main method.
*
* @param args <code>args[0]</code> is the class file name.
*/
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
} |
if (args.length != 1) {
System.err.println("Usage: java Dump <class file name>");
return;
}
DataInputStream in = new DataInputStream(
new FileInputStream(args[0]));
ClassFile w = new ClassFile(in);
PrintWriter out = new PrintWriter(System.out, true);
out.println("*** constant pool ***");
w.getConstPool().print(out);
out.println();
out.println("*** members ***");
ClassFilePrinter.print(w, out);
| 80 | 143 | 223 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/tools/framedump.java | framedump | main | class framedump {
private framedump() {}
/**
* Main method.
*
* @param args <code>args[0]</code> is the class file name.
*/
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
} |
if (args.length != 1) {
System.err.println("Usage: java javassist.tools.framedump <fully-qualified class name>");
return;
}
ClassPool pool = ClassPool.getDefault();
CtClass clazz = pool.get(args[0]);
System.out.println("Frame Dump of " + clazz.getName() + ":");
FramePrinter.print(clazz, System.out);
| 81 | 119 | 200 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/tools/reflect/Compiler.java | Compiler | parse | class Compiler {
public static void main(String[] args) throws Exception {
if (args.length == 0) {
help(System.err);
return;
}
CompiledClass[] entries = new CompiledClass[args.length];
int n = parse(args, entries);
if (n < 1) {
System.err.println("bad parameter.");
return;
}
processClasses(entries, n);
}
private static void processClasses(CompiledClass[] entries, int n)
throws Exception
{
Reflection implementor = new Reflection();
ClassPool pool = ClassPool.getDefault();
implementor.start(pool);
for (int i = 0; i < n; ++i) {
CtClass c = pool.get(entries[i].classname);
if (entries[i].metaobject != null
|| entries[i].classobject != null) {
String metaobj, classobj;
if (entries[i].metaobject == null)
metaobj = "org.hotswap.agent.javassist.tools.reflect.Metaobject";
else
metaobj = entries[i].metaobject;
if (entries[i].classobject == null)
classobj = "org.hotswap.agent.javassist.tools.reflect.ClassMetaobject";
else
classobj = entries[i].classobject;
if (!implementor.makeReflective(c, pool.get(metaobj),
pool.get(classobj)))
System.err.println("Warning: " + c.getName()
+ " is reflective. It was not changed.");
System.err.println(c.getName() + ": " + metaobj + ", "
+ classobj);
}
else
System.err.println(c.getName() + ": not reflective");
}
for (int i = 0; i < n; ++i) {
implementor.onLoad(pool, entries[i].classname);
pool.get(entries[i].classname).writeFile();
}
}
private static int parse(String[] args, CompiledClass[] result) {<FILL_FUNCTION_BODY>}
private static void help(PrintStream out) {
out.println("Usage: java javassist.tools.reflect.Compiler");
out.println(" (<class> [-m <metaobject>] [-c <class metaobject>])+");
}
} |
int n = -1;
for (int i = 0; i < args.length; ++i) {
String a = args[i];
if (a.equals("-m"))
if (n < 0 || i + 1 > args.length)
return -1;
else
result[n].metaobject = args[++i];
else if (a.equals("-c"))
if (n < 0 || i + 1 > args.length)
return -1;
else
result[n].classobject = args[++i];
else if (a.charAt(0) == '-')
return -1;
else {
CompiledClass cc = new CompiledClass();
cc.classname = a;
cc.metaobject = null;
cc.classobject = null;
result[++n] = cc;
}
}
return n + 1;
| 635 | 228 | 863 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/tools/reflect/Metaobject.java | Metaobject | getMethodName | class Metaobject implements Serializable {
/** default serialVersionUID */
private static final long serialVersionUID = 1L;
protected ClassMetaobject classmetaobject;
protected Metalevel baseobject;
protected Method[] methods;
/**
* Constructs a <code>Metaobject</code>. The metaobject is
* constructed before the constructor is called on the base-level
* object.
*
* @param self the object that this metaobject is associated with.
* @param args the parameters passed to the constructor of
* <code>self</code>.
*/
public Metaobject(Object self, Object[] args) {
baseobject = (Metalevel)self;
classmetaobject = baseobject._getClass();
methods = classmetaobject.getReflectiveMethods();
}
/**
* Constructs a <code>Metaobject</code> without initialization.
* If calling this constructor, a subclass should be responsible
* for initialization.
*/
protected Metaobject() {
baseobject = null;
classmetaobject = null;
methods = null;
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(baseobject);
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
baseobject = (Metalevel)in.readObject();
classmetaobject = baseobject._getClass();
methods = classmetaobject.getReflectiveMethods();
}
/**
* Obtains the class metaobject associated with this metaobject.
*
* @see javassist.tools.reflect.ClassMetaobject
*/
public final ClassMetaobject getClassMetaobject() {
return classmetaobject;
}
/**
* Obtains the object controlled by this metaobject.
*/
public final Object getObject() {
return baseobject;
}
/**
* Changes the object controlled by this metaobject.
*
* @param self the object
*/
public final void setObject(Object self) {
baseobject = (Metalevel)self;
classmetaobject = baseobject._getClass();
methods = classmetaobject.getReflectiveMethods();
// call _setMetaobject() after the metaobject is settled.
baseobject._setMetaobject(this);
}
/**
* Returns the name of the method specified
* by <code>identifier</code>.
*/
public final String getMethodName(int identifier) {<FILL_FUNCTION_BODY>}
/**
* Returns an array of <code>Class</code> objects representing the
* formal parameter types of the method specified
* by <code>identifier</code>.
*/
public final Class<?>[] getParameterTypes(int identifier) {
return methods[identifier].getParameterTypes();
}
/**
* Returns a <code>Class</code> objects representing the
* return type of the method specified by <code>identifier</code>.
*/
public final Class<?> getReturnType(int identifier) {
return methods[identifier].getReturnType();
}
/**
* Is invoked when public fields of the base-level
* class are read and the runtime system intercepts it.
* This method simply returns the value of the field.
*
* <p>Every subclass of this class should redefine this method.
*/
public Object trapFieldRead(String name) {
Class<?> jc = getClassMetaobject().getJavaClass();
try {
return jc.getField(name).get(getObject());
}
catch (NoSuchFieldException e) {
throw new RuntimeException(e.toString());
}
catch (IllegalAccessException e) {
throw new RuntimeException(e.toString());
}
}
/**
* Is invoked when public fields of the base-level
* class are modified and the runtime system intercepts it.
* This method simply sets the field to the given value.
*
* <p>Every subclass of this class should redefine this method.
*/
public void trapFieldWrite(String name, Object value) {
Class<?> jc = getClassMetaobject().getJavaClass();
try {
jc.getField(name).set(getObject(), value);
}
catch (NoSuchFieldException e) {
throw new RuntimeException(e.toString());
}
catch (IllegalAccessException e) {
throw new RuntimeException(e.toString());
}
}
/**
* Is invoked when base-level method invocation is intercepted.
* This method simply executes the intercepted method invocation
* with the original parameters and returns the resulting value.
*
* <p>Every subclass of this class should redefine this method.
*
* <p>Note: this method is not invoked if the base-level method
* is invoked by a constructor in the super class. For example,
*
* <pre>
* abstract class A {
* abstract void initialize();
* A() {
* initialize(); // not intercepted
* }
* }
*
* class B extends A {
* void initialize() { System.out.println("initialize()"); }
* B() {
* super();
* initialize(); // intercepted
* }
* }</pre>
*
* <p>if an instance of B is created,
* the invocation of initialize() in B is intercepted only once.
* The first invocation by the constructor in A is not intercepted.
* This is because the link between a base-level object and a
* metaobject is not created until the execution of a
* constructor of the super class finishes.
*/
public Object trapMethodcall(int identifier, Object[] args)
throws Throwable
{
try {
return methods[identifier].invoke(getObject(), args);
}
catch (java.lang.reflect.InvocationTargetException e) {
throw e.getTargetException();
}
catch (java.lang.IllegalAccessException e) {
throw new CannotInvokeException(e);
}
}
} |
String mname = methods[identifier].getName();
int j = ClassMetaobject.methodPrefixLen;
for (;;) {
char c = mname.charAt(j++);
if (c < '0' || '9' < c)
break;
}
return mname.substring(j);
| 1,592 | 83 | 1,675 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/tools/reflect/Sample.java | Sample | trap | class Sample {
private Metaobject _metaobject;
private static ClassMetaobject _classobject;
public Object trap(Object[] args, int identifier) throws Throwable {<FILL_FUNCTION_BODY>}
public static Object trapStatic(Object[] args, int identifier)
throws Throwable
{
return _classobject.trapMethodcall(identifier, args);
}
public static Object trapRead(Object[] args, String name) {
if (args[0] == null)
return _classobject.trapFieldRead(name);
return ((Metalevel)args[0])._getMetaobject().trapFieldRead(name);
}
public static Object trapWrite(Object[] args, String name) {
Metalevel base = (Metalevel)args[0];
if (base == null)
_classobject.trapFieldWrite(name, args[1]);
else
base._getMetaobject().trapFieldWrite(name, args[1]);
return null;
}
} |
Metaobject mobj;
mobj = _metaobject;
if (mobj == null)
return ClassMetaobject.invoke(this, identifier, args);
return mobj.trapMethodcall(identifier, args);
| 261 | 59 | 320 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/tools/rmi/AppletServer.java | AppletServer | lookupName | class AppletServer extends Webserver {
private StubGenerator stubGen;
private Map<String,ExportedObject> exportedNames;
private List<ExportedObject> exportedObjects;
private static final byte[] okHeader
= "HTTP/1.0 200 OK\r\n\r\n".getBytes();
/**
* Constructs a web server.
*
* @param port port number
*/
public AppletServer(String port)
throws IOException, NotFoundException, CannotCompileException
{
this(Integer.parseInt(port));
}
/**
* Constructs a web server.
*
* @param port port number
*/
public AppletServer(int port)
throws IOException, NotFoundException, CannotCompileException
{
this(ClassPool.getDefault(), new StubGenerator(), port);
}
/**
* Constructs a web server.
*
* @param port port number
* @param src the source of classs files.
*/
public AppletServer(int port, ClassPool src)
throws IOException, NotFoundException, CannotCompileException
{
this(new ClassPool(src), new StubGenerator(), port);
}
private AppletServer(ClassPool loader, StubGenerator gen, int port)
throws IOException, NotFoundException, CannotCompileException
{
super(port);
exportedNames = new Hashtable<String,ExportedObject>();
exportedObjects = new Vector<ExportedObject>();
stubGen = gen;
addTranslator(loader, gen);
}
/**
* Begins the HTTP service.
*/
@Override
public void run() {
super.run();
}
/**
* Exports an object.
* This method produces the bytecode of the proxy class used
* to access the exported object. A remote applet can load
* the proxy class and call a method on the exported object.
*
* @param name the name used for looking the object up.
* @param obj the exported object.
* @return the object identifier
*
* @see javassist.tools.rmi.ObjectImporter#lookupObject(String)
*/
public synchronized int exportObject(String name, Object obj)
throws CannotCompileException
{
Class<?> clazz = obj.getClass();
ExportedObject eo = new ExportedObject();
eo.object = obj;
eo.methods = clazz.getMethods();
exportedObjects.add(eo);
eo.identifier = exportedObjects.size() - 1;
if (name != null)
exportedNames.put(name, eo);
try {
stubGen.makeProxyClass(clazz);
}
catch (NotFoundException e) {
throw new CannotCompileException(e);
}
return eo.identifier;
}
/**
* Processes a request from a web browser (an ObjectImporter).
*/
@Override
public void doReply(InputStream in, OutputStream out, String cmd)
throws IOException, BadHttpRequest
{
if (cmd.startsWith("POST /rmi "))
processRMI(in, out);
else if (cmd.startsWith("POST /lookup "))
lookupName(cmd, in, out);
else
super.doReply(in, out, cmd);
}
private void processRMI(InputStream ins, OutputStream outs)
throws IOException
{
ObjectInputStream in = new ObjectInputStream(ins);
int objectId = in.readInt();
int methodId = in.readInt();
Exception err = null;
Object rvalue = null;
try {
ExportedObject eo = exportedObjects.get(objectId);
Object[] args = readParameters(in);
rvalue = convertRvalue(eo.methods[methodId].invoke(eo.object,
args));
}
catch(Exception e) {
err = e;
logging2(e.toString());
}
outs.write(okHeader);
ObjectOutputStream out = new ObjectOutputStream(outs);
if (err != null) {
out.writeBoolean(false);
out.writeUTF(err.toString());
}
else
try {
out.writeBoolean(true);
out.writeObject(rvalue);
}
catch (NotSerializableException e) {
logging2(e.toString());
}
catch (InvalidClassException e) {
logging2(e.toString());
}
out.flush();
out.close();
in.close();
}
private Object[] readParameters(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
int n = in.readInt();
Object[] args = new Object[n];
for (int i = 0; i < n; ++i) {
Object a = in.readObject();
if (a instanceof RemoteRef) {
RemoteRef ref = (RemoteRef)a;
ExportedObject eo = exportedObjects.get(ref.oid);
a = eo.object;
}
args[i] = a;
}
return args;
}
private Object convertRvalue(Object rvalue)
throws CannotCompileException
{
if (rvalue == null)
return null; // the return type is void.
String classname = rvalue.getClass().getName();
if (stubGen.isProxyClass(classname))
return new RemoteRef(exportObject(null, rvalue), classname);
return rvalue;
}
private void lookupName(String cmd, InputStream ins, OutputStream outs)
throws IOException
{<FILL_FUNCTION_BODY>}
} |
ObjectInputStream in = new ObjectInputStream(ins);
String name = DataInputStream.readUTF(in);
ExportedObject found = exportedNames.get(name);
outs.write(okHeader);
ObjectOutputStream out = new ObjectOutputStream(outs);
if (found == null) {
logging2(name + "not found.");
out.writeInt(-1); // error code
out.writeUTF("error");
}
else {
logging2(name);
out.writeInt(found.identifier);
out.writeUTF(found.object.getClass().getName());
}
out.flush();
out.close();
in.close();
| 1,492 | 170 | 1,662 | <methods>public void <init>(java.lang.String) throws java.io.IOException,public void <init>(int) throws java.io.IOException,public void addTranslator(org.hotswap.agent.javassist.ClassPool, org.hotswap.agent.javassist.Translator) throws org.hotswap.agent.javassist.NotFoundException, org.hotswap.agent.javassist.CannotCompileException,public void doReply(java.io.InputStream, java.io.OutputStream, java.lang.String) throws java.io.IOException, org.hotswap.agent.javassist.tools.web.BadHttpRequest,public void end() throws java.io.IOException,public void logging(java.lang.String) ,public void logging(java.lang.String, java.lang.String) ,public void logging(java.lang.String, java.lang.String, java.lang.String) ,public void logging2(java.lang.String) ,public static void main(java.lang.String[]) throws java.io.IOException,public void run() ,public void setClassPool(org.hotswap.agent.javassist.ClassPool) <variables>private org.hotswap.agent.javassist.ClassPool classPool,public java.lang.String debugDir,private static final byte[] endofline,public java.lang.String htmlfileBase,private java.net.ServerSocket socket,protected org.hotswap.agent.javassist.Translator translator,private static final int typeClass,private static final int typeGif,private static final int typeHtml,private static final int typeJpeg,private static final int typeText |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/tools/web/Viewer.java | Viewer | loadClass | class Viewer extends ClassLoader {
private String server;
private int port;
/**
* Starts a program.
*/
public static void main(String[] args) throws Throwable {
if (args.length >= 3) {
Viewer cl = new Viewer(args[0], Integer.parseInt(args[1]));
String[] args2 = new String[args.length - 3];
System.arraycopy(args, 3, args2, 0, args.length - 3);
cl.run(args[2], args2);
}
else
System.err.println(
"Usage: java javassist.tools.web.Viewer <host> <port> class [args ...]");
}
/**
* Constructs a viewer.
*
* @param host server name
* @param p port number
*/
public Viewer(String host, int p) {
server = host;
port = p;
}
/**
* Returns the server name.
*/
public String getServer() { return server; }
/**
* Returns the port number.
*/
public int getPort() { return port; }
/**
* Invokes main() in the class specified by <code>classname</code>.
*
* @param classname executed class
* @param args the arguments passed to <code>main()</code>.
*/
public void run(String classname, String[] args)
throws Throwable
{
Class<?> c = loadClass(classname);
try {
c.getDeclaredMethod("main", new Class[] { String[].class })
.invoke(null, new Object[] { args });
}
catch (java.lang.reflect.InvocationTargetException e) {
throw e.getTargetException();
}
}
/**
* Requests the class loader to load a class.
*/
@Override
protected synchronized Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException
{<FILL_FUNCTION_BODY>}
/**
* Finds the specified class. The implementation in this class
* fetches the class from the http server. If the class is
* either <code>java.*</code>, <code>javax.*</code>, or
* <code>Viewer</code>, then it is loaded by the parent class
* loader.
*
* <p>This method can be overridden by a subclass of
* <code>Viewer</code>.
*/
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
Class<?> c = null;
if (name.startsWith("java.") || name.startsWith("javax.")
|| name.equals("org.hotswap.agent.javassist.tools.web.Viewer"))
c = findSystemClass(name);
if (c == null)
try {
byte[] b = fetchClass(name);
if (b != null)
c = defineClass(name, b, 0, b.length);
}
catch (Exception e) {
}
return c;
}
/**
* Fetches the class file of the specified class from the http
* server.
*/
protected byte[] fetchClass(String classname) throws Exception
{
byte[] b;
URL url = new URL("http", server, port,
"/" + classname.replace('.', '/') + ".class");
URLConnection con = url.openConnection();
con.connect();
int size = con.getContentLength();
InputStream s = con.getInputStream();
if (size <= 0)
b = readStream(s);
else {
b = new byte[size];
int len = 0;
do {
int n = s.read(b, len, size - len);
if (n < 0) {
s.close();
throw new IOException("the stream was closed: "
+ classname);
}
len += n;
} while (len < size);
}
s.close();
return b;
}
private byte[] readStream(InputStream fin) throws IOException {
byte[] buf = new byte[4096];
int size = 0;
int len = 0;
do {
size += len;
if (buf.length - size <= 0) {
byte[] newbuf = new byte[buf.length * 2];
System.arraycopy(buf, 0, newbuf, 0, size);
buf = newbuf;
}
len = fin.read(buf, size, buf.length - size);
} while (len >= 0);
byte[] result = new byte[size];
System.arraycopy(buf, 0, result, 0, size);
return result;
}
} |
Class<?> c = findLoadedClass(name);
if (c == null)
c = findClass(name);
if (c == null)
throw new ClassNotFoundException(name);
if (resolve)
resolveClass(c);
return c;
| 1,260 | 74 | 1,334 | <methods>public void clearAssertionStatus() ,public final java.lang.Package getDefinedPackage(java.lang.String) ,public final java.lang.Package[] getDefinedPackages() ,public java.lang.String getName() ,public final java.lang.ClassLoader getParent() ,public static java.lang.ClassLoader getPlatformClassLoader() ,public java.net.URL getResource(java.lang.String) ,public java.io.InputStream getResourceAsStream(java.lang.String) ,public Enumeration<java.net.URL> getResources(java.lang.String) throws java.io.IOException,public static java.lang.ClassLoader getSystemClassLoader() ,public static java.net.URL getSystemResource(java.lang.String) ,public static java.io.InputStream getSystemResourceAsStream(java.lang.String) ,public static Enumeration<java.net.URL> getSystemResources(java.lang.String) throws java.io.IOException,public final java.lang.Module getUnnamedModule() ,public final boolean isRegisteredAsParallelCapable() ,public Class<?> loadClass(java.lang.String) throws java.lang.ClassNotFoundException,public Stream<java.net.URL> resources(java.lang.String) ,public void setClassAssertionStatus(java.lang.String, boolean) ,public void setDefaultAssertionStatus(boolean) ,public void setPackageAssertionStatus(java.lang.String, boolean) <variables>static final boolean $assertionsDisabled,final java.lang.Object assertionLock,Map<java.lang.String,java.lang.Boolean> classAssertionStatus,private volatile ConcurrentHashMap<?,?> classLoaderValueMap,private final ArrayList<Class<?>> classes,private boolean defaultAssertionStatus,private final java.security.ProtectionDomain defaultDomain,private final jdk.internal.loader.NativeLibraries libraries,private final java.lang.String name,private final java.lang.String nameAndId,private static final java.security.cert.Certificate[] nocerts,private final ConcurrentHashMap<java.lang.String,java.security.cert.Certificate[]> package2certs,private Map<java.lang.String,java.lang.Boolean> packageAssertionStatus,private final ConcurrentHashMap<java.lang.String,java.lang.NamedPackage> packages,private final ConcurrentHashMap<java.lang.String,java.lang.Object> parallelLockMap,private final java.lang.ClassLoader parent,private static volatile java.lang.ClassLoader scl,private final java.lang.Module unnamedModule |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/util/HotSwapAgent.java | HotSwapAgent | createJarFile | class HotSwapAgent {
private static Instrumentation instrumentation = null;
/**
* Obtains the {@code Instrumentation} object.
*
* @return null when it is not available.
*/
public Instrumentation instrumentation() { return instrumentation; }
/**
* The entry point invoked when this agent is started by {@code -javaagent}.
*/
public static void premain(String agentArgs, Instrumentation inst) throws Throwable {
agentmain(agentArgs, inst);
}
/**
* The entry point invoked when this agent is started after the JVM starts.
*/
public static void agentmain(String agentArgs, Instrumentation inst) throws Throwable {
if (!inst.isRedefineClassesSupported())
throw new RuntimeException("this JVM does not support redefinition of classes");
instrumentation = inst;
}
/**
* Redefines a class.
*/
public static void redefine(Class<?> oldClass, CtClass newClass)
throws NotFoundException, IOException, CannotCompileException
{
Class<?>[] old = { oldClass };
CtClass[] newClasses = { newClass };
redefine(old, newClasses);
}
/**
* Redefines classes.
*/
public static void redefine(Class<?>[] oldClasses, CtClass[] newClasses)
throws NotFoundException, IOException, CannotCompileException
{
startAgent();
ClassDefinition[] defs = new ClassDefinition[oldClasses.length];
for (int i = 0; i < oldClasses.length; i++)
defs[i] = new ClassDefinition(oldClasses[i], newClasses[i].toBytecode());
try {
instrumentation.redefineClasses(defs);
}
catch (ClassNotFoundException e) {
throw new NotFoundException(e.getMessage(), e);
}
catch (UnmodifiableClassException e) {
throw new CannotCompileException(e.getMessage(), e);
}
}
/**
* Ensures that the agent is ready.
* It attempts to dynamically start the agent if necessary.
*/
private static void startAgent() throws NotFoundException {
if (instrumentation != null)
return;
try {
File agentJar = createJarFile();
String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();
String pid = nameOfRunningVM.substring(0, nameOfRunningVM.indexOf('@'));
VirtualMachine vm = VirtualMachine.attach(pid);
vm.loadAgent(agentJar.getAbsolutePath(), null);
vm.detach();
}
catch (Exception e) {
throw new NotFoundException("hotswap agent", e);
}
for (int sec = 0; sec < 10 /* sec */; sec++) {
if (instrumentation != null)
return;
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
throw new NotFoundException("hotswap agent (timeout)");
}
/**
* Creates an agent file for using {@code HotSwapAgent}.
*/
public static File createAgentJarFile(String fileName)
throws IOException, CannotCompileException, NotFoundException
{
return createJarFile(new File(fileName));
}
private static File createJarFile()
throws IOException, CannotCompileException, NotFoundException
{
File jar = File.createTempFile("agent", ".jar");
jar.deleteOnExit();
return createJarFile(jar);
}
private static File createJarFile(File jar)
throws IOException, CannotCompileException, NotFoundException
{<FILL_FUNCTION_BODY>}
} |
Manifest manifest = new Manifest();
Attributes attrs = manifest.getMainAttributes();
attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0");
attrs.put(new Attributes.Name("Premain-Class"), HotSwapAgent.class.getName());
attrs.put(new Attributes.Name("Agent-Class"), HotSwapAgent.class.getName());
attrs.put(new Attributes.Name("Can-Retransform-Classes"), "true");
attrs.put(new Attributes.Name("Can-Redefine-Classes"), "true");
JarOutputStream jos = null;
try {
jos = new JarOutputStream(new FileOutputStream(jar), manifest);
String cname = HotSwapAgent.class.getName();
JarEntry e = new JarEntry(cname.replace('.', '/') + ".class");
jos.putNextEntry(e);
ClassPool pool = ClassPool.getDefault();
CtClass clazz = pool.get(cname);
jos.write(clazz.toBytecode());
jos.closeEntry();
}
finally {
if (jos != null)
jos.close();
}
return jar;
| 1,000 | 309 | 1,309 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/util/HotSwapper.java | HotSwapper | reload | class HotSwapper {
private VirtualMachine jvm;
private MethodEntryRequest request;
private Map<ReferenceType,byte[]> newClassFiles;
private Trigger trigger;
private static final String HOST_NAME = "localhost";
private static final String TRIGGER_NAME = Trigger.class.getName();
/**
* Connects to the JVM.
*
* @param port the port number used for the connection to the JVM.
*/
public HotSwapper(int port)
throws IOException, IllegalConnectorArgumentsException
{
this(Integer.toString(port));
}
/**
* Connects to the JVM.
*
* @param port the port number used for the connection to the JVM.
*/
public HotSwapper(String port)
throws IOException, IllegalConnectorArgumentsException
{
jvm = null;
request = null;
newClassFiles = null;
trigger = new Trigger();
AttachingConnector connector
= (AttachingConnector)findConnector("com.sun.jdi.SocketAttach");
Map<String,Connector.Argument> arguments = connector.defaultArguments();
arguments.get("hostname").setValue(HOST_NAME);
arguments.get("port").setValue(port);
jvm = connector.attach(arguments);
EventRequestManager manager = jvm.eventRequestManager();
request = methodEntryRequests(manager, TRIGGER_NAME);
}
private Connector findConnector(String connector) throws IOException {
List<Connector> connectors = Bootstrap.virtualMachineManager().allConnectors();
for (Connector con:connectors)
if (con.name().equals(connector))
return con;
throw new IOException("Not found: " + connector);
}
private static MethodEntryRequest methodEntryRequests(
EventRequestManager manager,
String classpattern) {
MethodEntryRequest mereq = manager.createMethodEntryRequest();
mereq.addClassFilter(classpattern);
mereq.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD);
return mereq;
}
/* Stops triggering a hotswapper when reload() is called.
*/
@SuppressWarnings("unused")
private void deleteEventRequest(EventRequestManager manager,
MethodEntryRequest request) {
manager.deleteEventRequest(request);
}
/**
* Reloads a class.
*
* @param className the fully-qualified class name.
* @param classFile the contents of the class file.
*/
public void reload(String className, byte[] classFile) {
ReferenceType classtype = toRefType(className);
Map<ReferenceType,byte[]> map = new HashMap<ReferenceType,byte[]>();
map.put(classtype, classFile);
reload2(map, className);
}
/**
* Reloads a class.
*
* @param classFiles a map between fully-qualified class names
* and class files. The type of the class names
* is <code>String</code> and the type of the
* class files is <code>byte[]</code>.
*/
public void reload(Map<String,byte[]> classFiles) {<FILL_FUNCTION_BODY>}
private ReferenceType toRefType(String className) {
List<ReferenceType> list = jvm.classesByName(className);
if (list == null || list.isEmpty())
throw new RuntimeException("no such class: " + className);
return list.get(0);
}
private void reload2(Map<ReferenceType,byte[]> map, String msg) {
synchronized (trigger) {
startDaemon();
newClassFiles = map;
request.enable();
trigger.doSwap();
request.disable();
Map<ReferenceType,byte[]> ncf = newClassFiles;
if (ncf != null) {
newClassFiles = null;
throw new RuntimeException("failed to reload: " + msg);
}
}
}
private void startDaemon() {
new Thread() {
private void errorMsg(Throwable e) {
System.err.print("Exception in thread \"HotSwap\" ");
e.printStackTrace(System.err);
}
@Override
public void run() {
EventSet events = null;
try {
events = waitEvent();
EventIterator iter = events.eventIterator();
while (iter.hasNext()) {
Event event = iter.nextEvent();
if (event instanceof MethodEntryEvent) {
hotswap();
break;
}
}
}
catch (Throwable e) {
errorMsg(e);
}
try {
if (events != null)
events.resume();
}
catch (Throwable e) {
errorMsg(e);
}
}
}.start();
}
EventSet waitEvent() throws InterruptedException {
EventQueue queue = jvm.eventQueue();
return queue.remove();
}
void hotswap() {
Map<ReferenceType,byte[]> map = newClassFiles;
jvm.redefineClasses(map);
newClassFiles = null;
}
} |
Map<ReferenceType,byte[]> map = new HashMap<ReferenceType,byte[]>();
String className = null;
for (Map.Entry<String,byte[]> e:classFiles.entrySet()) {
className = e.getKey();
map.put(toRefType(className), e.getValue());
}
if (className != null)
reload2(map, className + " etc.");
| 1,373 | 106 | 1,479 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/util/proxy/DefineClassHelper.java | Java7 | getDefineClassMethodHandle | class Java7 extends Helper {
private final SecurityActions stack = SecurityActions.stack;
private final MethodHandle defineClass = getDefineClassMethodHandle();
private final MethodHandle getDefineClassMethodHandle() {<FILL_FUNCTION_BODY>}
@Override
Class<?> defineClass(String name, byte[] b, int off, int len, Class<?> neighbor,
ClassLoader loader, ProtectionDomain protectionDomain)
throws ClassFormatError
{
if (stack.getCallerClass() != DefineClassHelper.class)
throw new IllegalAccessError("Access denied for caller.");
try {
return (Class<?>) defineClass.invokeWithArguments(
loader, name, b, off, len, protectionDomain);
} catch (Throwable e) {
if (e instanceof RuntimeException) throw (RuntimeException) e;
if (e instanceof ClassFormatError) throw (ClassFormatError) e;
throw new ClassFormatError(e.getMessage());
}
}
} |
if (privileged != null && stack.getCallerClass() != this.getClass())
throw new IllegalAccessError("Access denied for caller.");
try {
return SecurityActions.getMethodHandle(ClassLoader.class, "defineClass",
new Class[] {
String.class, byte[].class, int.class, int.class,
ProtectionDomain.class
});
} catch (NoSuchMethodException e) {
throw new RuntimeException("cannot initialize", e);
}
| 249 | 126 | 375 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/util/proxy/DefinePackageHelper.java | JavaOther | definePackage | class JavaOther extends Helper {
private final SecurityActions stack = SecurityActions.stack;
private final Method definePackage = getDefinePackageMethod();
private Method getDefinePackageMethod() {
if (stack.getCallerClass() != this.getClass())
throw new IllegalAccessError("Access denied for caller.");
try {
return SecurityActions.getDeclaredMethod(ClassLoader.class,
"definePackage", new Class[] {
String.class, String.class, String.class, String.class,
String.class, String.class, String.class, URL.class
});
} catch (NoSuchMethodException e) {
throw new RuntimeException("cannot initialize", e);
}
}
@Override
Package definePackage(ClassLoader loader, String name, String specTitle,
String specVersion, String specVendor, String implTitle, String implVersion,
String implVendor, URL sealBase)
throws IllegalArgumentException
{
if (stack.getCallerClass() != DefinePackageHelper.class)
throw new IllegalAccessError("Access denied for caller.");
try {
definePackage.setAccessible(true);
return (Package) definePackage.invoke(loader, new Object[] {
name, specTitle, specVersion, specVendor, implTitle,
implVersion, implVendor, sealBase
});
} catch (Throwable e) {
if (e instanceof InvocationTargetException) {
Throwable t = ((InvocationTargetException) e).getTargetException();
if (t instanceof IllegalArgumentException)
throw (IllegalArgumentException) t;
}
if (e instanceof RuntimeException) throw (RuntimeException) e;
}
finally {
definePackage.setAccessible(false);
}
return null;
}
};
private static final Helper privileged
= ClassFile.MAJOR_VERSION >= ClassFile.JAVA_9
? new Java9() : ClassFile.MAJOR_VERSION >= ClassFile.JAVA_7
? new Java7() : new JavaOther();
/**
* Defines a new package. If the package is already defined, this method
* performs nothing.
*
* <p>You do not necessarily need to
* call this method. If this method is called, then
* <code>getPackage()</code> on the <code>Class</code> object returned
* by <code>toClass()</code> will return a non-null object.</p>
*
* <p>The jigsaw module introduced by Java 9 has broken this method.
* In Java 9 or later, the VM argument
* <code>--add-opens java.base/java.lang=ALL-UNNAMED</code>
* has to be given to the JVM so that this method can run.
* </p>
*
* @param loader the class loader passed to <code>toClass()</code> or
* the default one obtained by <code>getClassLoader()</code>.
* @param className the package name.
* @see Class#getClassLoader()
* @see CtClass#toClass()
*/
public static void definePackage(String className, ClassLoader loader)
throws CannotCompileException
{<FILL_FUNCTION_BODY> |
try {
privileged.definePackage(loader, className,
null, null, null, null, null, null, null);
}
catch (IllegalArgumentException e) {
// if the package is already defined, an IllegalArgumentException
// is thrown.
return;
}
catch (Exception e) {
throw new CannotCompileException(e);
}
| 837 | 97 | 934 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/util/proxy/FactoryHelper.java | FactoryHelper | writeFile0 | class FactoryHelper {
/**
* Returns an index for accessing arrays in this class.
*
* @throws RuntimeException if a given type is not a primitive type.
*/
public static final int typeIndex(Class<?> type) {
for (int i = 0; i < primitiveTypes.length; i++)
if (primitiveTypes[i] == type)
return i;
throw new RuntimeException("bad type:" + type.getName());
}
/**
* <code>Class</code> objects representing primitive types.
*/
public static final Class<?>[] primitiveTypes = {
Boolean.TYPE, Byte.TYPE, Character.TYPE, Short.TYPE, Integer.TYPE,
Long.TYPE, Float.TYPE, Double.TYPE, Void.TYPE
};
/**
* The fully-qualified names of wrapper classes for primitive types.
*/
public static final String[] wrapperTypes = {
"java.lang.Boolean", "java.lang.Byte", "java.lang.Character",
"java.lang.Short", "java.lang.Integer", "java.lang.Long",
"java.lang.Float", "java.lang.Double", "java.lang.Void"
};
/**
* The descriptors of the constructors of wrapper classes.
*/
public static final String[] wrapperDesc = {
"(Z)V", "(B)V", "(C)V", "(S)V", "(I)V", "(J)V",
"(F)V", "(D)V"
};
/**
* The names of methods for obtaining a primitive value
* from a wrapper object. For example, <code>intValue()</code>
* is such a method for obtaining an integer value from a
* <code>java.lang.Integer</code> object.
*/
public static final String[] unwarpMethods = {
"booleanValue", "byteValue", "charValue", "shortValue",
"intValue", "longValue", "floatValue", "doubleValue"
};
/**
* The descriptors of the unwrapping methods contained
* in <code>unwrapMethods</code>.
*/
public static final String[] unwrapDesc = {
"()Z", "()B", "()C", "()S", "()I", "()J", "()F", "()D"
};
/**
* The data size of primitive types. <code>long</code>
* and <code>double</code> are 2; the others are 1.
*/
public static final int[] dataSize = {
1, 1, 1, 1, 1, 2, 1, 2
};
/**
* Loads a class file by a given class loader.
* This method uses a default protection domain for the class
* but it may not work with a security manager or a signed jar file.
*
* @see #toClass(ClassFile,Class,ClassLoader,ProtectionDomain)
* @deprecated
*/
public static Class<?> toClass(ClassFile cf, ClassLoader loader)
throws CannotCompileException
{
return toClass(cf, null, loader, null);
}
/**
* Loads a class file by a given class loader.
*
* @param neighbor a class belonging to the same package that
* the loaded class belongs to.
* It can be null.
* @param loader The class loader. It can be null if {@code neighbor}
* is not null.
* @param domain if it is null, a default domain is used.
* @since 3.3
*/
public static Class<?> toClass(ClassFile cf, Class<?> neighbor,
ClassLoader loader, ProtectionDomain domain)
throws CannotCompileException
{
try {
byte[] b = toBytecode(cf);
if (ProxyFactory.onlyPublicMethods)
return DefineClassHelper.toPublicClass(cf.getName(), b);
else
return DefineClassHelper.toClass(cf.getName(), neighbor,
loader, domain, b);
}
catch (IOException e) {
throw new CannotCompileException(e);
}
}
/**
* Loads a class file by a given lookup.
*
* @param lookup used to define the class.
* @since 3.24
*/
public static Class<?> toClass(ClassFile cf, java.lang.invoke.MethodHandles.Lookup lookup)
throws CannotCompileException
{
try {
byte[] b = toBytecode(cf);
return DefineClassHelper.toClass(lookup, b);
}
catch (IOException e) {
throw new CannotCompileException(e);
}
}
private static byte[] toBytecode(ClassFile cf) throws IOException {
ByteArrayOutputStream barray = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(barray);
try {
cf.write(out);
}
finally {
out.close();
}
return barray.toByteArray();
}
/**
* Writes a class file.
*/
public static void writeFile(ClassFile cf, String directoryName)
throws CannotCompileException {
try {
writeFile0(cf, directoryName);
}
catch (IOException e) {
throw new CannotCompileException(e);
}
}
private static void writeFile0(ClassFile cf, String directoryName)
throws CannotCompileException, IOException {<FILL_FUNCTION_BODY>}
} |
String classname = cf.getName();
String filename = directoryName + File.separatorChar
+ classname.replace('.', File.separatorChar) + ".class";
int pos = filename.lastIndexOf(File.separatorChar);
if (pos > 0) {
String dir = filename.substring(0, pos);
if (!dir.equals("."))
new File(dir).mkdirs();
}
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(
new FileOutputStream(filename)));
try {
cf.write(out);
}
catch (IOException e) {
throw e;
}
finally {
out.close();
}
| 1,423 | 177 | 1,600 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/util/proxy/ProxyObjectInputStream.java | ProxyObjectInputStream | readClassDescriptor | class ProxyObjectInputStream extends ObjectInputStream
{
/**
* create an input stream which can be used to deserialize an object graph which includes proxies created
* using class ProxyFactory. the classloader used to resolve proxy superclass and interface names
* read from the input stream will default to the current thread's context class loader or the system
* classloader if the context class loader is null.
* @param in
* @throws java.io.StreamCorruptedException whenever ObjectInputStream would also do so
* @throws IOException whenever ObjectInputStream would also do so
* @throws SecurityException whenever ObjectInputStream would also do so
* @throws NullPointerException if in is null
*/
public ProxyObjectInputStream(InputStream in) throws IOException
{
super(in);
loader = Thread.currentThread().getContextClassLoader();
if (loader == null) {
loader = ClassLoader.getSystemClassLoader();
}
}
/**
* Reset the loader to be
* @param loader
*/
public void setClassLoader(ClassLoader loader)
{
if (loader != null) {
this.loader = loader;
} else {
loader = ClassLoader.getSystemClassLoader();
}
}
@Override
protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>}
/**
* the loader to use to resolve classes for proxy superclass and interface names read
* from the stream. defaults to the context class loader of the thread which creates
* the input stream or the system class loader if the context class loader is null.
*/
private ClassLoader loader;
} |
boolean isProxy = readBoolean();
if (isProxy) {
String name = (String)readObject();
Class<?> superClass = loader.loadClass(name);
int length = readInt();
Class<?>[] interfaces = new Class[length];
for (int i = 0; i < length; i++) {
name = (String)readObject();
interfaces[i] = loader.loadClass(name);
}
length = readInt();
byte[] signature = new byte[length];
read(signature);
ProxyFactory factory = new ProxyFactory();
// we must always use the cache and never use writeReplace when using
// ProxyObjectOutputStream and ProxyObjectInputStream
factory.setUseCache(true);
factory.setUseWriteReplace(false);
factory.setSuperclass(superClass);
factory.setInterfaces(interfaces);
Class<?> proxyClass = factory.createClass(signature);
return ObjectStreamClass.lookup(proxyClass);
}
return super.readClassDescriptor();
| 410 | 261 | 671 | <methods>public void <init>(java.io.InputStream) throws java.io.IOException,public int available() throws java.io.IOException,public void close() throws java.io.IOException,public void defaultReadObject() throws java.io.IOException, java.lang.ClassNotFoundException,public final java.io.ObjectInputFilter getObjectInputFilter() ,public int read() throws java.io.IOException,public int read(byte[], int, int) throws java.io.IOException,public boolean readBoolean() throws java.io.IOException,public byte readByte() throws java.io.IOException,public char readChar() throws java.io.IOException,public double readDouble() throws java.io.IOException,public java.io.ObjectInputStream.GetField readFields() throws java.io.IOException, java.lang.ClassNotFoundException,public float readFloat() throws java.io.IOException,public void readFully(byte[]) throws java.io.IOException,public void readFully(byte[], int, int) throws java.io.IOException,public int readInt() throws java.io.IOException,public java.lang.String readLine() throws java.io.IOException,public long readLong() throws java.io.IOException,public final java.lang.Object readObject() throws java.io.IOException, java.lang.ClassNotFoundException,public short readShort() throws java.io.IOException,public java.lang.String readUTF() throws java.io.IOException,public java.lang.Object readUnshared() throws java.io.IOException, java.lang.ClassNotFoundException,public int readUnsignedByte() throws java.io.IOException,public int readUnsignedShort() throws java.io.IOException,public void registerValidation(java.io.ObjectInputValidation, int) throws java.io.NotActiveException, java.io.InvalidObjectException,public final void setObjectInputFilter(java.io.ObjectInputFilter) ,public int skipBytes(int) throws java.io.IOException<variables>static final boolean $assertionsDisabled,private static final int NULL_HANDLE,private static final jdk.internal.misc.Unsafe UNSAFE,private final java.io.ObjectInputStream.BlockDataInputStream bin,private boolean closed,private java.io.SerialCallbackContext curContext,private boolean defaultDataEnd,private long depth,private final boolean enableOverride,private boolean enableResolve,private final java.io.ObjectInputStream.HandleTable handles,private int passHandle,private static final Map<java.lang.String,Class<?>> primClasses,private java.io.ObjectInputFilter serialFilter,private boolean streamFilterSet,private long totalObjectRefs,private static final java.lang.Object unsharedMarker,private final java.io.ObjectInputStream.ValidationList vlist |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/util/proxy/ProxyObjectOutputStream.java | ProxyObjectOutputStream | writeClassDescriptor | class ProxyObjectOutputStream extends ObjectOutputStream
{
/**
* create an output stream which can be used to serialize an object graph which includes proxies created
* using class ProxyFactory
* @param out
* @throws IOException whenever ObjectOutputStream would also do so
* @throws SecurityException whenever ObjectOutputStream would also do so
* @throws NullPointerException if out is null
*/
public ProxyObjectOutputStream(OutputStream out) throws IOException
{
super(out);
}
@Override
protected void writeClassDescriptor(ObjectStreamClass desc) throws IOException {<FILL_FUNCTION_BODY>}
} |
Class<?> cl = desc.forClass();
if (ProxyFactory.isProxyClass(cl)) {
writeBoolean(true);
Class<?> superClass = cl.getSuperclass();
Class<?>[] interfaces = cl.getInterfaces();
byte[] signature = ProxyFactory.getFilterSignature(cl);
String name = superClass.getName();
writeObject(name);
// we don't write the marker interface ProxyObject
writeInt(interfaces.length - 1);
for (int i = 0; i < interfaces.length; i++) {
Class<?> interfaze = interfaces[i];
if (interfaze != ProxyObject.class && interfaze != Proxy.class) {
name = interfaces[i].getName();
writeObject(name);
}
}
writeInt(signature.length);
write(signature);
} else {
writeBoolean(false);
super.writeClassDescriptor(desc);
}
| 153 | 247 | 400 | <methods>public void <init>(java.io.OutputStream) throws java.io.IOException,public void close() throws java.io.IOException,public void defaultWriteObject() throws java.io.IOException,public void flush() throws java.io.IOException,public java.io.ObjectOutputStream.PutField putFields() throws java.io.IOException,public void reset() throws java.io.IOException,public void useProtocolVersion(int) throws java.io.IOException,public void write(int) throws java.io.IOException,public void write(byte[]) throws java.io.IOException,public void write(byte[], int, int) throws java.io.IOException,public void writeBoolean(boolean) throws java.io.IOException,public void writeByte(int) throws java.io.IOException,public void writeBytes(java.lang.String) throws java.io.IOException,public void writeChar(int) throws java.io.IOException,public void writeChars(java.lang.String) throws java.io.IOException,public void writeDouble(double) throws java.io.IOException,public void writeFields() throws java.io.IOException,public void writeFloat(float) throws java.io.IOException,public void writeInt(int) throws java.io.IOException,public void writeLong(long) throws java.io.IOException,public final void writeObject(java.lang.Object) throws java.io.IOException,public void writeShort(int) throws java.io.IOException,public void writeUTF(java.lang.String) throws java.io.IOException,public void writeUnshared(java.lang.Object) throws java.io.IOException<variables>static final boolean $assertionsDisabled,private final java.io.ObjectOutputStream.BlockDataOutputStream bout,private java.io.SerialCallbackContext curContext,private java.io.ObjectOutputStream.PutFieldImpl curPut,private final java.io.ObjectOutputStream.DebugTraceInfoStack debugInfoStack,private int depth,private final boolean enableOverride,private boolean enableReplace,private static final boolean extendedDebugInfo,private final java.io.ObjectOutputStream.HandleTable handles,private byte[] primVals,private int protocol,private final java.io.ObjectOutputStream.ReplaceTable subs |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/util/proxy/RuntimeSupport.java | DefaultMethodHandler | findMethod | class DefaultMethodHandler implements MethodHandler, Serializable {
/** default serialVersionUID */
private static final long serialVersionUID = 1L;
@Override
public Object invoke(Object self, Method m,
Method proceed, Object[] args)
throws Exception
{
return proceed.invoke(self, args);
}
};
/**
* Finds two methods specified by the parameters and stores them
* into the given array.
*
* @throws RuntimeException if the methods are not found.
* @see javassist.util.proxy.ProxyFactory
*/
public static void find2Methods(Class<?> clazz, String superMethod,
String thisMethod, int index,
String desc, java.lang.reflect.Method[] methods)
{
methods[index + 1] = thisMethod == null ? null
: findMethod(clazz, thisMethod, desc);
methods[index] = findSuperClassMethod(clazz, superMethod, desc);
}
/**
* Finds two methods specified by the parameters and stores them
* into the given array.
*
* <p>Added back for JBoss Seam. See JASSIST-206.</p>
*
* @throws RuntimeException if the methods are not found.
* @see javassist.util.proxy.ProxyFactory
* @deprecated replaced by {@link #find2Methods(Class, String, String, int, String, Method[])}
*/
@Deprecated
public static void find2Methods(Object self, String superMethod,
String thisMethod, int index,
String desc, java.lang.reflect.Method[] methods)
{
methods[index + 1] = thisMethod == null ? null
: findMethod(self, thisMethod, desc);
methods[index] = findSuperMethod(self, superMethod, desc);
}
/**
* Finds a method with the given name and descriptor.
* It searches only the class of self.
*
* <p>Added back for JBoss Seam. See JASSIST-206.</p>
*
* @throws RuntimeException if the method is not found.
* @deprecated replaced by {@link #findMethod(Class, String, String)}
*/
@Deprecated
public static Method findMethod(Object self, String name, String desc) {<FILL_FUNCTION_BODY> |
Method m = findMethod2(self.getClass(), name, desc);
if (m == null)
error(self.getClass(), name, desc);
return m;
| 597 | 48 | 645 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/util/proxy/SerializedProxy.java | SerializedProxy | loadClass | class SerializedProxy implements Serializable {
/** default serialVersionUID */
private static final long serialVersionUID = 1L;
private String superClass;
private String[] interfaces;
private byte[] filterSignature;
private MethodHandler handler;
SerializedProxy(Class<?> proxy, byte[] sig, MethodHandler h) {
filterSignature = sig;
handler = h;
superClass = proxy.getSuperclass().getName();
Class<?>[] infs = proxy.getInterfaces();
int n = infs.length;
interfaces = new String[n - 1];
String setterInf = ProxyObject.class.getName();
String setterInf2 = Proxy.class.getName();
for (int i = 0; i < n; i++) {
String name = infs[i].getName();
if (!name.equals(setterInf) && !name.equals(setterInf2))
interfaces[i] = name;
}
}
/**
* Load class.
*
* @param className the class name
* @return loaded class
* @throws ClassNotFoundException for any error
*/
protected Class<?> loadClass(final String className) throws ClassNotFoundException {<FILL_FUNCTION_BODY>}
Object readResolve() throws ObjectStreamException {
try {
int n = interfaces.length;
Class<?>[] infs = new Class[n];
for (int i = 0; i < n; i++)
infs[i] = loadClass(interfaces[i]);
ProxyFactory f = new ProxyFactory();
f.setSuperclass(loadClass(superClass));
f.setInterfaces(infs);
Proxy proxy = (Proxy)f.createClass(filterSignature).getConstructor().newInstance();
proxy.setHandler(handler);
return proxy;
}
catch (NoSuchMethodException e) {
throw new InvalidClassException(e.getMessage());
}
catch (InvocationTargetException e) {
throw new InvalidClassException(e.getMessage());
}
catch (ClassNotFoundException e) {
throw new InvalidClassException(e.getMessage());
}
catch (InstantiationException e2) {
throw new InvalidObjectException(e2.getMessage());
}
catch (IllegalAccessException e3) {
throw new InvalidClassException(e3.getMessage());
}
}
} |
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>(){
@Override
public Class<?> run() throws Exception{
ClassLoader cl = Thread.currentThread().getContextClassLoader();
return Class.forName(className, true, cl);
}
});
}
catch (PrivilegedActionException pae) {
throw new RuntimeException("cannot load the class: " + className, pae.getException());
}
| 605 | 126 | 731 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/logging/AgentLogger.java | AgentLogger | isLevelEnabled | class AgentLogger {
/**
* Get logger for a class
*
* @param clazz class to log
* @return logger
*/
public static AgentLogger getLogger(Class clazz) {
return new AgentLogger(clazz);
}
private static Map<String, Level> currentLevels = new HashMap<>();
public static void setLevel(String classPrefix, Level level) {
currentLevels.put(classPrefix, level);
}
private static Level rootLevel = Level.INFO;
public static void setLevel(Level level) {
rootLevel = level;
}
private static AgentLoggerHandler handler = new AgentLoggerHandler();
public static void setHandler(AgentLoggerHandler handler) {
AgentLogger.handler = handler;
}
public static AgentLoggerHandler getHandler() {
return handler;
}
public static void setDateTimeFormat(String dateTimeFormat) {
handler.setDateTimeFormat(dateTimeFormat);
}
/**
* Standard logging levels.
*/
public enum Level {
ERROR,
RELOAD,
WARNING,
INFO,
DEBUG,
TRACE
}
private Class clazz;
private AgentLogger(Class clazz) {
this.clazz = clazz;
}
public boolean isLevelEnabled(Level level) {<FILL_FUNCTION_BODY>}
public void log(Level level, String message, Throwable throwable, Object... args) {
if (isLevelEnabled(level))
handler.print(clazz, level, message, throwable, args);
}
public void log(Level level, String message, Object... args) {
log(level, message, null, args);
}
public void error(String message, Object... args) {
log(Level.ERROR, message, args);
}
public void error(String message, Throwable throwable, Object... args) {
log(Level.ERROR, message, throwable, args);
}
public void reload(String message, Object... args) {
log(Level.RELOAD, message, args);
}
public void reload(String message, Throwable throwable, Object... args) {
log(Level.RELOAD, message, throwable, args);
}
public void warning(String message, Object... args) {
log(Level.WARNING, message, args);
}
public void warning(String message, Throwable throwable, Object... args) {
log(Level.WARNING, message, throwable, args);
}
public void info(String message, Object... args) {
log(Level.INFO, message, args);
}
public void info(String message, Throwable throwable, Object... args) {
log(Level.INFO, message, throwable, args);
}
public void debug(String message, Object... args) {
log(Level.DEBUG, message, args);
}
public void debug(String message, Throwable throwable, Object... args) {
log(Level.DEBUG, message, throwable, args);
}
public void trace(String message, Object... args) {
log(Level.TRACE, message, args);
}
public void trace(String message, Throwable throwable, Object... args) {
log(Level.TRACE, message, throwable, args);
}
public boolean isDebugEnabled() {
return isLevelEnabled(Level.DEBUG);
}
public boolean isWarnEnabled() {
return isLevelEnabled(Level.WARNING);
}
} |
Level classLevel = rootLevel;
String className = clazz.getName();
String longestPrefix = "";
for (String classPrefix : currentLevels.keySet()) {
if (className.startsWith(classPrefix)) {
if (classPrefix.length() > longestPrefix.length()) {
longestPrefix = classPrefix;
classLevel = currentLevels.get(classPrefix);
}
}
}
// iterate levels in order from most serious. If classLevel is first, it preciedes required level and log is disabled
for (Level l : Level.values()) {
if (l == level)
return true;
if (l == classLevel)
return false;
}
throw new IllegalArgumentException("Should not happen.");
| 916 | 190 | 1,106 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/logging/AgentLoggerHandler.java | AgentLoggerHandler | formatErrorTrace | class AgentLoggerHandler {
// stream to receive the log
PrintStream outputStream;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
/**
* Setup custom stream (default is System.out).
*
* @param outputStream custom stream
*/
public void setPrintStream(PrintStream outputStream) {
this.outputStream = outputStream;
}
// print a message to System.out and optionally to custom stream
protected void printMessage(String message) {
String log = "HOTSWAP AGENT: " + sdf.format(new Date()) + " " + message;
System.out.println(log);
if (outputStream != null)
outputStream.println(log);
}
public void print(Class clazz, AgentLogger.Level level, String message, Throwable throwable, Object... args) {
// replace {} in string with actual parameters
String messageWithArgs = message;
for (Object arg : args) {
int index = messageWithArgs.indexOf("{}");
if (index >= 0) {
messageWithArgs = messageWithArgs.substring(0, index) + String.valueOf(arg) + messageWithArgs.substring(index + 2);
}
}
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(level);
stringBuffer.append(" (");
stringBuffer.append(clazz.getName());
stringBuffer.append(") - ");
stringBuffer.append(messageWithArgs);
if (throwable != null) {
stringBuffer.append("\n");
stringBuffer.append(formatErrorTrace(throwable));
}
printMessage(stringBuffer.toString());
}
private String formatErrorTrace(Throwable throwable) {<FILL_FUNCTION_BODY>}
public void setDateTimeFormat(String dateTimeFormat) {
sdf = new SimpleDateFormat(dateTimeFormat);
}
} |
StringWriter errors = new StringWriter();
throwable.printStackTrace(new PrintWriter(errors));
return errors.toString();
| 496 | 35 | 531 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/plugin/hotswapper/HotSwapper.java | HotSwapper | newClass | class HotSwapper {
/**
* Swap class definition from another class file.
* <p/>
* This is mainly useful for unit testing - declare multiple version of a class and then
* hotswap definition and do the tests.
*
* @param original original class currently in use
* @param swap fully qualified class name of class to swap
* @throws Exception swap exception
*/
public static void swapClasses(Class original, String swap) throws Exception {
// need to recreate classpool on each swap to avoid stale class definition
ClassPool classPool = new ClassPool();
classPool.appendClassPath(new LoaderClassPath(original.getClassLoader()));
CtClass ctClass = classPool.getAndRename(swap, original.getName());
reload(original, ctClass.toBytecode());
}
private static void reload(Class original, byte[] bytes) {
Map<Class<?>, byte[]> reloadMap = new HashMap<>();
reloadMap.put(original, bytes);
PluginManager.getInstance().hotswap(reloadMap);
}
public static Class newClass(String className, String directory, ClassLoader cl){<FILL_FUNCTION_BODY>}
} |
try {
ClassPool classPool = new ClassPool();
classPool.appendClassPath(new LoaderClassPath(cl));
CtClass makeClass = classPool.makeClass(className);
makeClass.writeFile(directory);
return makeClass.toClass();
} catch (Throwable ex) {
Logger.getLogger(HotSwapper.class.getName()).log(Level.SEVERE, null, ex);
throw new RuntimeException(ex);
}
| 317 | 121 | 438 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/plugin/hotswapper/HotSwapperJpda.java | HotSwapperJpda | run | class HotSwapperJpda {
private VirtualMachine jvm;
private MethodEntryRequest request;
private Map<ReferenceType,byte[]> newClassFiles;
private Trigger trigger;
private static final String HOST_NAME = "localhost";
private static final String TRIGGER_NAME = Trigger.class.getName();
/**
* Connects to the JVM.
*
* @param port the port number used for the connection to the JVM.
*/
public HotSwapperJpda(int port)
throws IOException, IllegalConnectorArgumentsException {
this(Integer.toString(port));
}
/**
* Connects to the JVM.
*
* @param port the port number used for the connection to the JVM.
*/
public HotSwapperJpda(String port)
throws IOException, IllegalConnectorArgumentsException {
jvm = null;
request = null;
newClassFiles = null;
trigger = new Trigger();
AttachingConnector connector
= (AttachingConnector)findConnector("com.sun.jdi.SocketAttach");
Map<String,Connector.Argument> arguments = connector.defaultArguments();
arguments.get("hostname").setValue(HOST_NAME);
arguments.get("port").setValue(port);
jvm = connector.attach(arguments);
EventRequestManager manager = jvm.eventRequestManager();
request = methodEntryRequests(manager, TRIGGER_NAME);
}
private Connector findConnector(String connector) throws IOException {
List<Connector> connectors = Bootstrap.virtualMachineManager().allConnectors();
for (Connector con:connectors)
if (con.name().equals(connector))
return con;
throw new IOException("Not found: " + connector);
}
private static MethodEntryRequest methodEntryRequests(
EventRequestManager manager,
String classpattern) {
MethodEntryRequest mereq = manager.createMethodEntryRequest();
mereq.addClassFilter(classpattern);
mereq.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD);
return mereq;
}
/* Stops triggering a hotswapper when reload() is called.
*/
@SuppressWarnings("unused")
private void deleteEventRequest(EventRequestManager manager,
MethodEntryRequest request) {
manager.deleteEventRequest(request);
}
/**
* Reloads a class.
*
* @param className the fully-qualified class name.
* @param classFile the contents of the class file.
*/
public void reload(String className, byte[] classFile) {
ReferenceType classtype = toRefType(className);
Map<ReferenceType,byte[]> map = new HashMap<ReferenceType,byte[]>();
map.put(classtype, classFile);
reload2(map, className);
}
/**
* Reloads a class.
*
* @param classFiles a map between fully-qualified class names
* and class files. The type of the class names
* is <code>String</code> and the type of the
* class files is <code>byte[]</code>.
*/
public void reload(Map<String,byte[]> classFiles) {
Map<ReferenceType,byte[]> map = new HashMap<ReferenceType,byte[]>();
String className = null;
for (Map.Entry<String,byte[]> e:classFiles.entrySet()) {
className = e.getKey();
map.put(toRefType(className), e.getValue());
}
if (className != null)
reload2(map, className + " etc.");
}
private ReferenceType toRefType(String className) {
List<ReferenceType> list = jvm.classesByName(className);
if (list == null || list.isEmpty())
throw new RuntimeException("no such class: " + className);
return list.get(0);
}
private void reload2(Map<ReferenceType,byte[]> map, String msg) {
synchronized (trigger) {
startDaemon();
newClassFiles = map;
request.enable();
trigger.doSwap();
request.disable();
Map<ReferenceType,byte[]> ncf = newClassFiles;
if (ncf != null) {
newClassFiles = null;
throw new RuntimeException("failed to reload: " + msg);
}
}
}
private void startDaemon() {
new Thread() {
private void errorMsg(Throwable e) {
System.err.print("Exception in thread \"HotSwap\" ");
e.printStackTrace(System.err);
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
}.start();
}
EventSet waitEvent() throws InterruptedException {
EventQueue queue = jvm.eventQueue();
return queue.remove();
}
void hotswap() {
Map<ReferenceType,byte[]> map = newClassFiles;
jvm.redefineClasses(map);
newClassFiles = null;
}
/**
* Swap class definition from another class file.
* <p/>
* This is mainly useful for unit testing - declare multiple version of a class and then
* hotswap definition and do the tests.
*
* @param original original class currently in use
* @param swap fully qualified class name of class to swap
* @throws Exception swap exception
*/
public void swapClasses(Class original, String swap) throws Exception {
// need to recreate classpool on each swap to avoid stale class definition
ClassPool classPool = new ClassPool();
classPool.appendClassPath(new LoaderClassPath(original.getClassLoader()));
CtClass ctClass = classPool.getAndRename(swap, original.getName());
reload(original.getName(), ctClass.toBytecode());
}
} |
EventSet events = null;
try {
events = waitEvent();
EventIterator iter = events.eventIterator();
while (iter.hasNext()) {
Event event = iter.nextEvent();
if (event instanceof MethodEntryEvent) {
hotswap();
break;
}
}
} catch (Throwable e) {
errorMsg(e);
}
try {
if (events != null)
events.resume();
} catch (Throwable e) {
errorMsg(e);
}
| 1,535 | 141 | 1,676 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/plugin/hotswapper/HotswapperCommand.java | HotswapperCommand | hotswap | class HotswapperCommand {
private static AgentLogger LOGGER = AgentLogger.getLogger(HotswapperCommand.class);
// HotSwapperJpda will connect to JPDA on first hotswap command and remain connected.
// The HotSwapperJpda class from javaassist is copied to the plugin, because it needs to reside
// in the application classloader to avoid NoClassDefFound error on tools.jar classes.
private static HotSwapperJpda hotSwapper = null;
public static synchronized void hotswap(String port, final HashMap<Class<?>, byte[]> reloadMap) {<FILL_FUNCTION_BODY>}
} |
// synchronize on the reloadMap object - do not allow addition while in process
synchronized (reloadMap) {
if (hotSwapper == null) {
LOGGER.debug("Starting HotSwapperJpda agent on JPDA transport socket - port {}, classloader {}", port, HotswapperCommand.class.getClassLoader());
try {
hotSwapper = new HotSwapperJpda(port);
} catch (IOException e) {
LOGGER.error("Unable to connect to debug session. Did you start the application with debug enabled " +
"(i.e. java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000)", e);
} catch (Exception e) {
LOGGER.error("Unable to connect to debug session. Please check port property setting '{}'.", e, port);
}
}
if (hotSwapper != null) {
LOGGER.debug("Reloading classes {}", Arrays.toString(reloadMap.keySet().toArray()));
// convert to Map Class name -> bytecode
// We loose some information here, reload use always first class name that it finds reference to.
Map<String, byte[]> reloadMapClassNames = new HashMap<>();
for (Map.Entry<Class<?>, byte[]> entry : reloadMap.entrySet()) {
reloadMapClassNames.put(entry.getKey().getName(), entry.getValue());
}
// actual hotswap via JPDA
hotSwapper.reload(reloadMapClassNames);
reloadMap.clear();
LOGGER.debug("HotSwapperJpda agent reload complete.");
}
}
| 175 | 437 | 612 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/plugin/hotswapper/HotswapperPlugin.java | HotswapperPlugin | initHotswapCommand | class HotswapperPlugin {
private static AgentLogger LOGGER = AgentLogger.getLogger(HotswapperPlugin.class);
@Init
Scheduler scheduler;
@Init
PluginManager pluginManager;
// synchronize on this map to wait for previous processing
final Map<Class<?>, byte[]> reloadMap = new HashMap<>();
// command to do actual hotswap. Single command to merge possible multiple reload actions.
Command hotswapCommand;
/**
* For each changed class create a reload command.
*/
@OnClassFileEvent(classNameRegexp = ".*", events = {FileEvent.MODIFY, FileEvent.CREATE})
public void watchReload(CtClass ctClass, ClassLoader appClassLoader, URL url) throws IOException, CannotCompileException {
if (!ClassLoaderHelper.isClassLoaded(appClassLoader, ctClass.getName())) {
LOGGER.trace("Class {} not loaded yet, no need for autoHotswap, skipped URL {}", ctClass.getName(), url);
return;
}
LOGGER.debug("Class {} will be reloaded from URL {}", ctClass.getName(), url);
// search for a class to reload
Class clazz;
try {
clazz = appClassLoader.loadClass(ctClass.getName());
} catch (ClassNotFoundException e) {
LOGGER.warning("Hotswapper tries to reload class {}, which is not known to application classLoader {}.",
ctClass.getName(), appClassLoader);
return;
}
synchronized (reloadMap) {
reloadMap.put(clazz, ctClass.toBytecode());
}
scheduler.scheduleCommand(hotswapCommand, 100, Scheduler.DuplicateSheduleBehaviour.SKIP);
}
/**
* Create a hotswap command using hotSwappper.
*
* @param appClassLoader it can be run in any classloader with tools.jar on classpath. AppClassLoader can
* be setup by maven dependency (jetty plugin), use this classloader.
* @param port attach the hotswapper
*/
public void initHotswapCommand(ClassLoader appClassLoader, String port) {<FILL_FUNCTION_BODY>}
/**
* For each classloader check for autoHotswap configuration instance with hotswapper.
*/
@Init
public static void init(PluginConfiguration pluginConfiguration, ClassLoader appClassLoader) {
if (appClassLoader == null) {
LOGGER.debug("Bootstrap class loader is null, hotswapper skipped.");
return;
}
LOGGER.debug("Init plugin at classLoader {}", appClassLoader);
// init only if the classloader contains directly the property file (not in parent classloader)
if (!HotswapAgent.isAutoHotswap() && !pluginConfiguration.containsPropertyFile()) {
LOGGER.debug("ClassLoader {} does not contain hotswap-agent.properties file, hotswapper skipped.", appClassLoader);
return;
}
// and autoHotswap enabled
if (!HotswapAgent.isAutoHotswap() && !pluginConfiguration.getPropertyBoolean("autoHotswap")) {
LOGGER.debug("ClassLoader {} has autoHotswap disabled, hotswapper skipped.", appClassLoader);
return;
}
String port = pluginConfiguration.getProperty("autoHotswap.port");
HotswapperPlugin plugin = PluginManagerInvoker.callInitializePlugin(HotswapperPlugin.class, appClassLoader);
if (plugin != null) {
plugin.initHotswapCommand(appClassLoader, port);
} else {
LOGGER.debug("Hotswapper is disabled in {}", appClassLoader);
}
}
} |
if (port != null && port.length() > 0) {
hotswapCommand = new ReflectionCommand(this, HotswapperCommand.class.getName(), "hotswap", appClassLoader,
port, reloadMap);
} else {
hotswapCommand = new Command() {
@Override
public void executeCommand() {
pluginManager.hotswap(reloadMap);
}
@Override
public String toString() {
return "pluginManager.hotswap(" + Arrays.toString(reloadMap.keySet().toArray()) + ")";
}
};
}
| 992 | 163 | 1,155 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/plugin/jdk/JdkPlugin.java | JdkPlugin | flushObjectStreamCaches | class JdkPlugin {
private static AgentLogger LOGGER = AgentLogger.getLogger(JdkPlugin.class);
/**
* Flag to check reload status. It is necessary (in unit tests)to wait for reload is finished before the test
* can continue. Set flag to true in the test class and wait until the flag is false again.
*/
public static boolean reloadFlag;
@OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE, skipSynthetic=false)
public static void flushBeanIntrospectorCaches(ClassLoader classLoader, CtClass ctClass) {
try {
LOGGER.debug("Flushing {} from introspector", ctClass.getName());
Class<?> clazz = classLoader.loadClass(ctClass.getName());
Class<?> threadGroupCtxClass = classLoader.loadClass("java.beans.ThreadGroupContext");
Class<?> introspectorClass = classLoader.loadClass("java.beans.Introspector");
synchronized (classLoader) {
Object contexts = ReflectionHelper.get(null, threadGroupCtxClass, "contexts");
Object table[] = (Object[]) ReflectionHelper.get(contexts, "table");
if (table != null) {
for (Object o: table) {
if (o != null) {
Object threadGroupContext = ReflectionHelper.get(o, "value");
if (threadGroupContext != null) {
LOGGER.trace("Removing from threadGroupContext");
ReflectionHelper.invoke(threadGroupContext, threadGroupCtxClass, "removeBeanInfo",
new Class[] { Class.class }, clazz);
}
}
}
}
ReflectionHelper.invoke(null, introspectorClass, "flushFromCaches",
new Class[] { Class.class }, clazz);
}
} catch (Exception e) {
LOGGER.error("flushBeanIntrospectorCaches() exception {}.", e.getMessage());
} finally {
reloadFlag = false;
}
}
@OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE, skipSynthetic=false)
public static void flushObjectStreamCaches(ClassLoader classLoader, CtClass ctClass) {<FILL_FUNCTION_BODY>}
} |
Class<?> clazz;
Object localDescs;
Object reflectors;
try {
LOGGER.debug("Flushing {} from ObjectStreamClass caches", ctClass.getName());
clazz = classLoader.loadClass(ctClass.getName());
Class<?> objectStreamClassCache = classLoader.loadClass("java.io.ObjectStreamClass$Caches");
localDescs = ReflectionHelper.get(null, objectStreamClassCache, "localDescs");
reflectors = ReflectionHelper.get(null, objectStreamClassCache, "reflectors");
} catch (Exception e) {
LOGGER.error("flushObjectStreamCaches() java.io.ObjectStreamClass$Caches not found.", e.getMessage());
return;
}
boolean java17;
try {
((Map) localDescs).clear();
((Map) reflectors).clear();
java17 = false;
} catch (Exception e) {
java17 = true;
}
if (java17) {
try {
Object localDescsMap = ReflectionHelper.get(localDescs, "map");
ReflectionHelper.invoke(localDescsMap, localDescsMap.getClass(), "remove", new Class[] { Class.class }, clazz);
Object reflectorsMap = ReflectionHelper.get(reflectors, "map");
ReflectionHelper.invoke(reflectorsMap, reflectorsMap.getClass(), "remove", new Class[] { Class.class }, clazz);
} catch (Exception e) {
LOGGER.error("flushObjectStreamCaches() exception {}.", e.getMessage());
}
}
| 590 | 410 | 1,000 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/plugin/jvm/AnonymousClassInfo.java | AnonymousClassInfo | getMethodSignature | class AnonymousClassInfo {
// name of the anonymous class
String className;
// signatures
String classSignature;
String methodSignature;
String fieldsSignature;
String enclosingMethodSignature;
public AnonymousClassInfo(Class c) {
this.className = c.getName();
StringBuilder classSignature = new StringBuilder(c.getSuperclass().getName());
for (Class intef : c.getInterfaces()) {
classSignature.append(";");
classSignature.append(intef.getName());
}
this.classSignature = classSignature.toString();
StringBuilder methodsSignature = new StringBuilder();
for (Method m : c.getDeclaredMethods()) {
getMethodSignature(methodsSignature, m);
}
this.methodSignature = methodsSignature.toString();
StringBuilder fieldsSignature = new StringBuilder();
for (Field f : c.getDeclaredFields()) {
// replace declarig class for constant because of unit tests (class name change)
fieldsSignature.append(f.getType().getName());
fieldsSignature.append(" ");
fieldsSignature.append(f.getName());
fieldsSignature.append(";");
}
this.fieldsSignature = fieldsSignature.toString();
StringBuilder enclosingMethodSignature = new StringBuilder();
Method enclosingMethod = c.getEnclosingMethod();
if (enclosingMethod != null) {
getMethodSignature(enclosingMethodSignature, enclosingMethod);
}
this.enclosingMethodSignature = enclosingMethodSignature.toString();
}
public AnonymousClassInfo(String className) {
this.className = className;
}
private void getMethodSignature(StringBuilder methodsSignature, Method m) {
methodsSignature.append(m.getReturnType().getName());
methodsSignature.append(" ");
methodsSignature.append(m.getName());
methodsSignature.append("(");
for (Class paramType : m.getParameterTypes())
methodsSignature.append(paramType.getName());
methodsSignature.append(")");
methodsSignature.append(";");
}
public AnonymousClassInfo(CtClass c) {
try {
this.className = c.getName();
StringBuilder classSignature = new StringBuilder(c.getSuperclassName());
for (CtClass intef : c.getInterfaces()) {
classSignature.append(";");
classSignature.append(intef.getName());
}
this.classSignature = classSignature.toString();
StringBuilder methodsSignature = new StringBuilder();
for (CtMethod m : c.getDeclaredMethods()) {
getMethodSignature(methodsSignature, m);
}
this.methodSignature = methodsSignature.toString();
StringBuilder fieldsSignature = new StringBuilder();
for (CtField f : c.getDeclaredFields()) {
fieldsSignature.append(f.getType().getName());
fieldsSignature.append(" ");
fieldsSignature.append(f.getName());
fieldsSignature.append(";");
}
this.fieldsSignature = fieldsSignature.toString();
StringBuilder enclosingMethodSignature = new StringBuilder();
try {
CtMethod enclosingMethod = c.getEnclosingMethod();
if (enclosingMethod != null) {
getMethodSignature(enclosingMethodSignature, enclosingMethod);
}
} catch (Exception e) {
// OK, enclosing method not defined or out of scope
}
this.enclosingMethodSignature = enclosingMethodSignature.toString();
} catch (Throwable t) {
throw new IllegalStateException("Error creating AnonymousClassInfo from " + c.getName(), t);
}
}
private void getMethodSignature(StringBuilder methodsSignature, CtMethod m) throws NotFoundException {<FILL_FUNCTION_BODY>}
public String getClassName() {
return className;
}
public String getClassSignature() {
return classSignature;
}
public String getMethodSignature() {
return methodSignature;
}
public String getFieldsSignature() {
return fieldsSignature;
}
public String getEnclosingMethodSignature() {
return enclosingMethodSignature;
}
/**
* Exact match including enclosing method.
*/
public boolean matchExact(AnonymousClassInfo other) {
return getClassSignature().equals(other.getClassSignature()) &&
getMethodSignature().equals(other.getMethodSignature()) &&
getFieldsSignature().equals(other.getFieldsSignature()) &&
getEnclosingMethodSignature().equals(other.getEnclosingMethodSignature());
}
/**
* Exact match of class, interfaces, declared methods and fields.
* May be different enclosing method.
*/
public boolean matchSignatures(AnonymousClassInfo other) {
return getClassSignature().equals(other.getClassSignature()) &&
getMethodSignature().equals(other.getMethodSignature()) &&
getFieldsSignature().equals(other.getFieldsSignature());
}
/**
* The least matching variant - same class signature can be still resolved by hotswap.
*/
public boolean matchClassSignature(AnonymousClassInfo other) {
return getClassSignature().equals(other.getClassSignature());
}
} |
methodsSignature.append(m.getReturnType().getName());
methodsSignature.append(" ");
methodsSignature.append(m.getName());
methodsSignature.append("(");
for (CtClass paramType : m.getParameterTypes())
methodsSignature.append(paramType.getName());
methodsSignature.append(")");
methodsSignature.append(";");
| 1,315 | 92 | 1,407 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/plugin/jvm/ClassInitPlugin.java | ClassInitPlugin | patch | class ClassInitPlugin {
private static AgentLogger LOGGER = AgentLogger.getLogger(ClassInitPlugin.class);
private static final String HOTSWAP_AGENT_CLINIT_METHOD = "$$ha$clinit";
public static boolean reloadFlag;
@OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE)
public static void patch(final CtClass ctClass, final ClassLoader classLoader, final Class<?> originalClass) throws IOException, CannotCompileException, NotFoundException {<FILL_FUNCTION_BODY>}
private static boolean checkOldEnumValues(CtClass ctClass, Class<?> originalClass) {
if (ctClass.isEnum()) {
// Check if some field from original enumeration was deleted
Enum<?>[] enumConstants = (Enum<?>[]) originalClass.getEnumConstants();
for (Enum<?> en : enumConstants) {
try {
CtField existing = ctClass.getDeclaredField(en.toString());
} catch (NotFoundException e) {
LOGGER.debug("Enum field deleted. $VALUES will be reinitialized {}", en.toString());
return true;
}
}
} else {
LOGGER.error("Patching " + HOTSWAP_AGENT_CLINIT_METHOD + " method failed. Enum type expected {}", ctClass.getName());
}
return false;
}
private static boolean isSyntheticClass(Class<?> classBeingRedefined) {
return classBeingRedefined.getSimpleName().contains("$$_javassist")
|| classBeingRedefined.getSimpleName().contains("$$_jvst")
|| classBeingRedefined.getName().startsWith("com.sun.proxy.$Proxy")
|| classBeingRedefined.getSimpleName().contains("$$");
}
} |
if (isSyntheticClass(originalClass)) {
return;
}
final String className = ctClass.getName();
try {
CtMethod origMethod = ctClass.getDeclaredMethod(HOTSWAP_AGENT_CLINIT_METHOD);
ctClass.removeMethod(origMethod);
} catch (org.hotswap.agent.javassist.NotFoundException ex) {
// swallow
}
CtConstructor clinit = ctClass.getClassInitializer();
if (clinit != null) {
LOGGER.debug("Adding " + HOTSWAP_AGENT_CLINIT_METHOD + " to class: {}", className);
CtConstructor haClinit = new CtConstructor(clinit, ctClass, null);
haClinit.getMethodInfo().setName(HOTSWAP_AGENT_CLINIT_METHOD);
haClinit.setModifiers(Modifier.PUBLIC | Modifier.STATIC);
ctClass.addConstructor(haClinit);
final boolean reinitializeStatics[] = new boolean[] { false };
haClinit.instrument(
new ExprEditor() {
public void edit(FieldAccess f) throws CannotCompileException {
try {
if (f.isStatic() && f.isWriter()) {
Field originalField = null;
try {
originalField = originalClass.getDeclaredField(f.getFieldName());
} catch (NoSuchFieldException e) {
LOGGER.debug("New field will be initialized {}", f.getFieldName());
reinitializeStatics[0] = true;
}
if (originalField != null) {
// Enum class contains an array field, in javac it's name starts with $VALUES,
// in eclipse compiler starts with ENUM$VALUES
if (originalClass.isEnum() && f.getSignature().startsWith("[L")
&& (f.getFieldName().startsWith("$VALUES")
|| f.getFieldName().startsWith("ENUM$VALUES"))) {
if (reinitializeStatics[0]) {
LOGGER.debug("New field will be initialized {}", f.getFieldName());
} else {
reinitializeStatics[0] = checkOldEnumValues(ctClass, originalClass);
}
} else {
LOGGER.debug("Skipping old field {}", f.getFieldName());
f.replace("{}");
}
}
}
} catch (Exception e) {
LOGGER.error("Patching " + HOTSWAP_AGENT_CLINIT_METHOD + " method failed.", e);
}
}
}
);
if (reinitializeStatics[0]) {
PluginManager.getInstance().getScheduler().scheduleCommand(new Command() {
@Override
public void executeCommand() {
try {
Class<?> clazz = classLoader.loadClass(className);
Method m = clazz.getDeclaredMethod(HOTSWAP_AGENT_CLINIT_METHOD, new Class[] {});
if (m != null) {
m.setAccessible(true);
m.invoke(null, new Object[] {});
LOGGER.debug("Initializer {} invoked for class {}", HOTSWAP_AGENT_CLINIT_METHOD, className);
} else {
LOGGER.error("Class initializer {} not found", HOTSWAP_AGENT_CLINIT_METHOD);
}
} catch (Exception e) {
LOGGER.error("Error initializing redefined class {}", e, className);
} finally {
reloadFlag = false;
}
}
}, 150); // Hack : init must be called after dependant class redefinition. Since the class can
// be proxied, the class init must be scheduled after proxy redefinition. Currently proxy
// redefinition (in ProxyPlugin) is scheduled with 100ms delay, therefore we use delay 150ms.
} else {
reloadFlag = false;
}
}
| 474 | 1,032 | 1,506 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/plugin/watchResources/WatchResourcesPlugin.java | WatchResourcesPlugin | init | class WatchResourcesPlugin {
private static AgentLogger LOGGER = AgentLogger.getLogger(WatchResourcesPlugin.class);
@Init
Watcher watcher;
@Init
ClassLoader appClassLoader;
// Classloader to return only modified resources on watchResources path.
WatchResourcesClassLoader watchResourcesClassLoader = new WatchResourcesClassLoader(false);
/**
* For each classloader check for watchResources configuration instance with hotswapper.
*/
@Init
public static void init(PluginManager pluginManager, PluginConfiguration pluginConfiguration, ClassLoader appClassLoader) {<FILL_FUNCTION_BODY>}
/**
* Init the plugin instance for resources.
*
* @param watchResources resources to watch
*/
private void init(URL[] watchResources) {
// configure the classloader to return only changed resources on watchResources path
watchResourcesClassLoader.initWatchResources(watchResources, watcher);
if (appClassLoader instanceof HotswapAgentClassLoaderExt) {
((HotswapAgentClassLoaderExt) appClassLoader).$$ha$setWatchResourceLoader(watchResourcesClassLoader);
} else if (URLClassPathHelper.isApplicable(appClassLoader)) {
// modify the application classloader to look for resources first in watchResourcesClassLoader
URLClassPathHelper.setWatchResourceLoader(appClassLoader, watchResourcesClassLoader);
}
}
} |
LOGGER.debug("Init plugin at classLoader {}", appClassLoader);
// synthetic classloader, skip
if (appClassLoader instanceof WatchResourcesClassLoader.UrlOnlyClassLoader)
return;
// init only if the classloader contains directly the property file (not in parent classloader)
if (!pluginConfiguration.containsPropertyFile()) {
LOGGER.debug("ClassLoader {} does not contain hotswap-agent.properties file, WatchResources skipped.", appClassLoader);
return;
}
// and watch resources are set
URL[] watchResources = pluginConfiguration.getWatchResources();
if (watchResources.length == 0) {
LOGGER.debug("ClassLoader {} has hotswap-agent.properties watchResources empty.", appClassLoader);
return;
}
if (!URLClassPathHelper.isApplicable(appClassLoader) &&
!(appClassLoader instanceof HotswapAgentClassLoaderExt)) {
LOGGER.warning("Unable to modify application classloader. Classloader '{}' is of type '{}'," +
"unknown classloader type.\n" +
"*** watchResources configuration property will not be handled on JVM level ***",
appClassLoader, appClassLoader.getClass());
return;
}
// create new plugin instance
WatchResourcesPlugin plugin = (WatchResourcesPlugin) pluginManager.getPluginRegistry()
.initializePlugin(WatchResourcesPlugin.class.getName(), appClassLoader);
// and init it with watchResources path
plugin.init(watchResources);
| 347 | 375 | 722 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/AnnotationHelper.java | AnnotationHelper | hasAnnotation | class AnnotationHelper {
public static boolean hasAnnotation(Class clazz, String annotationClass) {<FILL_FUNCTION_BODY>}
public static boolean hasAnnotation(CtClass clazz, String annotationClass) {
AnnotationsAttribute ainfo = (AnnotationsAttribute) clazz.getClassFile2().
getAttribute(AnnotationsAttribute.visibleTag);
if (ainfo != null) {
for (org.hotswap.agent.javassist.bytecode.annotation.Annotation annot : ainfo.getAnnotations()) {
if (annot.getTypeName().equals(annotationClass))
return true;
}
}
return false;
}
public static boolean hasAnnotation(Class<?> clazz, Iterable<String> annotationClasses) {
for (String pathAnnotation : annotationClasses) {
if (AnnotationHelper.hasAnnotation(clazz, pathAnnotation)) {
return true;
}
}
return false;
}
public static boolean hasAnnotation(CtClass clazz, Iterable<String> annotationClasses) {
for (String pathAnnotation : annotationClasses) {
if (AnnotationHelper.hasAnnotation(clazz, pathAnnotation)) {
return true;
}
}
return false;
}
} |
for (Annotation annot : clazz.getDeclaredAnnotations())
if (annot.annotationType().getName().equals(annotationClass))
return true;
return false;
| 315 | 46 | 361 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/AppClassLoaderExecutor.java | AppClassLoaderExecutor | execute | class AppClassLoaderExecutor {
private static AgentLogger LOGGER = AgentLogger.getLogger(AnnotationProcessor.class);
ClassLoader appClassLoader;
ProtectionDomain protectionDomain;
public AppClassLoaderExecutor(ClassLoader appClassLoader, ProtectionDomain protectionDomain) {
this.appClassLoader = appClassLoader;
this.protectionDomain = protectionDomain;
}
public Object execute(String className, String method, Object... params)
throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {<FILL_FUNCTION_BODY>}
private boolean isSimpleType(Class<? extends Object> aClass) {
// primitive data types has null class loader
return aClass.getClassLoader() == null;
}
} |
LOGGER.error("Start");
PluginManager.getInstance().initClassLoader(appClassLoader, protectionDomain);
Class classInAppClassLoader = Class.forName(className, true, appClassLoader);
LOGGER.error("Executing: requestedClassLoader={}, resolvedClassLoader={}, class={}, method={}, params={}",
appClassLoader, classInAppClassLoader.getClassLoader(), classInAppClassLoader, method, params);
Class[] paramTypes = new Class[params.length];
for (int i = 0; i < params.length; i++) {
if (params[i] == null)
throw new IllegalArgumentException("Cannot execute for null parameter classNameRegexp");
else if (!isSimpleType(params[i].getClass())) {
throw new IllegalArgumentException("Use only simple parameter values.");
} else {
paramTypes[i] = params[i].getClass();
}
}
Object instance = classInAppClassLoader.newInstance();
Method m = classInAppClassLoader.getDeclaredMethod(method, paramTypes);
Thread.currentThread().setContextClassLoader(appClassLoader);
return m.invoke(instance, params);
| 193 | 297 | 490 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/HotswapProperties.java | HotswapProperties | substitute | class HotswapProperties extends Properties {
private static final long serialVersionUID = 4467598209091707788L;
private static final Pattern VAR_PATTERN = Pattern.compile("\\$\\{([a-zA-Z0-9._]+?)\\}");
@Override
public Object put(Object key, Object value) {
return super.put(key, substitute(value));
}
private Object substitute(Object obj) {<FILL_FUNCTION_BODY>}
} |
if (obj instanceof String) {
StringBuffer result = new StringBuffer();
Matcher m = VAR_PATTERN.matcher((String) obj);
while (m.find()) {
String replacement = System.getProperty(m.group(1));
if (replacement != null) {
m.appendReplacement(result, replacement);
}
}
m.appendTail(result);
return result.toString();
}
return obj;
| 142 | 121 | 263 | <methods>public void <init>() ,public void <init>(int) ,public void <init>(java.util.Properties) ,public synchronized void clear() ,public synchronized java.lang.Object clone() ,public synchronized java.lang.Object compute(java.lang.Object, BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public synchronized java.lang.Object computeIfAbsent(java.lang.Object, Function<? super java.lang.Object,?>) ,public synchronized java.lang.Object computeIfPresent(java.lang.Object, BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public boolean contains(java.lang.Object) ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public Enumeration<java.lang.Object> elements() ,public Set<Entry<java.lang.Object,java.lang.Object>> entrySet() ,public synchronized boolean equals(java.lang.Object) ,public synchronized void forEach(BiConsumer<? super java.lang.Object,? super java.lang.Object>) ,public java.lang.Object get(java.lang.Object) ,public java.lang.Object getOrDefault(java.lang.Object, java.lang.Object) ,public java.lang.String getProperty(java.lang.String) ,public java.lang.String getProperty(java.lang.String, java.lang.String) ,public synchronized int hashCode() ,public boolean isEmpty() ,public Set<java.lang.Object> keySet() ,public Enumeration<java.lang.Object> keys() ,public void list(java.io.PrintStream) ,public void list(java.io.PrintWriter) ,public synchronized void load(java.io.Reader) throws java.io.IOException,public synchronized void load(java.io.InputStream) throws java.io.IOException,public synchronized void loadFromXML(java.io.InputStream) throws java.io.IOException, java.util.InvalidPropertiesFormatException,public synchronized java.lang.Object merge(java.lang.Object, java.lang.Object, BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public Enumeration<?> propertyNames() ,public synchronized java.lang.Object put(java.lang.Object, java.lang.Object) ,public synchronized void putAll(Map<?,?>) ,public synchronized java.lang.Object putIfAbsent(java.lang.Object, java.lang.Object) ,public synchronized java.lang.Object remove(java.lang.Object) ,public synchronized boolean remove(java.lang.Object, java.lang.Object) ,public synchronized java.lang.Object replace(java.lang.Object, java.lang.Object) ,public synchronized boolean replace(java.lang.Object, java.lang.Object, java.lang.Object) ,public synchronized void replaceAll(BiFunction<? super java.lang.Object,? super java.lang.Object,?>) ,public void save(java.io.OutputStream, java.lang.String) ,public synchronized java.lang.Object setProperty(java.lang.String, java.lang.String) ,public int size() ,public void store(java.io.Writer, java.lang.String) throws java.io.IOException,public void store(java.io.OutputStream, java.lang.String) throws java.io.IOException,public void storeToXML(java.io.OutputStream, java.lang.String) throws java.io.IOException,public void storeToXML(java.io.OutputStream, java.lang.String, java.lang.String) throws java.io.IOException,public void storeToXML(java.io.OutputStream, java.lang.String, java.nio.charset.Charset) throws java.io.IOException,public Set<java.lang.String> stringPropertyNames() ,public synchronized java.lang.String toString() ,public Collection<java.lang.Object> values() <variables>private static final jdk.internal.misc.Unsafe UNSAFE,protected volatile java.util.Properties defaults,private volatile transient ConcurrentHashMap<java.lang.Object,java.lang.Object> map,private static final long serialVersionUID |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/HotswapTransformer.java | RegisteredTransformersRecord | closeClassLoader | class RegisteredTransformersRecord {
Pattern pattern;
List<HaClassFileTransformer> transformerList = new LinkedList<>();
}
protected Map<String, RegisteredTransformersRecord> redefinitionTransformers = new LinkedHashMap<>();
protected Map<String, RegisteredTransformersRecord> otherTransformers = new LinkedHashMap<>();
// keep track about which classloader requested which transformer
protected Map<ClassFileTransformer, ClassLoader> classLoaderTransformers = new LinkedHashMap<>();
protected Map<ClassLoader, Boolean> seenClassLoaders = new WeakHashMap<>();
private List<Pattern> includedClassLoaderPatterns;
private List<Pattern> excludedClassLoaderPatterns;
public List<Pattern> getIncludedClassLoaderPatterns() {
return includedClassLoaderPatterns;
}
public void setIncludedClassLoaderPatterns(List<Pattern> includedClassLoaderPatterns) {
this.includedClassLoaderPatterns = includedClassLoaderPatterns;
}
/**
* @param excludedClassLoaderPatterns
* the excludedClassLoaderPatterns to set
*/
public void setExcludedClassLoaderPatterns(List<Pattern> excludedClassLoaderPatterns) {
this.excludedClassLoaderPatterns = excludedClassLoaderPatterns;
}
public List<Pattern> getExcludedClassLoaderPatterns() {
return excludedClassLoaderPatterns;
}
/**
* Register a transformer for a regexp matching class names.
* Used by {@link org.hotswap.agent.annotation.OnClassLoadEvent} annotation respective
* {@link org.hotswap.agent.annotation.handler.OnClassLoadedHandler}.
*
* @param classLoader the classloader to which this transformation is associated
* @param classNameRegexp regexp to match fully qualified class name.
* Because "." is any character in regexp, this will match / in the transform method as well
* (diffentence between java/lang/String and java.lang.String).
* @param transformer the transformer to be called for each class matching regexp.
*/
public void registerTransformer(ClassLoader classLoader, String classNameRegexp, HaClassFileTransformer transformer) {
LOGGER.debug("Registering transformer for class regexp '{}'.", classNameRegexp);
String normalizeRegexp = normalizeTypeRegexp(classNameRegexp);
Map<String, RegisteredTransformersRecord> transformersMap = getTransformerMap(transformer);
RegisteredTransformersRecord transformerRecord = transformersMap.get(normalizeRegexp);
if (transformerRecord == null) {
transformerRecord = new RegisteredTransformersRecord();
transformerRecord.pattern = Pattern.compile(normalizeRegexp);
transformersMap.put(normalizeRegexp, transformerRecord);
}
if (!transformerRecord.transformerList.contains(transformer)) {
transformerRecord.transformerList.add(transformer);
}
// register classloader association to allow classloader unregistration
if (classLoader != null) {
classLoaderTransformers.put(transformer, classLoader);
}
}
private Map<String, RegisteredTransformersRecord> getTransformerMap(HaClassFileTransformer transformer) {
if (transformer.isForRedefinitionOnly()) {
return redefinitionTransformers;
}
return otherTransformers;
}
/**
* Remove registered transformer.
*
* @param classNameRegexp regexp to match fully qualified class name.
* @param transformer currently registered transformer
*/
public void removeTransformer(String classNameRegexp, HaClassFileTransformer transformer) {
String normalizeRegexp = normalizeTypeRegexp(classNameRegexp);
Map<String, RegisteredTransformersRecord> transformersMap = getTransformerMap(transformer);
RegisteredTransformersRecord transformerRecord = transformersMap.get(normalizeRegexp);
if (transformerRecord != null) {
transformerRecord.transformerList.remove(transformer);
}
}
/**
* Remove all transformers registered with a classloader
* @param classLoader
*/
public void closeClassLoader(ClassLoader classLoader) {<FILL_FUNCTION_BODY> |
for (Iterator<Map.Entry<ClassFileTransformer, ClassLoader>> entryIterator = classLoaderTransformers.entrySet().iterator();
entryIterator.hasNext(); ) {
Map.Entry<ClassFileTransformer, ClassLoader> entry = entryIterator.next();
if (entry.getValue().equals(classLoader)) {
entryIterator.remove();
for (RegisteredTransformersRecord transformerRecord : redefinitionTransformers.values()) {
transformerRecord.transformerList.remove(entry.getKey());
}
for (RegisteredTransformersRecord transformerRecord : otherTransformers.values()) {
transformerRecord.transformerList.remove(entry.getKey());
}
}
}
LOGGER.debug("All transformers removed for classLoader {}", classLoader);
| 1,058 | 189 | 1,247 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/IOUtils.java | IOUtils | streamToString | class IOUtils {
private static final AgentLogger LOGGER = AgentLogger.getLogger(IOUtils.class);
// some IDEs remove and recreate whole package multiple times while recompiling -
// we may need to wait for a file to be available on a filesystem
private static final int WAIT_FOR_FILE_MAX_SECONDS = 5;
/** URL protocol for a file in the file system: "file" */
public static final String URL_PROTOCOL_FILE = "file";
/** URL protocol for a JBoss VFS resource: "vfs" */
public static final String URL_PROTOCOL_VFS = "vfs";
/**
* Download URI to byte array.
*
* Wait for the file to exists up to 5 seconds - it may be recreated while IDE recompilation,
* automatic retry will avoid false errors.
*
* @param uri uri to process
* @return byte array
* @throws IllegalArgumentException for download problems
*/
public static byte[] toByteArray(URI uri) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
InputStream inputStream = null;
int tryCount = 0;
while (inputStream == null) {
try {
inputStream = uri.toURL().openStream();
} catch (FileNotFoundException e) {
// some IDEs remove and recreate whole package multiple times while recompiling -
// we may need to waitForResult for the file.
if (tryCount > WAIT_FOR_FILE_MAX_SECONDS * 10) {
LOGGER.trace("File not found, exiting with exception...", e);
throw new IllegalArgumentException(e);
} else {
tryCount++;
LOGGER.trace("File not found, waiting...", e);
try {
Thread.sleep(100);
} catch (InterruptedException ignore) {
}
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
LOGGER.error("Can't close file.", e);
}
}
}
}
try (InputStream stream = uri.toURL().openStream()) {
byte[] chunk = new byte[4096];
int bytesRead;
while ((bytesRead = stream.read(chunk)) > 0) {
outputStream.write(chunk, 0, bytesRead);
}
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
return outputStream.toByteArray();
}
/**
* Convert input stream to a string.
* @param is stream
* @return string (at least empty string for empty stream)
*/
public static String streamToString(InputStream is) {<FILL_FUNCTION_BODY>}
/**
* Determine whether the given URL points to a resource in the file system,
* that is, has protocol "file" or "vfs".
* @param url the URL to check
* @return whether the URL has been identified as a file system URL
* @author Juergen Hoeller (org.springframework.util.ResourceUtils)
*/
public static boolean isFileURL(URL url) {
String protocol = url.getProtocol();
return (URL_PROTOCOL_FILE.equals(protocol) || protocol.startsWith(URL_PROTOCOL_VFS));
}
/**
* Determine whether the given URL points to a directory in the file system
*
* @param url the URL to check
* @return whether the URL has been identified as a file system URL
*/
public static boolean isDirectoryURL(URL url) {
try {
File f = new File(url.toURI());
if(f.exists() && f.isDirectory()) {
return true;
}
} catch (Exception ignore) {
}
return false;
}
/**
* Return fully qualified class name of class file on a URI.
*
* @param uri uri of class file
* @return name
* @throws IOException any exception on class instantiation
*/
public static String urlToClassName(URI uri) throws IOException {
return ClassPool.getDefault().makeClass(uri.toURL().openStream()).getName();
}
/**
* Extract file name from input stream.
*
* @param is the is
* @return the string
*/
public static String extractFileNameFromInputStream(InputStream is) {
try {
if ("sun.nio.ch.ChannelInputStream".equals(is.getClass().getName())) {
ReadableByteChannel ch = (ReadableByteChannel) ReflectionHelper.get(is, "ch");
return ch instanceof FileChannel ? (String) ReflectionHelper.get(ch, "path") : null;
}
while (true) {
if (is instanceof FileInputStream) {
return (String) ReflectionHelper.get(is, "path");
}
if (!(is instanceof FilterInputStream)) {
break;
}
is = (InputStream) ReflectionHelper.get(is, "in");
}
} catch (IllegalArgumentException e) {
LOGGER.error("extractFileNameFromInputStream() failed.", e);
}
return null;
}
/**
* Extract file name from reader.
*
* @param reader the reader
* @return the string
*/
public static String extractFileNameFromReader(Reader reader) {
try {
if (reader instanceof InputStreamReader) {
InputStream is = (InputStream) ReflectionHelper.get(reader, "lock");
return extractFileNameFromInputStream(is);
}
} catch (IllegalArgumentException e) {
LOGGER.error("extractFileNameFromReader() failed.", e);
}
return null;
}
/**
* Extract file name from input source.
*
* @param inputSource the input source
* @return the string
*/
public static String extractFileNameFromInputSource(InputSource inputSource) {
if (inputSource.getByteStream() != null) {
return extractFileNameFromInputStream(inputSource.getByteStream());
}
if (inputSource.getCharacterStream() != null) {
return extractFileNameFromReader(inputSource.getCharacterStream());
}
return null;
}
} |
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
| 1,609 | 46 | 1,655 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/PluginManagerInvoker.java | PluginManagerInvoker | buildCallPluginMethod | class PluginManagerInvoker {
/**
* Initialize plugin for a classloader.
*
* @param pluginClass identify plugin instance
* @param appClassLoader classloader in which the plugin should reside
*/
public static <T> T callInitializePlugin(Class<T> pluginClass, ClassLoader appClassLoader) {
// noinspection unchecked
return (T) PluginManager.getInstance().getPluginRegistry().initializePlugin(
pluginClass.getName(), appClassLoader
);
}
public static String buildInitializePlugin(Class pluginClass) {
return buildInitializePlugin(pluginClass, "getClass().getClassLoader()");
}
public static String buildInitializePlugin(Class pluginClass, String classLoaderVar) {
return "org.hotswap.agent.config.PluginManager.getInstance().getPluginRegistry().initializePlugin(" +
"\"" + pluginClass.getName() + "\", " + classLoaderVar +
");";
}
/**
* Free all classloader references and close any associated plugin instance.
* Typical use is after webapp undeploy.
*
* @param appClassLoader clasloade to free
*/
public static void callCloseClassLoader(ClassLoader appClassLoader) {
PluginManager.getInstance().closeClassLoader(appClassLoader);
}
public static String buildCallCloseClassLoader(String classLoaderVar) {
return "org.hotswap.agent.config.PluginManager.getInstance().closeClassLoader(" + classLoaderVar + ");";
}
/**
* Methods on plugin should be called via reflection, because the real plugin object is in parent classloader,
* but plugin class may be defined in app classloader as well introducing ClassCastException on same class name.
*
* @param pluginClass class name of the plugin - it is used to resolve plugin instance from plugin manager
* @param appClassLoader application classloader (to resolve plugin instance)
* @param method method name
* @param paramTypes param types (as required by reflection)
* @param params actual param values
* @return method return value
*/
public static Object callPluginMethod(Class pluginClass, ClassLoader appClassLoader, String method, Class[] paramTypes, Object[] params) {
Object pluginInstance = PluginManager.getInstance().getPlugin(pluginClass.getName(), appClassLoader);
try {
Method m = pluginInstance.getClass().getDeclaredMethod(method, paramTypes);
return m.invoke(pluginInstance, params);
} catch (Exception e) {
throw new Error(String.format("Exception calling method %s on plugin class %s", method, pluginClass), e);
}
}
/**
* Equivalent to callPluginMethod for insertion into source code.
* <p/>
* PluginManagerInvoker.buildCallPluginMethod(this, "hibernateInitialized",
* "getClass().getClassLoader()", "java.lang.ClassLoader")
*
* @param pluginClass plugin to use
* @param method method name
* @param paramValueAndType for each param its value AND type must be provided
* @return method source code
*/
public static String buildCallPluginMethod(Class pluginClass, String method, String... paramValueAndType) {
return buildCallPluginMethod("getClass().getClassLoader()", pluginClass, method, paramValueAndType);
}
/**
* Same as {@link PluginManagerInvoker#buildCallPluginMethod(Class, String, String...)}, but with explicit
* appClassLoader variable. Use this method if appClassLoader is different from getClass().getClassLoader().
*/
public static String buildCallPluginMethod(String appClassLoaderVar, Class pluginClass,
String method, String... paramValueAndType) {<FILL_FUNCTION_BODY>}
} |
String managerClass = PluginManager.class.getName();
int paramCount = paramValueAndType.length / 2;
StringBuilder b = new StringBuilder();
// block to hide variables and catch checked exceptions
b.append("try {");
b.append("ClassLoader __pluginClassLoader = ");
b.append(managerClass);
b.append(".class.getClassLoader();");
// Object __pluginInstance = org.hotswap.agent.config.PluginManager.getInstance().getPlugin(org.hotswap.agent.plugin.TestPlugin.class.getName(), __pluginClassLoader);
b.append("Object __pluginInstance = ");
b.append(managerClass);
b.append(".getInstance().getPlugin(");
b.append(pluginClass.getName());
b.append(".class.getName(), " + appClassLoaderVar + ");");
// Class __pluginClass = __pluginClassLoader.loadClass("org.hotswap.agent.plugin.TestPlugin");
b.append("Class __pluginClass = ");
b.append("__pluginClassLoader.loadClass(\"");
b.append(pluginClass.getName());
b.append("\");");
// param types
b.append("Class[] paramTypes = new Class[" + paramCount + "];");
for (int i = 0; i < paramCount; i++) {
// paramTypes[i] = = __pluginClassLoader.loadClass("my.test.TestClass").getClass();
b.append("paramTypes[" + i + "] = __pluginClassLoader.loadClass(\"" + paramValueAndType[(i * 2) + 1] + "\");");
}
// java.lang.reflect.Method __pluginMethod = __pluginClass.getDeclaredMethod("method", paramType1, paramType2);
b.append("java.lang.reflect.Method __callPlugin = __pluginClass.getDeclaredMethod(\"");
b.append(method);
b.append("\", paramTypes");
b.append(");");
b.append("Object[] params = new Object[" + paramCount + "];");
for (int i = 0; i < paramCount; i = i + 1) {
b.append("params[" + i + "] = " + paramValueAndType[i * 2] + ";");
}
// __pluginMethod.invoke(__pluginInstance, param1, param2);
b.append("__callPlugin.invoke(__pluginInstance, params);");
// catch (Exception e) {throw new Error(e);}
b.append("} catch (Exception e) {throw new Error(e);}");
return b.toString();
| 948 | 659 | 1,607 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/Version.java | Version | version | class Version {
/**
* Return current version.
* @return the version.
*/
public static String version() {<FILL_FUNCTION_BODY>}
} |
try {
Properties prop = new Properties();
InputStream in = Version.class.getResourceAsStream("/version.properties");
prop.load(in);
in.close();
return prop.getProperty("version") == null ? "unkown" : prop.getProperty("version");
} catch (IOException e) {
return "unknown";
}
| 48 | 92 | 140 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/classloader/ClassLoaderDefineClassPatcher.java | ClassLoaderDefineClassPatcher | transferTo | class ClassLoaderDefineClassPatcher {
private static AgentLogger LOGGER = AgentLogger.getLogger(ClassLoaderDefineClassPatcher.class);
private static Map<String, List<byte[]>> pluginClassCache = new HashMap<>();
/**
* Patch the classloader.
*
* @param classLoaderFrom classloader to load classes from
* @param pluginPath path to copy
* @param classLoaderTo classloader to copy classes to
* @param protectionDomain required protection in target classloader
*/
public void patch(final ClassLoader classLoaderFrom, final String pluginPath,
final ClassLoader classLoaderTo, final ProtectionDomain protectionDomain) {
List<byte[]> cache = getPluginCache(classLoaderFrom, pluginPath);
if (cache != null) {
final ClassPool cp = new ClassPool();
cp.appendClassPath(new LoaderClassPath(getClass().getClassLoader()));
Set<String> loadedClasses = new HashSet<>();
String packagePrefix = pluginPath.replace('/', '.');
for (byte[] pluginBytes: cache) {
CtClass pluginClass = null;
try {
// force to load class in classLoaderFrom (it may not yet be loaded) and if the classLoaderTo
// is parent of classLoaderFrom, after definition in classLoaderTo will classLoaderFrom return
// class from parent classloader instead own definition (hence change of behaviour).
InputStream is = new ByteArrayInputStream(pluginBytes);
pluginClass = cp.makeClass(is);
try {
classLoaderFrom.loadClass(pluginClass.getName());
} catch (NoClassDefFoundError e) {
LOGGER.trace("Skipping class loading {} in classloader {} - " +
"class has probably unresolvable dependency.", pluginClass.getName(), classLoaderTo);
}
// and load the class in classLoaderTo as well. Now the class is defined in BOTH classloaders.
transferTo(pluginClass, packagePrefix, classLoaderTo, protectionDomain, loadedClasses);
} catch (CannotCompileException e) {
LOGGER.trace("Skipping class definition {} in app classloader {} - " +
"class is probably already defined.", pluginClass.getName(), classLoaderTo);
} catch (NoClassDefFoundError e) {
LOGGER.trace("Skipping class definition {} in app classloader {} - " +
"class has probably unresolvable dependency.", pluginClass.getName(), classLoaderTo);
} catch (Throwable e) {
LOGGER.trace("Skipping class definition app classloader {} - " +
"unknown error.", e, classLoaderTo);
}
}
}
LOGGER.debug("Classloader {} patched with plugin classes from agent classloader {}.", classLoaderTo, classLoaderFrom);
}
private void transferTo(CtClass pluginClass, String pluginPath, ClassLoader classLoaderTo,
ProtectionDomain protectionDomain, Set<String> loadedClasses) throws CannotCompileException {<FILL_FUNCTION_BODY>}
private List<byte[]> getPluginCache(final ClassLoader classLoaderFrom, final String pluginPath) {
List<byte[]> ret = null;
synchronized(pluginClassCache) {
ret = pluginClassCache.get(pluginPath);
if (ret == null) {
final List<byte[]> retList = new ArrayList<>();
Scanner scanner = new ClassPathScanner();
try {
scanner.scan(classLoaderFrom, pluginPath, new ScannerVisitor() {
@Override
public void visit(InputStream file) throws IOException {
// skip plugin classes
// TODO this should be skipped only in patching application classloader. To copy
// classes into agent classloader, Plugin class must be copied as well
// if (patchClass.hasAnnotation(Plugin.class)) {
// LOGGER.trace("Skipping plugin class: " + patchClass.getName());
// return;
// }
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int readBytes;
byte[] data = new byte[16384];
while ((readBytes = file.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, readBytes);
}
buffer.flush();
retList.add(buffer.toByteArray());
}
});
} catch (IOException e) {
LOGGER.error("Exception while scanning 'org/hotswap/agent/plugin'", e);
}
ret = retList;
pluginClassCache.put(pluginPath, ret);
}
}
return ret;
}
/**
* Check if the classloader can be patched.
* Typically skip synthetic classloaders.
*
* @param classLoader classloader to check
* @return if true, call patch()
*/
public boolean isPatchAvailable(ClassLoader classLoader) {
// we can define class in any class loader
// exclude synthetic classloader where it does not make any sense
// sun.reflect.DelegatingClassLoader - created automatically by JVM to optimize reflection calls
return classLoader != null &&
!classLoader.getClass().getName().equals("sun.reflect.DelegatingClassLoader") &&
!classLoader.getClass().getName().equals("jdk.internal.reflect.DelegatingClassLoader")
;
}
} |
// if the class is already loaded, skip it
if (loadedClasses.contains(pluginClass.getName()) || pluginClass.isFrozen() ||
!pluginClass.getName().startsWith(pluginPath)) {
return;
}
// 1. interface
try {
if (!pluginClass.isInterface()) {
CtClass[] ctClasses = pluginClass.getInterfaces();
if (ctClasses != null && ctClasses.length > 0) {
for (CtClass ctClass : ctClasses) {
try {
transferTo(ctClass, pluginPath, classLoaderTo, protectionDomain, loadedClasses);
} catch (Throwable e) {
LOGGER.trace("Skipping class loading {} in classloader {} - " +
"class has probably unresolvable dependency.", ctClass.getName(), classLoaderTo);
}
}
}
}
} catch (NotFoundException e) {
}
// 2. superClass
try {
CtClass ctClass = pluginClass.getSuperclass();
if (ctClass != null) {
try {
transferTo(ctClass, pluginPath, classLoaderTo, protectionDomain, loadedClasses);
} catch (Throwable e) {
LOGGER.trace("Skipping class loading {} in classloader {} - " +
"class has probably unresolvable dependency.", ctClass.getName(), classLoaderTo);
}
}
} catch (NotFoundException e) {
}
pluginClass.toClass(classLoaderTo, protectionDomain);
loadedClasses.add(pluginClass.getName());
| 1,331 | 396 | 1,727 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/classloader/ClassLoaderHelper.java | ClassLoaderHelper | isClassLoderStarted | class ClassLoaderHelper {
private static AgentLogger LOGGER = AgentLogger.getLogger(ClassLoaderHelper.class);
public static Method findLoadedClass;
static {
try {
findLoadedClass = ClassLoader.class.getDeclaredMethod("findLoadedClass", new Class[] { String.class });
findLoadedClass.setAccessible(true);
} catch (NoSuchMethodException e) {
LOGGER.error("Unexpected: failed to get ClassLoader findLoadedClass method", e);
}
}
/**
* Check if the class was already loaded by the classloader. It does not try to load the class
* (opposite to Class.forName()).
*
* @param classLoader classLoader to check
* @param className fully qualified class name
* @return true if the class was loaded
*/
public static boolean isClassLoaded(ClassLoader classLoader, String className) {
try {
return findLoadedClass.invoke(classLoader, className) != null;
} catch (Exception e) {
LOGGER.error("Unable to invoke findLoadedClass on classLoader {}, className {}", e, classLoader, className);
return false;
}
}
/**
* Some class loader has activity state. e.g. WebappClassLoader must be started before it can be used
*
* @param classLoader the class loader
* @return true, if is class loader active
*/
public static boolean isClassLoderStarted(ClassLoader classLoader) {<FILL_FUNCTION_BODY>}
} |
String classLoaderClassName = (classLoader != null) ? classLoader.getClass().getName() : null;
// TODO: use interface instead of this hack
if ("org.glassfish.web.loader.WebappClassLoader".equals(classLoaderClassName)||
"org.apache.catalina.loader.WebappClassLoader".equals(classLoaderClassName) ||
"org.apache.catalina.loader.ParallelWebappClassLoader".equals(classLoaderClassName) ||
"org.apache.tomee.catalina.TomEEWebappClassLoader".equals(classLoaderClassName) ||
"org.springframework.boot.web.embedded.tomcat.TomcatEmbeddedWebappClassLoader".equals(classLoaderClassName)
)
{
try {
Class<?> clazz = classLoader.getClass();
boolean isStarted;
if ("org.apache.catalina.loader.WebappClassLoaderBase".equals(clazz.getSuperclass().getName())) {
clazz = clazz.getSuperclass();
isStarted = "STARTED".equals((String) ReflectionHelper.invoke(classLoader, clazz, "getStateName", new Class[] {}, null));
} else {
isStarted = (boolean) ReflectionHelper.invoke(classLoader, clazz, "isStarted", new Class[] {}, null);
}
return isStarted;
} catch (Exception e) {
LOGGER.warning("isClassLoderStarted() : {}", e.getMessage());
}
}
return true;
| 391 | 389 | 780 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/classloader/ClassLoaderProxy.java | ClassLoaderProxy | create | class ClassLoaderProxy {
ClassLoader targetClassLoader;
public CtClass create(CtClass classToProxy) throws Exception {<FILL_FUNCTION_BODY>}
} |
// CtPool ctPool = classToProxy;
// ProxyFactory factory = new ProxyFactory();
// factory.setSuperclass(classToProxy);
// factory.
//
// Class proxy = factory.createClass();
//
// new ClassFile()
//
//
// MethodHandler handler = new MethodHandler() {
//
// @Override
// public Object invoke(Object self, Method overridden, Method forwarder,
// Object[] args) throws Throwable {
// System.out.println("do something "+overridden.getName());
//
// Class classInTargetClassLoader = targetClassLoader.loadClass(classToProxy.getName());
// Method methodInTargetClassLoader = classInTargetClassLoader.getDeclaredMethod(
// overridden.getName(), overridden.getParameterTypes()
// );
//
// Class returnType = overridden.getReturnType();
//
// return methodInTargetClassLoader.invoke(null, args);
// }
// };
// Object instance = proxy.newInstance();
// ((ProxyObject) instance).setHandler(handler);
// return (T) instance;
return null;
| 49 | 292 | 341 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/classloader/WatchResourcesClassLoader.java | WatchResourcesClassLoader | initWatchResources | class WatchResourcesClassLoader extends URLClassLoader {
private static AgentLogger LOGGER = AgentLogger.getLogger(WatchResourcesClassLoader.class);
/**
* URLs of changed resources. Use this set to check if the resource was changed and hence should
* be returned by this classloader.
*/
Set<URL> changedUrls = new HashSet<>();
/**
* Watch for requested resource in parent classloader in case it is not found by this classloader?
* Note that there is child first precedence anyway.
*/
boolean searchParent = true;
public void setSearchParent(boolean searchParent) {
this.searchParent = searchParent;
}
/**
* URL classloader configured to get resources only from exact set of URL's (no parent delegation)
*/
ClassLoader watchResourcesClassLoader;
public WatchResourcesClassLoader() {
this(false);
}
public WatchResourcesClassLoader(boolean searchParent) {
super(new URL[]{}, searchParent ? WatchResourcesClassLoader.class.getClassLoader() : null);
this.searchParent = searchParent;
}
public WatchResourcesClassLoader(ClassLoader classLoader) {
super(new URL[] {}, classLoader);
this.searchParent = false;
}
/**
* Configure new instance with urls and watcher service.
*
* @param extraPath the URLs from which to load resources
*/
public void initExtraPath(URL[] extraPath) {
for (URL url : extraPath)
addURL(url);
}
/**
* Configure new instance with urls and watcher service.
*
* @param watchResources the URLs from which to load resources
* @param watcher watcher service to register watch events
*/
public void initWatchResources(URL[] watchResources, Watcher watcher) {<FILL_FUNCTION_BODY>}
/**
* Check if the resource was changed after this classloader instantiaton.
*
* @param url full URL of the file
* @return true if was changed after instantiation
*/
public boolean isResourceChanged(URL url) {
return changedUrls.contains(url);
}
/**
* Returns URL only if the resource is found in changedURL and was actually changed after
* instantiation of this classloader.
*/
@Override
public URL getResource(String name) {
if (watchResourcesClassLoader != null) {
URL resource = watchResourcesClassLoader.getResource(name);
if (resource != null && isResourceChanged(resource)) {
LOGGER.trace("watchResources - using changed resource {}", name);
return resource;
}
}
// child first (extra classpath)
URL resource = findResource(name);
if (resource != null)
return resource;
// without parent do not call super (ignore even bootstrapResources)
if (searchParent)
return super.getResource(name);
else
return null;
}
@Override
public InputStream getResourceAsStream(String name) {
URL url = getResource(name);
try {
return url != null ? url.openStream() : null;
} catch (IOException e) {
}
return null;
}
/**
* Returns only a single instance of the changed resource.
* There are conflicting requirements for other resources inclusion. This class
* should "hide" the original resource, hence it should not be included in the resoult.
* On the other hand, there may be resource with the same name in other JAR which
* should be included and now is hidden (for example multiple persistence.xml).
* Maybe a new property to influence this behaviour?
*/
@Override
public Enumeration<URL> getResources(String name) throws IOException {
if (watchResourcesClassLoader != null) {
URL resource = watchResourcesClassLoader.getResource(name);
if (resource != null && isResourceChanged(resource)) {
LOGGER.trace("watchResources - using changed resource {}", name);
Vector<URL> res = new Vector<>();
res.add(resource);
return res.elements();
}
}
// if extraClasspath contains at least one element, return only extraClasspath
if (findResources(name).hasMoreElements())
return findResources(name);
return super.getResources(name);
}
/**
* Support for classpath builder on Tomcat.
*/
public String getClasspath() {
ClassLoader parent = getParent();
if (parent == null)
return null;
try {
Method m = parent.getClass().getMethod("getClasspath", new Class[] {});
if( m==null ) return null;
Object o = m.invoke( parent, new Object[] {} );
if( o instanceof String )
return (String)o;
return null;
} catch( Exception ex ) {
LOGGER.debug("getClasspath not supported on parent classloader.");
}
return null;
}
/**
* Helper classloader to get resources from list of urls only.
*/
public static class UrlOnlyClassLoader extends URLClassLoader {
public UrlOnlyClassLoader(URL[] urls) {
super(urls);
}
// do not use parent resource (may introduce infinite loop)
@Override
public URL getResource(String name) {
return findResource(name);
}
};
} |
// create classloader to serve resources only from watchResources URL's
this.watchResourcesClassLoader = new UrlOnlyClassLoader(watchResources);
// register watch resources - on change event each modified resource will be added to changedUrls.
for (URL resource : watchResources) {
try {
URI uri = resource.toURI();
LOGGER.debug("Watching directory '{}' for changes.", uri);
watcher.addEventListener(this, uri, new WatchEventListener() {
@Override
public void onEvent(WatchFileEvent event) {
try {
if (event.isFile() || event.isDirectory()) {
changedUrls.add(event.getURI().toURL());
LOGGER.trace("File '{}' changed and will be returned instead of original classloader equivalent.", event.getURI().toURL());
}
} catch (MalformedURLException e) {
LOGGER.error("Unexpected - cannot convert URI {} to URL.", e, event.getURI());
}
}
});
} catch (URISyntaxException e) {
LOGGER.warning("Unable to convert watchResources URL '{}' to URI. URL is skipped.", e, resource);
}
}
| 1,375 | 299 | 1,674 | <methods>public void <init>(java.net.URL[]) ,public void <init>(java.net.URL[], java.lang.ClassLoader) ,public void <init>(java.net.URL[], java.lang.ClassLoader, java.net.URLStreamHandlerFactory) ,public void <init>(java.lang.String, java.net.URL[], java.lang.ClassLoader) ,public void <init>(java.lang.String, java.net.URL[], java.lang.ClassLoader, java.net.URLStreamHandlerFactory) ,public void close() throws java.io.IOException,public java.net.URL findResource(java.lang.String) ,public Enumeration<java.net.URL> findResources(java.lang.String) throws java.io.IOException,public java.io.InputStream getResourceAsStream(java.lang.String) ,public java.net.URL[] getURLs() ,public static java.net.URLClassLoader newInstance(java.net.URL[]) ,public static java.net.URLClassLoader newInstance(java.net.URL[], java.lang.ClassLoader) <variables>private final java.security.AccessControlContext acc,private WeakHashMap<java.io.Closeable,java.lang.Void> closeables,private final jdk.internal.loader.URLClassPath ucp |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/scanner/ClassPathAnnotationScanner.java | ClassPathAnnotationScanner | scanPlugins | class ClassPathAnnotationScanner {
private static AgentLogger LOGGER = AgentLogger.getLogger(ClassPathAnnotationScanner.class);
// Annotation name to search for
String annotation;
// scanner to search path
Scanner scanner;
/**
* Create scanner for the annotation.
*/
public ClassPathAnnotationScanner(String annotation, Scanner scanner) {
this.annotation = annotation;
this.scanner = scanner;
}
/**
* Run the scan - search path for files containing annotation.
*
* @param classLoader classloader to resolve path
* @param path path to scan {@link org.hotswap.agent.util.scanner.Scanner#scan(ClassLoader, String, ScannerVisitor)}
* @return list of class names containing the annotation
* @throws IOException scan exception.
*/
public List<String> scanPlugins(ClassLoader classLoader, String path) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Check if the file contains annotation.
*/
protected boolean hasAnnotation(ClassFile cf) throws IOException {
AnnotationsAttribute visible = (AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.visibleTag);
if (visible != null) {
for (Annotation ann : visible.getAnnotations()) {
if (annotation.equals(ann.getTypeName())) {
return true;
}
}
}
return false;
}
} |
final List<String> files = new LinkedList<>();
scanner.scan(classLoader, path, new ScannerVisitor() {
@Override
public void visit(InputStream file) throws IOException {
ClassFile cf;
try {
DataInputStream dstream = new DataInputStream(file);
cf = new ClassFile(dstream);
} catch (IOException e) {
throw new IOException("Stream not a valid classFile", e);
}
if (hasAnnotation(cf))
files.add(cf.getName());
}
});
return files;
| 372 | 144 | 516 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/scanner/ClassPathScanner.java | ClassPathScanner | scanJar | class ClassPathScanner implements Scanner {
private static AgentLogger LOGGER = AgentLogger.getLogger(ClassPathScanner.class);
// scan for files inside JAR file - e.g. jar:file:\J:\HotswapAgent\target\HotswapAgent-1.0.jar!\org\hotswap\agent\plugin
public static final String JAR_URL_SEPARATOR = "!/";
public static final String JAR_URL_PREFIX = "jar:";
public static final String ZIP_URL_PREFIX = "zip:";
public static final String FILE_URL_PREFIX = "file:";
@Override
public void scan(ClassLoader classLoader, String path, ScannerVisitor visitor) throws IOException {
LOGGER.trace("Scanning path {}", path);
// find all directories - classpath directory or JAR
Enumeration<URL> en = classLoader == null ? ClassLoader.getSystemResources(path) : classLoader.getResources(path);
while (en.hasMoreElements()) {
URL pluginDirURL = en.nextElement();
File pluginDir = new File(pluginDirURL.getFile());
if (pluginDir.isDirectory()) {
scanDirectory(pluginDir, visitor);
} else {
// JAR file
String uri;
try {
uri = pluginDirURL.toURI().toString();
} catch (URISyntaxException e) {
throw new IOException("Illegal directory URI " + pluginDirURL, e);
}
if (uri.startsWith(JAR_URL_PREFIX) || uri.startsWith(ZIP_URL_PREFIX)) {
String jarFile = uri.substring(uri.indexOf(':') + 1); // remove the prefix
scanJar(jarFile, visitor);
} else {
LOGGER.warning("Unknown resource type of file " + uri);
}
}
}
}
/**
* Recursively scan the directory.
*
* @param pluginDir directory.
* @param visitor callback
* @throws IOException exception from a visitor
*/
protected void scanDirectory(File pluginDir, ScannerVisitor visitor) throws IOException {
LOGGER.trace("Scanning directory " + pluginDir.getName());
for (File file : pluginDir.listFiles()) {
if (file.isDirectory()) {
scanDirectory(file, visitor);
} else if (file.isFile() && file.getName().endsWith(".class")) {
visitor.visit(new FileInputStream(file));
}
}
}
/**
* Scan JAR file for all entries.
* Resolve the JAR file itself and than iterate all entries and call visitor.
*
* @param urlFile URL to the file containing scanned directory
* (e.g. jar:file:\J:\HotswapAgent\target\HotswapAgent-1.0.jar!\org\hotswap\agent\plugin)
* @param visitor callback
* @throws IOException exception from a visitor
*/
private void scanJar(String urlFile, ScannerVisitor visitor) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Resolve the given jar file URL into a JarFile object.
*/
protected JarFile getJarFile(String jarFileUrl) throws IOException {
LOGGER.trace("Opening JAR file " + jarFileUrl);
if (jarFileUrl.startsWith(FILE_URL_PREFIX)) {
try {
return new JarFile(toURI(jarFileUrl).getSchemeSpecificPart());
} catch (URISyntaxException ex) {
// Fallback for URLs that are not valid URIs (should hardly ever happen).
return new JarFile(jarFileUrl.substring(FILE_URL_PREFIX.length()));
}
} else {
return new JarFile(jarFileUrl);
}
}
/**
* Create a URI instance for the given location String,
* replacing spaces with "%20" quotes first.
*
* @param location the location String to convert into a URI instance
* @return the URI instance
* @throws URISyntaxException if the location wasn't a valid URI
*/
public static URI toURI(String location) throws URISyntaxException {
return new URI(location.replace(" ", "%20"));
}
} |
LOGGER.trace("Scanning JAR file '{}'", urlFile);
int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR);
JarFile jarFile = null;
String rootEntryPath;
try {
if (separatorIndex != -1) {
String jarFileUrl = urlFile.substring(0, separatorIndex);
rootEntryPath = urlFile.substring(separatorIndex + JAR_URL_SEPARATOR.length());
jarFile = getJarFile(jarFileUrl);
} else {
rootEntryPath = "";
jarFile = new JarFile(urlFile);
}
if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
rootEntryPath = rootEntryPath + "/";
}
for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements(); ) {
JarEntry entry = entries.nextElement();
String entryPath = entry.getName();
// class files inside entry
if (entryPath.startsWith(rootEntryPath) && entryPath.endsWith(".class")) {
LOGGER.trace("Visiting JAR entry {}", entryPath);
visitor.visit(jarFile.getInputStream(entry));
}
}
} finally {
if (jarFile != null) {
jarFile.close();
}
}
| 1,090 | 354 | 1,444 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/scanner/PluginCache.java | PluginCache | scanPlugins | class PluginCache {
public static final String PLUGIN_PATH = "org/hotswap/agent/plugin";
private Map<ClassLoader, Set<CtClass>> pluginDefs = new HashMap<>();
Scanner scanner = new ClassPathScanner();
public Set<CtClass> getPlugins(ClassLoader classLoader) {
if (pluginDefs.containsKey(classLoader))
return pluginDefs.get(classLoader);
else
return Collections.emptySet();
}
public Set<CtClass> scanPlugins(ClassLoader classLoader) throws IOException {<FILL_FUNCTION_BODY>}
} |
if (!pluginDefs.containsKey(classLoader)) {
synchronized (pluginDefs) {
if (!pluginDefs.containsKey(classLoader)) {
final Set<CtClass> plugins = new HashSet<>();
final ClassPool classPool = ClassPool.getDefault();
scanner.scan(getClass().getClassLoader(), PLUGIN_PATH, new ScannerVisitor() {
@Override
public void visit(InputStream file) throws IOException {
plugins.add(classPool.makeClass(file));
}
});
}
}
}
return pluginDefs.get(classLoader);
| 168 | 159 | 327 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/signature/ClassSignatureBase.java | ClassSignatureBase | annotationToString | class ClassSignatureBase {
private static final String[] IGNORED_METHODS = new String[] { "annotationType", "equals", "hashCode", "toString" };
private final Set<ClassSignatureElement> elements = new HashSet<>();
protected static final String SWITCH_TABLE_METHOD_PREFIX = "$SWITCH_TABLE$"; // java stores switch table to class field, signature should ingore it
/**
* Evaluate and return signature value
*
* @return the signature value
* @throws Exception
*/
public abstract String getValue() throws Exception;
/**
* Adds the signature elements to set of used signature elements
*
* @param elems
*/
public void addSignatureElements(ClassSignatureElement elems[]) {
for (ClassSignatureElement element : elems) {
elements.add(element);
}
}
/**
* Check if given signature element is set.
*
* @param element
* @return true, if has given element
*/
public boolean hasElement(ClassSignatureElement element) {
return elements.contains(element);
}
protected String annotationToString(Object[] a) {<FILL_FUNCTION_BODY>}
private Object arrayToString(Object value) {
Object result = value;
try {
try {
Method toStringMethod = Arrays.class.getMethod("toString", value.getClass());
// maybe because value is a subclass of Object[]
result = toStringMethod.invoke(null, value);
} catch (NoSuchMethodException e) {
if (value instanceof Object[]) {
Method toStringMethod = Arrays.class.getMethod("toString", Object[].class);
result = toStringMethod.invoke(null, value);
}
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e ) {
}
return result;
}
protected String annotationToString(Object[][] a) {
if (a == null)
return "null";
int iMax = a.length - 1;
if (iMax == -1)
return "[]";
a = sort(a);
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0;; i++) {
Object[] object = a[i];
b.append(annotationToString(object));
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
private <T> T[] sort(T[] a) {
a = Arrays.copyOf(a, a.length);
Arrays.sort(a, ToStringComparator.INSTANCE);
return a;
}
private <T> T[][] sort(T[][] a) {
a = Arrays.copyOf(a, a.length);
Arrays.sort(a, ToStringComparator.INSTANCE);
for (Object[] objects : a) {
Arrays.sort(objects, ToStringComparator.INSTANCE);
}
return a;
}
private Object getAnnotationValue(Annotation annotation, String attributeName) {
Method method = null;
boolean acessibleSet = false;
try {
method = annotation.annotationType().getDeclaredMethod(attributeName);
acessibleSet = makeAccessible(method);
return method.invoke(annotation);
} catch (Exception ex) {
return null;
} finally {
if (method != null && acessibleSet) {
method.setAccessible(false);
}
}
}
private boolean makeAccessible(Method method) {
if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
&& !method.isAccessible()) {
method.setAccessible(true);
return true;
}
return false;
}
protected static class ToStringComparator implements Comparator<Object> {
public static final ToStringComparator INSTANCE = new ToStringComparator();
@Override
public int compare(Object o1, Object o2) {
return o1.toString().compareTo(o2.toString());
}
}
} |
if (a == null)
return "null";
int iMax = a.length - 1;
if (iMax == -1)
return "[]";
a = sort(a);
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0;i < a.length; i++) {
Annotation object = (Annotation) a[i];
Method[] declaredMethods = object.getClass().getDeclaredMethods();
b.append("(");
boolean printComma = false;
for (Method method : declaredMethods) {
if (Arrays.binarySearch(IGNORED_METHODS, method.getName()) < 0) {
Object value = getAnnotationValue(object, method.getName());
if (value != null) {
if (printComma) {
b.append(",");
} else {
printComma = true;
}
if (value.getClass().isArray()) {
value = arrayToString(value);
}
b.append(method.getName() + "=" + value.getClass() + ":" + value);
}
}
}
b.append(")");
// TODO : sometimes for CtFile object.annotationType() is not known an it fails here
// v.d. : uncommented in v1.1 alpha with javassist update (3.21) to check if there is still problem
b.append(object.annotationType().getName());
if (i<a.length-1) {
b.append(",");
}
}
b.append(']');
return b.toString();
| 1,082 | 414 | 1,496 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/signature/ClassSignatureComparerHelper.java | ClassSignatureComparerHelper | isDifferent | class ClassSignatureComparerHelper {
private static AgentLogger LOGGER = AgentLogger.getLogger(ClassSignatureComparerHelper.class);
public static String getCtClassSignature(CtClass ctClass, ClassSignatureElement[] signatureElements) throws Exception {
CtClassSignature signature = new CtClassSignature(ctClass);
signature.addSignatureElements(signatureElements);
return signature.getValue();
}
public static String getJavaClassSignature(Class<?> clazz, ClassSignatureElement[] signatureElements) throws Exception {
JavaClassSignature signature = new JavaClassSignature(clazz);
signature.addSignatureElements(signatureElements);
return signature.getValue();
}
/**
* @param ctClass new CtClass definition
* @param clazz old Class definition
* @return is signature different
*/
public static boolean isDifferent(CtClass ctClass, Class<?> clazz, ClassSignatureElement[] signatureElements) {
try {
String sig1 = getCtClassSignature(ctClass, signatureElements);
String sig2 = getJavaClassSignature(clazz, signatureElements);
return !sig1.equals(sig2);
} catch (Exception e) {
LOGGER.error("Error reading signature", e);
return false;
}
}
public static boolean isDifferent(Class<?> clazz1, Class<?> clazz2, ClassSignatureElement[] signatureElements) {<FILL_FUNCTION_BODY>}
/**
* @param clazz old Class definition
* @param cp ClassPool which should contain the new/compared definition
* @return is signature different
*/
public static boolean isPoolClassDifferent(Class<?> clazz, ClassPool cp, ClassSignatureElement[] signatureElements) {
try {
return isDifferent(cp.get(clazz.getName()), clazz, signatureElements);
} catch (NotFoundException e) {
LOGGER.error("Class not found ", e);
return false;
}
}
} |
try {
String sig1 = getJavaClassSignature(clazz1, signatureElements);
String sig2 = getJavaClassSignature(clazz2, signatureElements);
return !sig1.equals(sig2);
} catch (Exception e) {
LOGGER.error("Error reading signature", e);
return false;
}
| 498 | 85 | 583 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/signature/CtClassSignature.java | CtClassSignature | getValue | class CtClassSignature extends ClassSignatureBase {
private CtClass ctClass;
/**
* @param ctClass the class for signature is to be counted
*/
public CtClassSignature(CtClass ctClass) {
this.ctClass = ctClass;
}
@Override
public String getValue() throws Exception {<FILL_FUNCTION_BODY>}
private String getName(CtClass ctClass) {
return ctClass.getName();
}
private String getConstructorString(CtConstructor method) throws ClassNotFoundException, NotFoundException {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(Modifier.toString(method.getModifiers()) + " ");
strBuilder.append(method.getDeclaringClass().getName());
strBuilder.append(getParams(method.getParameterTypes()));
if (hasElement(ClassSignatureElement.METHOD_ANNOTATION))
strBuilder.append(annotationToString(method.getAvailableAnnotations()));
if (hasElement(ClassSignatureElement.METHOD_PARAM_ANNOTATION))
strBuilder.append(annotationToString(method.getAvailableParameterAnnotations()));
if (hasElement(ClassSignatureElement.METHOD_EXCEPTION))
strBuilder.append(toStringException(method.getExceptionTypes()));
strBuilder.append(";");
return strBuilder.toString();
}
private String getMethodString(CtMethod method) throws NotFoundException, ClassNotFoundException {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(Modifier.toString(method.getModifiers()) + " ");
strBuilder.append(getName(method.getReturnType()) + " " + method.getName());
strBuilder.append(getParams(method.getParameterTypes()));
if (hasElement(ClassSignatureElement.METHOD_ANNOTATION))
strBuilder.append(annotationToString(method.getAvailableAnnotations()));
if (hasElement(ClassSignatureElement.METHOD_PARAM_ANNOTATION))
strBuilder.append(annotationToString(method.getAvailableParameterAnnotations()));
if (hasElement(ClassSignatureElement.METHOD_EXCEPTION))
strBuilder.append(toStringException(method.getExceptionTypes()));
strBuilder.append(";");
return strBuilder.toString();
}
private String getParams(CtClass[] ctClasses) {
StringBuilder strBuilder = new StringBuilder("(");
boolean first = true;
for (CtClass ctClass : ctClasses) {
if (!first)
strBuilder.append(",");
else
first = false;
strBuilder.append(getName(ctClass));
}
strBuilder.append(")");
return strBuilder.toString();
}
private String toStringException(CtClass[] a) {
if (a == null)
return "null";
int iMax = a.length - 1;
if (iMax == -1)
return "[]";
a = sort(a);
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0;; i++) {
b.append("class " + a[i].getName());
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
private CtClass[] sort(CtClass[] a) {
a = Arrays.copyOf(a, a.length);
Arrays.sort(a, CtClassComparator.INSTANCE);
return a;
}
private static class CtClassComparator implements Comparator<CtClass> {
public static final CtClassComparator INSTANCE = new CtClassComparator();
@Override
public int compare(CtClass o1, CtClass o2) {
return o1.getName().compareTo(o2.getName());
}
}
} |
List<String> strings = new ArrayList<>();
if (hasElement(ClassSignatureElement.METHOD)) {
boolean usePrivateMethod = hasElement(ClassSignatureElement.METHOD_PRIVATE);
boolean useStaticMethod = hasElement(ClassSignatureElement.METHOD_STATIC);
for (CtMethod method : ctClass.getDeclaredMethods()) {
if (!usePrivateMethod && Modifier.isPrivate(method.getModifiers()))
continue;
if (!useStaticMethod && Modifier.isStatic(method.getModifiers()))
continue;
if (method.getName().startsWith(SWITCH_TABLE_METHOD_PREFIX))
continue;
strings.add(getMethodString(method));
}
}
if (hasElement(ClassSignatureElement.CONSTRUCTOR)) {
boolean usePrivateConstructor = hasElement(ClassSignatureElement.CONSTRUCTOR_PRIVATE);
for (CtConstructor method : ctClass.getDeclaredConstructors()) {
if (!usePrivateConstructor && Modifier.isPrivate(method.getModifiers()))
continue;
strings.add(getConstructorString(method));
}
}
if (hasElement(ClassSignatureElement.CLASS_ANNOTATION)) {
strings.add(annotationToString(ctClass.getAvailableAnnotations()));
}
if (hasElement(ClassSignatureElement.INTERFACES)) {
for (CtClass iClass : ctClass.getInterfaces()) {
strings.add(iClass.getName());
}
}
if (hasElement(ClassSignatureElement.SUPER_CLASS)) {
String superclassName = ctClass.getSuperclassName();
if (superclassName != null && !superclassName.equals(Object.class.getName()))
strings.add(superclassName);
}
if (hasElement(ClassSignatureElement.FIELD)) {
boolean useStaticField = hasElement(ClassSignatureElement.FIELD_STATIC);
boolean useFieldAnnotation = hasElement(ClassSignatureElement.FIELD_ANNOTATION);
for (CtField field : ctClass.getDeclaredFields()) {
if (!useStaticField && Modifier.isStatic(field.getModifiers()))
continue;
if (field.getName().startsWith(SWITCH_TABLE_METHOD_PREFIX))
continue;
String fieldSignature = field.getType().getName() + " " + field.getName();
if (useFieldAnnotation) {
fieldSignature += annotationToString(field.getAvailableAnnotations());
}
strings.add(fieldSignature + ";");
}
}
Collections.sort(strings);
StringBuilder strBuilder = new StringBuilder();
for (String methodString : strings) {
strBuilder.append(methodString);
}
return strBuilder.toString();
| 974 | 688 | 1,662 | <methods>public non-sealed void <init>() ,public void addSignatureElements(org.hotswap.agent.util.signature.ClassSignatureElement[]) ,public abstract java.lang.String getValue() throws java.lang.Exception,public boolean hasElement(org.hotswap.agent.util.signature.ClassSignatureElement) <variables>private static final java.lang.String[] IGNORED_METHODS,protected static final java.lang.String SWITCH_TABLE_METHOD_PREFIX,private final Set<org.hotswap.agent.util.signature.ClassSignatureElement> elements |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/signature/JavaClassSignature.java | JavaClassSignature | getValue | class JavaClassSignature extends ClassSignatureBase {
private Class<?> clazz;
public JavaClassSignature(Class<?> clazz) {
this.clazz = clazz;
}
@Override
public String getValue() throws Exception {<FILL_FUNCTION_BODY>}
private String getConstructorString(Constructor<?> method) {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(Modifier.toString(method.getModifiers()) + " ");
strBuilder.append(method.getName());
strBuilder.append(getParams(method.getParameterTypes()));
if (hasElement(ClassSignatureElement.METHOD_ANNOTATION))
strBuilder.append(annotationToString(method.getDeclaredAnnotations()));
if (hasElement(ClassSignatureElement.METHOD_PARAM_ANNOTATION))
strBuilder.append(annotationToString(method.getParameterAnnotations()));
if (hasElement(ClassSignatureElement.METHOD_EXCEPTION))
strBuilder.append(Arrays.toString(sort(method.getExceptionTypes())));
strBuilder.append(";");
return strBuilder.toString();
}
private String getMethodString(Method method) {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(Modifier.toString(method.getModifiers()) + " ");
strBuilder.append(getName(method.getReturnType()) + " " + method.getName());
strBuilder.append(getParams(method.getParameterTypes()));
if (hasElement(ClassSignatureElement.METHOD_ANNOTATION))
strBuilder.append(annotationToString(method.getDeclaredAnnotations()));
if (hasElement(ClassSignatureElement.METHOD_PARAM_ANNOTATION))
strBuilder.append(annotationToString(method.getParameterAnnotations()));
if (hasElement(ClassSignatureElement.METHOD_EXCEPTION))
strBuilder.append(Arrays.toString(sort(method.getExceptionTypes())));
strBuilder.append(";");
return strBuilder.toString();
}
private <T> T[] sort(T[] a) {
a = Arrays.copyOf(a, a.length);
Arrays.sort(a, ToStringComparator.INSTANCE);
return a;
}
private String getParams(Class<?>[] parameterTypes) {
StringBuilder strB = new StringBuilder("(");
boolean first = true;
for (Class<?> ctClass : parameterTypes) {
if (!first)
strB.append(",");
else
first = false;
strB.append(getName(ctClass));
}
strB.append(")");
return strB.toString();
}
private String getName(Class<?> ctClass) {
if (ctClass.isArray())
return Descriptor.toString(ctClass.getName());
else
return ctClass.getName();
}
} |
List<String> strings = new ArrayList<>();
if (hasElement(ClassSignatureElement.METHOD)) {
boolean usePrivateMethod = hasElement(ClassSignatureElement.METHOD_PRIVATE);
boolean useStaticMethod = hasElement(ClassSignatureElement.METHOD_STATIC);
for (Method method : clazz.getDeclaredMethods()) {
if (!usePrivateMethod && Modifier.isPrivate(method.getModifiers()))
continue;
if (!useStaticMethod && Modifier.isStatic(method.getModifiers()))
continue;
if (method.getName().startsWith(SWITCH_TABLE_METHOD_PREFIX))
continue;
strings.add(getMethodString(method));
}
}
if (hasElement(ClassSignatureElement.CONSTRUCTOR)) {
boolean usePrivateConstructor = hasElement(ClassSignatureElement.CONSTRUCTOR_PRIVATE);
for (Constructor<?> method : clazz.getDeclaredConstructors()) {
if (!usePrivateConstructor && Modifier.isPrivate(method.getModifiers()))
continue;
strings.add(getConstructorString(method));
}
}
if (hasElement(ClassSignatureElement.CLASS_ANNOTATION)) {
strings.add(annotationToString(clazz.getAnnotations()));
}
if (hasElement(ClassSignatureElement.INTERFACES)) {
for (Class<?> iClass : clazz.getInterfaces()) {
strings.add(iClass.getName());
}
}
if (hasElement(ClassSignatureElement.SUPER_CLASS)) {
if (clazz.getSuperclass() != null && !clazz.getSuperclass().getName().equals(Object.class.getName()))
strings.add(clazz.getSuperclass().getName());
}
if (hasElement(ClassSignatureElement.FIELD)) {
boolean useStaticField = hasElement(ClassSignatureElement.FIELD_STATIC);
boolean useFieldAnnotation = hasElement(ClassSignatureElement.FIELD_ANNOTATION);
for (Field field : clazz.getDeclaredFields()) {
if (!useStaticField && Modifier.isStatic(field.getModifiers()))
continue;
if (field.getName().startsWith(SWITCH_TABLE_METHOD_PREFIX))
continue;
String fieldSignature = field.getType().getName() + " " + field.getName();
if (useFieldAnnotation) {
fieldSignature += annotationToString(field.getAnnotations());
}
strings.add(fieldSignature + ";");
}
}
Collections.sort(strings);
StringBuilder strBuilder = new StringBuilder();
for (String methodString : strings) {
strBuilder.append(methodString);
}
return strBuilder.toString();
| 723 | 685 | 1,408 | <methods>public non-sealed void <init>() ,public void addSignatureElements(org.hotswap.agent.util.signature.ClassSignatureElement[]) ,public abstract java.lang.String getValue() throws java.lang.Exception,public boolean hasElement(org.hotswap.agent.util.signature.ClassSignatureElement) <variables>private static final java.lang.String[] IGNORED_METHODS,protected static final java.lang.String SWITCH_TABLE_METHOD_PREFIX,private final Set<org.hotswap.agent.util.signature.ClassSignatureElement> elements |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/collections/LinkedMultiValueMap.java | LinkedMultiValueMap | deepCopy | class LinkedMultiValueMap<K, V> implements MultiValueMap<K, V>, Serializable {
private static final long serialVersionUID = 3801124242820219131L;
private final Map<K, List<V>> targetMap;
/**
* Create a new LinkedMultiValueMap that wraps a {@link LinkedHashMap}.
*/
public LinkedMultiValueMap() {
this.targetMap = new LinkedHashMap<K, List<V>>();
}
/**
* Create a new LinkedMultiValueMap that wraps a {@link LinkedHashMap} with
* the given initial capacity.
*
* @param initialCapacity
* the initial capacity
*/
public LinkedMultiValueMap(int initialCapacity) {
this.targetMap = new LinkedHashMap<K, List<V>>(initialCapacity);
}
/**
* Copy constructor: Create a new LinkedMultiValueMap with the same mappings
* as the specified Map. Note that this will be a shallow copy; its
* value-holding List entries will get reused and therefore cannot get
* modified independently.
*
* @param otherMap
* the Map whose mappings are to be placed in this Map
* @see #clone()
* @see #deepCopy()
*/
public LinkedMultiValueMap(Map<K, List<V>> otherMap) {
this.targetMap = new LinkedHashMap<K, List<V>>(otherMap);
}
// MultiValueMap implementation
@Override
public void add(K key, V value) {
List<V> values = this.targetMap.get(key);
if (values == null) {
values = new LinkedList<V>();
this.targetMap.put(key, values);
}
values.add(value);
}
@Override
public V getFirst(K key) {
List<V> values = this.targetMap.get(key);
return (values != null ? values.get(0) : null);
}
@Override
public void set(K key, V value) {
List<V> values = new LinkedList<V>();
values.add(value);
this.targetMap.put(key, values);
}
@Override
public void setAll(Map<K, V> values) {
for (Entry<K, V> entry : values.entrySet()) {
set(entry.getKey(), entry.getValue());
}
}
@Override
public Map<K, V> toSingleValueMap() {
LinkedHashMap<K, V> singleValueMap = new LinkedHashMap<K, V>(this.targetMap.size());
for (Entry<K, List<V>> entry : this.targetMap.entrySet()) {
singleValueMap.put(entry.getKey(), entry.getValue().get(0));
}
return singleValueMap;
}
// Map implementation
@Override
public int size() {
return this.targetMap.size();
}
@Override
public boolean isEmpty() {
return this.targetMap.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return this.targetMap.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return this.targetMap.containsValue(value);
}
@Override
public List<V> get(Object key) {
return this.targetMap.get(key);
}
@Override
public List<V> put(K key, List<V> value) {
return this.targetMap.put(key, value);
}
@Override
public List<V> remove(Object key) {
return this.targetMap.remove(key);
}
@Override
public void putAll(Map<? extends K, ? extends List<V>> map) {
this.targetMap.putAll(map);
}
@Override
public void clear() {
this.targetMap.clear();
}
@Override
public Set<K> keySet() {
return this.targetMap.keySet();
}
@Override
public Collection<List<V>> values() {
return this.targetMap.values();
}
@Override
public Set<Entry<K, List<V>>> entrySet() {
return this.targetMap.entrySet();
}
/**
* Create a regular copy of this Map.
*
* @return a shallow copy of this Map, reusing this Map's value-holding List
* entries
* @since 4.2
* @see LinkedMultiValueMap#LinkedMultiValueMap(Map)
* @see #deepCopy()
*/
@Override
public LinkedMultiValueMap<K, V> clone() {
return new LinkedMultiValueMap<K, V>(this);
}
/**
* Create a deep copy of this Map.
*
* @return a copy of this Map, including a copy of each value-holding List
* entry
* @since 4.2
* @see #clone()
*/
public LinkedMultiValueMap<K, V> deepCopy() {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object obj) {
return this.targetMap.equals(obj);
}
@Override
public int hashCode() {
return this.targetMap.hashCode();
}
@Override
public String toString() {
return this.targetMap.toString();
}
} |
LinkedMultiValueMap<K, V> copy = new LinkedMultiValueMap<K, V>(this.targetMap.size());
for (Map.Entry<K, List<V>> entry : this.targetMap.entrySet()) {
copy.put(entry.getKey(), new LinkedList<V>(entry.getValue()));
}
return copy;
| 1,440 | 89 | 1,529 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/loader/ClassRelativeResourceLoader.java | ClassRelativeContextResource | createRelative | class ClassRelativeContextResource extends ClassPathResource implements ContextResource {
private final Class<?> clazz;
public ClassRelativeContextResource(String path, Class<?> clazz) {
super(path, clazz);
this.clazz = clazz;
}
@Override
public String getPathWithinContext() {
return getPath();
}
@Override
public Resource createRelative(String relativePath) {<FILL_FUNCTION_BODY>}
} |
String pathToUse = StringUtils.applyRelativePath(getPath(), relativePath);
return new ClassRelativeContextResource(pathToUse, this.clazz);
| 128 | 43 | 171 | <methods>public void <init>() ,public void <init>(java.lang.ClassLoader) ,public java.lang.ClassLoader getClassLoader() ,public org.hotswap.agent.util.spring.io.resource.Resource getResource(java.lang.String) ,public void setClassLoader(java.lang.ClassLoader) <variables>private java.lang.ClassLoader classLoader |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/loader/DefaultResourceLoader.java | DefaultResourceLoader | getResource | class DefaultResourceLoader implements ResourceLoader {
private ClassLoader classLoader;
/**
* Create a new DefaultResourceLoader.
* <p>
* ClassLoader access will happen using the thread context class loader at
* the time of this ResourceLoader's initialization.
*
* @see java.lang.Thread#getContextClassLoader()
*/
public DefaultResourceLoader() {
this.classLoader = ClassUtils.getDefaultClassLoader();
}
/**
* Create a new DefaultResourceLoader.
*
* @param classLoader
* the ClassLoader to load class path resources with, or
* {@code null} for using the thread context class loader at the
* time of actual resource access
*/
public DefaultResourceLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
/**
* Specify the ClassLoader to load class path resources with, or
* {@code null} for using the thread context class loader at the time of
* actual resource access.
* <p>
* The default is that ClassLoader access will happen using the thread
* context class loader at the time of this ResourceLoader's initialization.
*/
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
/**
* Return the ClassLoader to load class path resources with.
* <p>
* Will get passed to ClassPathResource's constructor for all
* ClassPathResource objects created by this resource loader.
*
* @see ClassPathResource
*/
@Override
public ClassLoader getClassLoader() {
return (this.classLoader != null ? this.classLoader : ClassUtils.getDefaultClassLoader());
}
@Override
public Resource getResource(String location) {<FILL_FUNCTION_BODY>}
/**
* Return a Resource handle for the resource at the given path.
* <p>
* The default implementation supports class path locations. This should be
* appropriate for standalone implementations but can be overridden, e.g.
* for implementations targeted at a Servlet container.
*
* @param path
* the path to the resource
* @return the corresponding Resource handle
* @see ClassPathResource
* @see org.springframework.context.support.FileSystemXmlApplicationContext#getResourceByPath
* @see org.springframework.web.context.support.XmlWebApplicationContext#getResourceByPath
*/
protected Resource getResourceByPath(String path) {
return new ClassPathContextResource(path, getClassLoader());
}
/**
* ClassPathResource that explicitly expresses a context-relative path
* through implementing the ContextResource interface.
*/
protected static class ClassPathContextResource extends ClassPathResource implements ContextResource {
public ClassPathContextResource(String path, ClassLoader classLoader) {
super(path, classLoader);
}
@Override
public String getPathWithinContext() {
return getPath();
}
@Override
public Resource createRelative(String relativePath) {
String pathToUse = StringUtils.applyRelativePath(getPath(), relativePath);
return new ClassPathContextResource(pathToUse, getClassLoader());
}
}
} |
Assert.notNull(location, "Location must not be null");
if (location.startsWith("/")) {
return getResourceByPath(location);
} else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
} else {
try {
// Try to parse the location as a URL...
URL url = new URL(location);
return new UrlResource(url);
} catch (MalformedURLException ex) {
// No URL -> resolve as resource path.
return getResourceByPath(location);
}
}
| 818 | 170 | 988 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/loader/FileSystemResourceLoader.java | FileSystemResourceLoader | getResourceByPath | class FileSystemResourceLoader extends DefaultResourceLoader {
/**
* Resolve resource paths as file system paths.
* <p>
* Note: Even if a given path starts with a slash, it will get interpreted
* as relative to the current VM working directory.
*
* @param path
* the path to the resource
* @return the corresponding Resource handle
* @see FileSystemResource
* @see org.springframework.web.context.support.ServletContextResourceLoader#getResourceByPath
*/
@Override
protected Resource getResourceByPath(String path) {<FILL_FUNCTION_BODY>}
/**
* FileSystemResource that explicitly expresses a context-relative path
* through implementing the ContextResource interface.
*/
private static class FileSystemContextResource extends FileSystemResource implements ContextResource {
public FileSystemContextResource(String path) {
super(path);
}
@Override
public String getPathWithinContext() {
return getPath();
}
}
} |
if (path != null && path.startsWith("/")) {
path = path.substring(1);
}
return new FileSystemContextResource(path);
| 260 | 45 | 305 | <methods>public void <init>() ,public void <init>(java.lang.ClassLoader) ,public java.lang.ClassLoader getClassLoader() ,public org.hotswap.agent.util.spring.io.resource.Resource getResource(java.lang.String) ,public void setClassLoader(java.lang.ClassLoader) <variables>private java.lang.ClassLoader classLoader |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/resource/AbstractFileResolvingResource.java | AbstractFileResolvingResource | lastModified | class AbstractFileResolvingResource extends AbstractResource {
/**
* This implementation returns a File reference for the underlying class
* path resource, provided that it refers to a file in the file system.
*
* @see org.hotswap.agent.util.spring.util.springframework.util.ResourceUtils#getFile(java.net.URL,
* String)
*/
@Override
public File getFile() throws IOException {
URL url = getURL();
if (url.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
return VfsResourceDelegate.getResource(url).getFile();
}
return ResourceUtils.getFile(url, getDescription());
}
/**
* This implementation determines the underlying File (or jar file, in case
* of a resource in a jar/zip).
*/
@Override
protected File getFileForLastModifiedCheck() throws IOException {
URL url = getURL();
if (ResourceUtils.isJarURL(url)) {
URL actualUrl = ResourceUtils.extractJarFileURL(url);
if (actualUrl.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
return VfsResourceDelegate.getResource(actualUrl).getFile();
}
return ResourceUtils.getFile(actualUrl, "Jar URL");
} else {
return getFile();
}
}
/**
* This implementation returns a File reference for the underlying class
* path resource, provided that it refers to a file in the file system.
*
* @see org.hotswap.agent.util.spring.util.springframework.util.ResourceUtils#getFile(java.net.URI,
* String)
*/
protected File getFile(URI uri) throws IOException {
if (uri.getScheme().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
return VfsResourceDelegate.getResource(uri).getFile();
}
return ResourceUtils.getFile(uri, getDescription());
}
@Override
public boolean exists() {
try {
URL url = getURL();
if (ResourceUtils.isFileURL(url)) {
// Proceed with file system resolution...
return getFile().exists();
} else {
// Try a URL connection content-length header...
URLConnection con = url.openConnection();
customizeConnection(con);
HttpURLConnection httpCon = (con instanceof HttpURLConnection ? (HttpURLConnection) con : null);
if (httpCon != null) {
int code = httpCon.getResponseCode();
if (code == HttpURLConnection.HTTP_OK) {
return true;
} else if (code == HttpURLConnection.HTTP_NOT_FOUND) {
return false;
}
}
if (con.getContentLength() >= 0) {
return true;
}
if (httpCon != null) {
// no HTTP OK status, and no content-length header: give up
httpCon.disconnect();
return false;
} else {
// Fall back to stream existence: can we open the stream?
try (InputStream is = getInputStream()) {
return true;
}
}
}
} catch (IOException ex) {
return false;
}
}
@Override
public boolean isReadable() {
try {
URL url = getURL();
if (ResourceUtils.isFileURL(url)) {
// Proceed with file system resolution...
File file = getFile();
return (file.canRead() && !file.isDirectory());
} else {
return true;
}
} catch (IOException ex) {
return false;
}
}
@Override
public long contentLength() throws IOException {
URL url = getURL();
if (ResourceUtils.isFileURL(url)) {
// Proceed with file system resolution...
return getFile().length();
} else {
// Try a URL connection content-length header...
URLConnection con = url.openConnection();
customizeConnection(con);
return con.getContentLength();
}
}
@Override
public long lastModified() throws IOException {<FILL_FUNCTION_BODY>}
/**
* Customize the given {@link URLConnection}, obtained in the course of an
* {@link #exists()}, {@link #contentLength()} or {@link #lastModified()}
* call.
* <p>
* Calls {@link ResourceUtils#useCachesIfNecessary(URLConnection)} and
* delegates to {@link #customizeConnection(HttpURLConnection)} if possible.
* Can be overridden in subclasses.
*
* @param con
* the URLConnection to customize
* @throws IOException
* if thrown from URLConnection methods
*/
protected void customizeConnection(URLConnection con) throws IOException {
ResourceUtils.useCachesIfNecessary(con);
if (con instanceof HttpURLConnection) {
customizeConnection((HttpURLConnection) con);
}
}
/**
* Customize the given {@link HttpURLConnection}, obtained in the course of
* an {@link #exists()}, {@link #contentLength()} or {@link #lastModified()}
* call.
* <p>
* Sets request method "HEAD" by default. Can be overridden in subclasses.
*
* @param con
* the HttpURLConnection to customize
* @throws IOException
* if thrown from HttpURLConnection methods
*/
protected void customizeConnection(HttpURLConnection con) throws IOException {
con.setRequestMethod("HEAD");
}
/**
* Inner delegate class, avoiding a hard JBoss VFS API dependency at
* runtime.
*/
private static class VfsResourceDelegate {
public static Resource getResource(URL url) throws IOException {
return new VfsResource(VfsUtils.getRoot(url));
}
public static Resource getResource(URI uri) throws IOException {
return new VfsResource(VfsUtils.getRoot(uri));
}
}
} |
URL url = getURL();
if (ResourceUtils.isFileURL(url) || ResourceUtils.isJarURL(url)) {
// Proceed with file system resolution...
return super.lastModified();
} else {
// Try a URL connection last-modified header...
URLConnection con = url.openConnection();
customizeConnection(con);
return con.getLastModified();
}
| 1,544 | 104 | 1,648 | <methods>public non-sealed void <init>() ,public long contentLength() throws java.io.IOException,public org.hotswap.agent.util.spring.io.resource.Resource createRelative(java.lang.String) throws java.io.IOException,public boolean equals(java.lang.Object) ,public boolean exists() ,public java.io.File getFile() throws java.io.IOException,public java.lang.String getFilename() ,public java.net.URI getURI() throws java.io.IOException,public java.net.URL getURL() throws java.io.IOException,public int hashCode() ,public boolean isOpen() ,public boolean isReadable() ,public long lastModified() throws java.io.IOException,public java.lang.String toString() <variables> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/resource/AbstractResource.java | AbstractResource | exists | class AbstractResource implements Resource {
/**
* This implementation checks whether a File can be opened, falling back to
* whether an InputStream can be opened. This will cover both directories
* and content resources.
*/
@Override
public boolean exists() {<FILL_FUNCTION_BODY>}
/**
* This implementation always returns {@code true}.
*/
@Override
public boolean isReadable() {
return true;
}
/**
* This implementation always returns {@code false}.
*/
@Override
public boolean isOpen() {
return false;
}
/**
* This implementation throws a FileNotFoundException, assuming that the
* resource cannot be resolved to a URL.
*/
@Override
public URL getURL() throws IOException {
throw new FileNotFoundException(getDescription() + " cannot be resolved to URL");
}
/**
* This implementation builds a URI based on the URL returned by
* {@link #getURL()}.
*/
@Override
public URI getURI() throws IOException {
URL url = getURL();
try {
return ResourceUtils.toURI(url);
} catch (URISyntaxException ex) {
throw new NestedIOException("Invalid URI [" + url + "]", ex);
}
}
/**
* This implementation throws a FileNotFoundException, assuming that the
* resource cannot be resolved to an absolute file path.
*/
@Override
public File getFile() throws IOException {
throw new FileNotFoundException(getDescription() + " cannot be resolved to absolute file path");
}
/**
* This implementation reads the entire InputStream to calculate the content
* length. Subclasses will almost always be able to provide a more optimal
* version of this, e.g. checking a File length.
*
* @see #getInputStream()
* @throws IllegalStateException
* if {@link #getInputStream()} returns null.
*/
@Override
public long contentLength() throws IOException {
try (InputStream is = this.getInputStream()) {
Assert.state(is != null, "resource input stream must not be null");
long size = 0;
byte[] buf = new byte[255];
int read;
while ((read = is.read(buf)) != -1) {
size += read;
}
return size;
}
}
/**
* This implementation checks the timestamp of the underlying File, if
* available.
*
* @see #getFileForLastModifiedCheck()
*/
@Override
public long lastModified() throws IOException {
long lastModified = getFileForLastModifiedCheck().lastModified();
if (lastModified == 0L) {
throw new FileNotFoundException(getDescription() + " cannot be resolved in the file system for resolving its last-modified timestamp");
}
return lastModified;
}
/**
* Determine the File to use for timestamp checking.
* <p>
* The default implementation delegates to {@link #getFile()}.
*
* @return the File to use for timestamp checking (never {@code null})
* @throws IOException
* if the resource cannot be resolved as absolute file path,
* i.e. if the resource is not available in a file system
*/
protected File getFileForLastModifiedCheck() throws IOException {
return getFile();
}
/**
* This implementation throws a FileNotFoundException, assuming that
* relative resources cannot be created for this resource.
*/
@Override
public Resource createRelative(String relativePath) throws IOException {
throw new FileNotFoundException("Cannot create a relative resource for " + getDescription());
}
/**
* This implementation always returns {@code null}, assuming that this
* resource type does not have a filename.
*/
@Override
public String getFilename() {
return null;
}
/**
* This implementation returns the description of this resource.
*
* @see #getDescription()
*/
@Override
public String toString() {
return getDescription();
}
/**
* This implementation compares description strings.
*
* @see #getDescription()
*/
@Override
public boolean equals(Object obj) {
return (obj == this || (obj instanceof Resource && ((Resource) obj).getDescription().equals(getDescription())));
}
/**
* This implementation returns the description's hash code.
*
* @see #getDescription()
*/
@Override
public int hashCode() {
return getDescription().hashCode();
}
} |
// Try file existence: can we find the file in the file system?
try {
return getFile().exists();
} catch (IOException ex) {
// Fall back to stream existence: can we open the stream?
try (InputStream is = getInputStream()) {
return true;
} catch (Throwable isEx) {
return false;
}
}
| 1,171 | 94 | 1,265 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/resource/ClassPathResource.java | ClassPathResource | resolveURL | class ClassPathResource extends AbstractFileResolvingResource {
private final String path;
private ClassLoader classLoader;
private Class<?> clazz;
/**
* Create a new {@code ClassPathResource} for {@code ClassLoader} usage. A
* leading slash will be removed, as the ClassLoader resource access methods
* will not accept it.
* <p>
* The thread context class loader will be used for loading the resource.
*
* @param path
* the absolute path within the class path
* @see java.lang.ClassLoader#getResourceAsStream(String)
* @see org.springframework.util.ClassUtils#getDefaultClassLoader()
*/
public ClassPathResource(String path) {
this(path, (ClassLoader) null);
}
/**
* Create a new {@code ClassPathResource} for {@code ClassLoader} usage. A
* leading slash will be removed, as the ClassLoader resource access methods
* will not accept it.
*
* @param path
* the absolute path within the classpath
* @param classLoader
* the class loader to load the resource with, or {@code null}
* for the thread context class loader
* @see ClassLoader#getResourceAsStream(String)
*/
public ClassPathResource(String path, ClassLoader classLoader) {
Assert.notNull(path, "Path must not be null");
String pathToUse = StringUtils.cleanPath(path);
if (pathToUse.startsWith("/")) {
pathToUse = pathToUse.substring(1);
}
this.path = pathToUse;
this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
}
/**
* Create a new {@code ClassPathResource} for {@code Class} usage. The path
* can be relative to the given class, or absolute within the classpath via
* a leading slash.
*
* @param path
* relative or absolute path within the class path
* @param clazz
* the class to load resources with
* @see java.lang.Class#getResourceAsStream
*/
public ClassPathResource(String path, Class<?> clazz) {
Assert.notNull(path, "Path must not be null");
this.path = StringUtils.cleanPath(path);
this.clazz = clazz;
}
/**
* Create a new {@code ClassPathResource} with optional {@code ClassLoader}
* and {@code Class}. Only for internal usage.
*
* @param path
* relative or absolute path within the classpath
* @param classLoader
* the class loader to load the resource with, if any
* @param clazz
* the class to load resources with, if any
*/
protected ClassPathResource(String path, ClassLoader classLoader, Class<?> clazz) {
this.path = StringUtils.cleanPath(path);
this.classLoader = classLoader;
this.clazz = clazz;
}
/**
* Return the path for this resource (as resource path within the class
* path).
*/
public final String getPath() {
return this.path;
}
/**
* Return the ClassLoader that this resource will be obtained from.
*/
public final ClassLoader getClassLoader() {
return (this.clazz != null ? this.clazz.getClassLoader() : this.classLoader);
}
/**
* This implementation checks for the resolution of a resource URL.
*
* @see java.lang.ClassLoader#getResource(String)
* @see java.lang.Class#getResource(String)
*/
@Override
public boolean exists() {
return (resolveURL() != null);
}
/**
* Resolves a URL for the underlying class path resource.
*
* @return the resolved URL, or {@code null} if not resolvable
*/
protected URL resolveURL() {<FILL_FUNCTION_BODY>}
/**
* This implementation opens an InputStream for the given class path
* resource.
*
* @see java.lang.ClassLoader#getResourceAsStream(String)
* @see java.lang.Class#getResourceAsStream(String)
*/
@Override
public InputStream getInputStream() throws IOException {
InputStream is;
if (this.clazz != null) {
is = this.clazz.getResourceAsStream(this.path);
} else if (this.classLoader != null) {
is = this.classLoader.getResourceAsStream(this.path);
} else {
is = ClassLoader.getSystemResourceAsStream(this.path);
}
if (is == null) {
throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist");
}
return is;
}
/**
* This implementation returns a URL for the underlying class path resource,
* if available.
*
* @see java.lang.ClassLoader#getResource(String)
* @see java.lang.Class#getResource(String)
*/
@Override
public URL getURL() throws IOException {
URL url = resolveURL();
if (url == null) {
throw new FileNotFoundException(getDescription() + " cannot be resolved to URL because it does not exist");
}
return url;
}
/**
* This implementation creates a ClassPathResource, applying the given path
* relative to the path of the underlying resource of this descriptor.
*
* @see org.springframework.util.StringUtils#applyRelativePath(String,
* String)
*/
@Override
public Resource createRelative(String relativePath) {
String pathToUse = StringUtils.applyRelativePath(this.path, relativePath);
return new ClassPathResource(pathToUse, this.classLoader, this.clazz);
}
/**
* This implementation returns the name of the file that this class path
* resource refers to.
*
* @see org.springframework.util.StringUtils#getFilename(String)
*/
@Override
public String getFilename() {
return StringUtils.getFilename(this.path);
}
/**
* This implementation returns a description that includes the class path
* location.
*/
@Override
public String getDescription() {
StringBuilder builder = new StringBuilder("class path resource [");
String pathToUse = path;
if (this.clazz != null && !pathToUse.startsWith("/")) {
builder.append(ClassUtils.classPackageAsResourcePath(this.clazz));
builder.append('/');
}
if (pathToUse.startsWith("/")) {
pathToUse = pathToUse.substring(1);
}
builder.append(pathToUse);
builder.append(']');
return builder.toString();
}
/**
* This implementation compares the underlying class path locations.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof ClassPathResource) {
ClassPathResource otherRes = (ClassPathResource) obj;
return (this.path.equals(otherRes.path) && ObjectUtils.nullSafeEquals(this.classLoader, otherRes.classLoader) && ObjectUtils.nullSafeEquals(this.clazz, otherRes.clazz));
}
return false;
}
/**
* This implementation returns the hash code of the underlying class path
* location.
*/
@Override
public int hashCode() {
return this.path.hashCode();
}
} |
if (this.clazz != null) {
return this.clazz.getResource(this.path);
} else if (this.classLoader != null) {
return this.classLoader.getResource(this.path);
} else {
return ClassLoader.getSystemResource(this.path);
}
| 1,964 | 83 | 2,047 | <methods>public non-sealed void <init>() ,public long contentLength() throws java.io.IOException,public boolean exists() ,public java.io.File getFile() throws java.io.IOException,public boolean isReadable() ,public long lastModified() throws java.io.IOException<variables> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/resource/FileSystemResource.java | FileSystemResource | equals | class FileSystemResource extends AbstractResource implements WritableResource {
private final File file;
private final String path;
/**
* Create a new {@code FileSystemResource} from a {@link File} handle.
* <p>
* Note: When building relative resources via {@link #createRelative}, the
* relative path will apply <i>at the same directory level</i>: e.g. new
* File("C:/dir1"), relative path "dir2" -> "C:/dir2"! If you prefer to have
* relative paths built underneath the given root directory, use the
* {@link #FileSystemResource(String) constructor with a file path} to
* append a trailing slash to the root path: "C:/dir1/", which indicates
* this directory as root for all relative paths.
*
* @param file
* a File handle
*/
public FileSystemResource(File file) {
Assert.notNull(file, "File must not be null");
this.file = file;
this.path = StringUtils.cleanPath(file.getPath());
}
/**
* Create a new {@code FileSystemResource} from a file path.
* <p>
* Note: When building relative resources via {@link #createRelative}, it
* makes a difference whether the specified resource base path here ends
* with a slash or not. In the case of "C:/dir1/", relative paths will be
* built underneath that root: e.g. relative path "dir2" -> "C:/dir1/dir2".
* In the case of "C:/dir1", relative paths will apply at the same directory
* level: relative path "dir2" -> "C:/dir2".
*
* @param path
* a file path
*/
public FileSystemResource(String path) {
Assert.notNull(path, "Path must not be null");
this.file = new File(path);
this.path = StringUtils.cleanPath(path);
}
/**
* Return the file path for this resource.
*/
public final String getPath() {
return this.path;
}
/**
* This implementation returns whether the underlying file exists.
*
* @see java.io.File#exists()
*/
@Override
public boolean exists() {
return this.file.exists();
}
/**
* This implementation checks whether the underlying file is marked as
* readable (and corresponds to an actual file with content, not to a
* directory).
*
* @see java.io.File#canRead()
* @see java.io.File#isDirectory()
*/
@Override
public boolean isReadable() {
return (this.file.canRead() && !this.file.isDirectory());
}
/**
* This implementation opens a FileInputStream for the underlying file.
*
* @see java.io.FileInputStream
*/
@Override
public InputStream getInputStream() throws IOException {
return new FileInputStream(this.file);
}
/**
* This implementation returns a URL for the underlying file.
*
* @see java.io.File#toURI()
*/
@Override
public URL getURL() throws IOException {
return this.file.toURI().toURL();
}
/**
* This implementation returns a URI for the underlying file.
*
* @see java.io.File#toURI()
*/
@Override
public URI getURI() throws IOException {
return this.file.toURI();
}
/**
* This implementation returns the underlying File reference.
*/
@Override
public File getFile() {
return this.file;
}
/**
* This implementation returns the underlying File's length.
*/
@Override
public long contentLength() throws IOException {
return this.file.length();
}
/**
* This implementation creates a FileSystemResource, applying the given path
* relative to the path of the underlying file of this resource descriptor.
*
* @see org.hotswap.agent.util.spring.util.springframework.util.StringUtils#applyRelativePath(String,
* String)
*/
@Override
public Resource createRelative(String relativePath) {
String pathToUse = StringUtils.applyRelativePath(this.path, relativePath);
return new FileSystemResource(pathToUse);
}
/**
* This implementation returns the name of the file.
*
* @see java.io.File#getName()
*/
@Override
public String getFilename() {
return this.file.getName();
}
/**
* This implementation returns a description that includes the absolute path
* of the file.
*
* @see java.io.File#getAbsolutePath()
*/
@Override
public String getDescription() {
return "file [" + this.file.getAbsolutePath() + "]";
}
// implementation of WritableResource
/**
* This implementation checks whether the underlying file is marked as
* writable (and corresponds to an actual file with content, not to a
* directory).
*
* @see java.io.File#canWrite()
* @see java.io.File#isDirectory()
*/
@Override
public boolean isWritable() {
return (this.file.canWrite() && !this.file.isDirectory());
}
/**
* This implementation opens a FileOutputStream for the underlying file.
*
* @see java.io.FileOutputStream
*/
@Override
public OutputStream getOutputStream() throws IOException {
return new FileOutputStream(this.file);
}
/**
* This implementation compares the underlying File references.
*/
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
/**
* This implementation returns the hash code of the underlying File
* reference.
*/
@Override
public int hashCode() {
return this.path.hashCode();
}
} |
return (obj == this || (obj instanceof FileSystemResource && this.path.equals(((FileSystemResource) obj).path)));
| 1,559 | 33 | 1,592 | <methods>public non-sealed void <init>() ,public long contentLength() throws java.io.IOException,public org.hotswap.agent.util.spring.io.resource.Resource createRelative(java.lang.String) throws java.io.IOException,public boolean equals(java.lang.Object) ,public boolean exists() ,public java.io.File getFile() throws java.io.IOException,public java.lang.String getFilename() ,public java.net.URI getURI() throws java.io.IOException,public java.net.URL getURL() throws java.io.IOException,public int hashCode() ,public boolean isOpen() ,public boolean isReadable() ,public long lastModified() throws java.io.IOException,public java.lang.String toString() <variables> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/resource/InputStreamResource.java | InputStreamResource | getInputStream | class InputStreamResource extends AbstractResource {
private final InputStream inputStream;
private final String description;
private boolean read = false;
/**
* Create a new InputStreamResource.
*
* @param inputStream
* the InputStream to use
*/
public InputStreamResource(InputStream inputStream) {
this(inputStream, "resource loaded through InputStream");
}
/**
* Create a new InputStreamResource.
*
* @param inputStream
* the InputStream to use
* @param description
* where the InputStream comes from
*/
public InputStreamResource(InputStream inputStream, String description) {
if (inputStream == null) {
throw new IllegalArgumentException("InputStream must not be null");
}
this.inputStream = inputStream;
this.description = (description != null ? description : "");
}
/**
* This implementation always returns {@code true}.
*/
@Override
public boolean exists() {
return true;
}
/**
* This implementation always returns {@code true}.
*/
@Override
public boolean isOpen() {
return true;
}
/**
* This implementation throws IllegalStateException if attempting to read
* the underlying stream multiple times.
*/
@Override
public InputStream getInputStream() throws IOException, IllegalStateException {<FILL_FUNCTION_BODY>}
/**
* This implementation returns a description that includes the passed-in
* description, if any.
*/
@Override
public String getDescription() {
return "InputStream resource [" + this.description + "]";
}
/**
* This implementation compares the underlying InputStream.
*/
@Override
public boolean equals(Object obj) {
return (obj == this || (obj instanceof InputStreamResource && ((InputStreamResource) obj).inputStream.equals(this.inputStream)));
}
/**
* This implementation returns the hash code of the underlying InputStream.
*/
@Override
public int hashCode() {
return this.inputStream.hashCode();
}
} |
if (this.read) {
throw new IllegalStateException("InputStream has already been read - " + "do not use InputStreamResource if a stream needs to be read multiple times");
}
this.read = true;
return this.inputStream;
| 537 | 64 | 601 | <methods>public non-sealed void <init>() ,public long contentLength() throws java.io.IOException,public org.hotswap.agent.util.spring.io.resource.Resource createRelative(java.lang.String) throws java.io.IOException,public boolean equals(java.lang.Object) ,public boolean exists() ,public java.io.File getFile() throws java.io.IOException,public java.lang.String getFilename() ,public java.net.URI getURI() throws java.io.IOException,public java.net.URL getURL() throws java.io.IOException,public int hashCode() ,public boolean isOpen() ,public boolean isReadable() ,public long lastModified() throws java.io.IOException,public java.lang.String toString() <variables> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/resource/NestedExceptionUtils.java | NestedExceptionUtils | buildMessage | class NestedExceptionUtils {
/**
* Build a message for the given base message and root cause.
*
* @param message
* the base message
* @param cause
* the root cause
* @return the full exception message
*/
public static String buildMessage(String message, Throwable cause) {<FILL_FUNCTION_BODY>}
} |
if (cause != null) {
StringBuilder sb = new StringBuilder();
if (message != null) {
sb.append(message).append("; ");
}
sb.append("nested exception is ").append(cause);
return sb.toString();
} else {
return message;
}
| 100 | 84 | 184 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/resource/PathResource.java | PathResource | getInputStream | class PathResource extends AbstractResource implements WritableResource {
private final Path path;
/**
* Create a new PathResource from a Path handle.
* <p>
* Note: Unlike {@link FileSystemResource}, when building relative resources
* via {@link #createRelative}, the relative path will be built
* <i>underneath</i> the given root: e.g. Paths.get("C:/dir1/"), relative
* path "dir2" -> "C:/dir1/dir2"!
*
* @param path
* a Path handle
*/
public PathResource(Path path) {
Assert.notNull(path, "Path must not be null");
this.path = path.normalize();
}
/**
* Create a new PathResource from a Path handle.
* <p>
* Note: Unlike {@link FileSystemResource}, when building relative resources
* via {@link #createRelative}, the relative path will be built
* <i>underneath</i> the given root: e.g. Paths.get("C:/dir1/"), relative
* path "dir2" -> "C:/dir1/dir2"!
*
* @param path
* a path
* @see java.nio.file.Paths#get(String, String...)
*/
public PathResource(String path) {
Assert.notNull(path, "Path must not be null");
this.path = Paths.get(path).normalize();
}
/**
* Create a new PathResource from a Path handle.
* <p>
* Note: Unlike {@link FileSystemResource}, when building relative resources
* via {@link #createRelative}, the relative path will be built
* <i>underneath</i> the given root: e.g. Paths.get("C:/dir1/"), relative
* path "dir2" -> "C:/dir1/dir2"!
*
* @see java.nio.file.Paths#get(URI)
* @param uri
* a path URI
*/
public PathResource(URI uri) {
Assert.notNull(uri, "URI must not be null");
this.path = Paths.get(uri).normalize();
}
/**
* Return the file path for this resource.
*/
public final String getPath() {
return this.path.toString();
}
/**
* This implementation returns whether the underlying file exists.
*
* @see org.hotswap.agent.util.spring.io.resource.springframework.core.io.PathResource#exists()
*/
@Override
public boolean exists() {
return Files.exists(this.path);
}
/**
* This implementation checks whether the underlying file is marked as
* readable (and corresponds to an actual file with content, not to a
* directory).
*
* @see java.nio.file.Files#isReadable(Path)
* @see java.nio.file.Files#isDirectory(Path, java.nio.file.LinkOption...)
*/
@Override
public boolean isReadable() {
return (Files.isReadable(this.path) && !Files.isDirectory(this.path));
}
/**
* This implementation opens a InputStream for the underlying file.
*
* @see java.nio.file.spi.FileSystemProvider#newInputStream(Path,
* OpenOption...)
*/
@Override
public InputStream getInputStream() throws IOException {<FILL_FUNCTION_BODY>}
/**
* This implementation returns a URL for the underlying file.
*
* @see java.nio.file.Path#toUri()
* @see java.net.URI#toURL()
*/
@Override
public URL getURL() throws IOException {
return this.path.toUri().toURL();
}
/**
* This implementation returns a URI for the underlying file.
*
* @see java.nio.file.Path#toUri()
*/
@Override
public URI getURI() throws IOException {
return this.path.toUri();
}
/**
* This implementation returns the underlying File reference.
*/
@Override
public File getFile() throws IOException {
try {
return this.path.toFile();
} catch (UnsupportedOperationException ex) {
// only Paths on the default file system can be converted to a File
// do exception translation for cases where conversion is not
// possible
throw new FileNotFoundException(this.path + " cannot be resolved to " + "absolute file path");
}
}
/**
* This implementation returns the underlying File's length.
*/
@Override
public long contentLength() throws IOException {
return Files.size(this.path);
}
/**
* This implementation returns the underlying File's timestamp.
*
* @see java.nio.file.Files#getLastModifiedTime(Path,
* java.nio.file.LinkOption...)
*/
@Override
public long lastModified() throws IOException {
// we can not use the super class method since it uses conversion to a
// File and
// only Paths on the default file system can be converted to a File
return Files.getLastModifiedTime(path).toMillis();
}
/**
* This implementation creates a FileResource, applying the given path
* relative to the path of the underlying file of this resource descriptor.
*
* @see java.nio.file.Path#resolve(String)
*/
@Override
public Resource createRelative(String relativePath) throws IOException {
return new PathResource(this.path.resolve(relativePath));
}
/**
* This implementation returns the name of the file.
*
* @see java.nio.file.Path#getFileName()
*/
@Override
public String getFilename() {
return this.path.getFileName().toString();
}
@Override
public String getDescription() {
return "path [" + this.path.toAbsolutePath() + "]";
}
// implementation of WritableResource
/**
* This implementation checks whether the underlying file is marked as
* writable (and corresponds to an actual file with content, not to a
* directory).
*
* @see java.nio.file.Files#isWritable(Path)
* @see java.nio.file.Files#isDirectory(Path, java.nio.file.LinkOption...)
*/
@Override
public boolean isWritable() {
return Files.isWritable(this.path) && !Files.isDirectory(this.path);
}
/**
* This implementation opens a OutputStream for the underlying file.
*
* @see java.nio.file.spi.FileSystemProvider#newOutputStream(Path,
* OpenOption...)
*/
@Override
public OutputStream getOutputStream() throws IOException {
if (Files.isDirectory(this.path)) {
throw new FileNotFoundException(getPath() + " (is a directory)");
}
return Files.newOutputStream(this.path);
}
/**
* This implementation compares the underlying Path references.
*/
@Override
public boolean equals(Object obj) {
return (this == obj || (obj instanceof PathResource && this.path.equals(((PathResource) obj).path)));
}
/**
* This implementation returns the hash code of the underlying Path
* reference.
*/
@Override
public int hashCode() {
return this.path.hashCode();
}
} |
if (!exists()) {
throw new FileNotFoundException(getPath() + " (no such file or directory)");
}
if (Files.isDirectory(this.path)) {
throw new FileNotFoundException(getPath() + " (is a directory)");
}
return Files.newInputStream(this.path);
| 1,960 | 82 | 2,042 | <methods>public non-sealed void <init>() ,public long contentLength() throws java.io.IOException,public org.hotswap.agent.util.spring.io.resource.Resource createRelative(java.lang.String) throws java.io.IOException,public boolean equals(java.lang.Object) ,public boolean exists() ,public java.io.File getFile() throws java.io.IOException,public java.lang.String getFilename() ,public java.net.URI getURI() throws java.io.IOException,public java.net.URL getURL() throws java.io.IOException,public int hashCode() ,public boolean isOpen() ,public boolean isReadable() ,public long lastModified() throws java.io.IOException,public java.lang.String toString() <variables> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/resource/VfsResource.java | VfsResource | getURL | class VfsResource extends AbstractResource {
private final Object resource;
public VfsResource(Object resource) {
Assert.notNull(resource, "VirtualFile must not be null");
this.resource = resource;
}
@Override
public InputStream getInputStream() throws IOException {
return VfsUtils.getInputStream(this.resource);
}
@Override
public boolean exists() {
return VfsUtils.exists(this.resource);
}
@Override
public boolean isReadable() {
return VfsUtils.isReadable(this.resource);
}
@Override
public URL getURL() throws IOException {<FILL_FUNCTION_BODY>}
@Override
public URI getURI() throws IOException {
try {
return VfsUtils.getURI(this.resource);
} catch (Exception ex) {
throw new NestedIOException("Failed to obtain URI for " + this.resource, ex);
}
}
@Override
public File getFile() throws IOException {
return VfsUtils.getFile(this.resource);
}
@Override
public long contentLength() throws IOException {
return VfsUtils.getSize(this.resource);
}
@Override
public long lastModified() throws IOException {
return VfsUtils.getLastModified(this.resource);
}
@Override
public Resource createRelative(String relativePath) throws IOException {
if (!relativePath.startsWith(".") && relativePath.contains("/")) {
try {
return new VfsResource(VfsUtils.getChild(this.resource, relativePath));
} catch (IOException ex) {
// fall back to getRelative
}
}
return new VfsResource(VfsUtils.getRelative(new URL(getURL(), relativePath)));
}
@Override
public String getFilename() {
return VfsUtils.getName(this.resource);
}
@Override
public String getDescription() {
return "VFS resource [" + this.resource + "]";
}
@Override
public boolean equals(Object obj) {
return (obj == this || (obj instanceof VfsResource && this.resource.equals(((VfsResource) obj).resource)));
}
@Override
public int hashCode() {
return this.resource.hashCode();
}
} |
try {
return VfsUtils.getURL(this.resource);
} catch (Exception ex) {
throw new NestedIOException("Failed to obtain URL for file " + this.resource, ex);
}
| 603 | 55 | 658 | <methods>public non-sealed void <init>() ,public long contentLength() throws java.io.IOException,public org.hotswap.agent.util.spring.io.resource.Resource createRelative(java.lang.String) throws java.io.IOException,public boolean equals(java.lang.Object) ,public boolean exists() ,public java.io.File getFile() throws java.io.IOException,public java.lang.String getFilename() ,public java.net.URI getURI() throws java.io.IOException,public java.net.URL getURL() throws java.io.IOException,public int hashCode() ,public boolean isOpen() ,public boolean isReadable() ,public long lastModified() throws java.io.IOException,public java.lang.String toString() <variables> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/path/VfsPatternUtils.java | VfsPatternUtils | visit | class VfsPatternUtils extends VfsUtils {
static Object getVisitorAttribute() {
return doGetVisitorAttribute();
}
static String getPath(Object resource) {
return doGetPath(resource);
}
static Object findRoot(URL url) throws IOException {
return getRoot(url);
}
static void visit(Object resource, InvocationHandler visitor) throws IOException {<FILL_FUNCTION_BODY>}
} |
Object visitorProxy = Proxy.newProxyInstance(VIRTUAL_FILE_VISITOR_INTERFACE.getClassLoader(), new Class<?>[] { VIRTUAL_FILE_VISITOR_INTERFACE }, visitor);
invokeVfsMethod(VIRTUAL_FILE_METHOD_VISIT, resource, visitorProxy);
| 116 | 89 | 205 | <methods>public non-sealed void <init>() ,public static boolean exists(java.lang.Object) ,public static T getChild(java.lang.Object, java.lang.String) throws java.io.IOException,public static java.io.File getFile(java.lang.Object) throws java.io.IOException,public static java.io.InputStream getInputStream(java.lang.Object) throws java.io.IOException,public static long getLastModified(java.lang.Object) throws java.io.IOException,public static java.lang.String getName(java.lang.Object) ,public static T getRelative(java.net.URL) throws java.io.IOException,public static T getRoot(java.net.URI) throws java.io.IOException,public static T getRoot(java.net.URL) throws java.io.IOException,public static long getSize(java.lang.Object) throws java.io.IOException,public static java.net.URI getURI(java.lang.Object) throws java.io.IOException,public static java.net.URL getURL(java.lang.Object) throws java.io.IOException,public static boolean isReadable(java.lang.Object) <variables>private static java.lang.reflect.Method GET_PHYSICAL_FILE,private static final org.hotswap.agent.logging.AgentLogger LOGGER,private static final java.lang.String VFS3_PKG,private static java.lang.reflect.Method VFS_METHOD_GET_ROOT_URI,private static java.lang.reflect.Method VFS_METHOD_GET_ROOT_URL,private static final java.lang.String VFS_NAME,private static java.lang.reflect.Method VIRTUAL_FILE_METHOD_EXISTS,private static java.lang.reflect.Method VIRTUAL_FILE_METHOD_GET_CHILD,private static java.lang.reflect.Method VIRTUAL_FILE_METHOD_GET_INPUT_STREAM,private static java.lang.reflect.Method VIRTUAL_FILE_METHOD_GET_LAST_MODIFIED,private static java.lang.reflect.Method VIRTUAL_FILE_METHOD_GET_NAME,private static java.lang.reflect.Method VIRTUAL_FILE_METHOD_GET_PATH_NAME,private static java.lang.reflect.Method VIRTUAL_FILE_METHOD_GET_SIZE,private static java.lang.reflect.Method VIRTUAL_FILE_METHOD_TO_URI,private static java.lang.reflect.Method VIRTUAL_FILE_METHOD_TO_URL,protected static java.lang.reflect.Method VIRTUAL_FILE_METHOD_VISIT,protected static Class<?> VIRTUAL_FILE_VISITOR_INTERFACE,private static java.lang.reflect.Field VISITOR_ATTRIBUTES_FIELD_RECURSE,private static volatile boolean initialized |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/util/PatternMatchUtils.java | PatternMatchUtils | simpleMatch | class PatternMatchUtils {
private final static Map<String, Pattern> patterns = new HashMap<>();
public static boolean regexMatch(String pattern, String str) {
if (StringUtils.isEmpty(pattern)) {
return true;
}
Pattern p = patterns.get(pattern);
if (p == null) {
p = Pattern.compile(pattern);
patterns.put(pattern, p);
}
boolean matched = p.matcher(str).matches();
return matched;
}
/**
* Match a String against the given pattern, supporting the following simple
* pattern styles: "xxx*", "*xxx", "*xxx*" and "xxx*yyy" matches (with an
* arbitrary number of pattern parts), as well as direct equality.
*
* @param pattern
* the pattern to match against
* @param str
* the String to match
* @return whether the String matches the given pattern
*/
public static boolean simpleMatch(String pattern, String str) {<FILL_FUNCTION_BODY>}
/**
* Match a String against the given patterns, supporting the following
* simple pattern styles: "xxx*", "*xxx", "*xxx*" and "xxx*yyy" matches
* (with an arbitrary number of pattern parts), as well as direct equality.
*
* @param patterns
* the patterns to match against
* @param str
* the String to match
* @return whether the String matches any of the given patterns
*/
public static boolean simpleMatch(String[] patterns, String str) {
if (patterns != null) {
for (String pattern : patterns) {
if (simpleMatch(pattern, str)) {
return true;
}
}
}
return false;
}
} |
if (pattern == null || str == null) {
return false;
}
int firstIndex = pattern.indexOf('*');
if (firstIndex == -1) {
return pattern.equals(str);
}
if (firstIndex == 0) {
if (pattern.length() == 1) {
return true;
}
int nextIndex = pattern.indexOf('*', firstIndex + 1);
if (nextIndex == -1) {
return str.endsWith(pattern.substring(1));
}
String part = pattern.substring(1, nextIndex);
if ("".equals(part)) {
return simpleMatch(pattern.substring(nextIndex), str);
}
int partIndex = str.indexOf(part);
while (partIndex != -1) {
if (simpleMatch(pattern.substring(nextIndex), str.substring(partIndex + part.length()))) {
return true;
}
partIndex = str.indexOf(part, partIndex + 1);
}
return false;
}
return (str.length() >= firstIndex && pattern.substring(0, firstIndex).equals(str.substring(0, firstIndex)) && simpleMatch(pattern.substring(firstIndex), str.substring(firstIndex)));
| 457 | 321 | 778 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/util/WeakReferenceMonitor.java | MonitoringProcess | run | class MonitoringProcess implements Runnable {
@Override
public void run() {<FILL_FUNCTION_BODY>}
} |
logger.debug("Starting reference monitor thread");
// Check if there are any tracked entries left.
while (keepMonitoringThreadAlive()) {
try {
Reference<?> reference = handleQueue.remove();
// Stop tracking this reference.
ReleaseListener entry = removeEntry(reference);
if (entry != null) {
// Invoke listener callback.
try {
entry.released();
} catch (Throwable ex) {
logger.warning("Reference release listener threw exception", ex);
}
}
} catch (InterruptedException ex) {
synchronized (WeakReferenceMonitor.class) {
monitoringThread = null;
}
logger.debug("Reference monitor thread interrupted", ex);
break;
}
}
| 37 | 192 | 229 | <no_super_class> |
HotswapProjects_HotswapAgent | HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/versions/ArtifactVersion.java | ArtifactVersion | parseVersion | class ArtifactVersion implements Comparable<ArtifactVersion> {
/** The version. */
private final String version;
/** The major version. */
private Integer majorVersion;
/** The minor version. */
private Integer minorVersion;
/** The incremental version. */
private Integer incrementalVersion;
/** The build number. */
private Integer buildNumber;
/** The qualifier. */
private String qualifier;
/** The comparable. */
private ComparableVersion comparable;
/**
* Instantiates a new artifact version.
*
* @param version the version
*/
public ArtifactVersion(String version) {
this.version = version != null ? version.trim() : "";
parseVersion(version);
}
/**
* Gets the version.
*
* @return the version
*/
public String getVersion() {
return version;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return 11 + comparable.hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof ArtifactVersion)) {
return false;
}
return compareTo(ArtifactVersion.class.cast(other)) == 0;
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(ArtifactVersion otherVersion) {
return this.comparable.compareTo(otherVersion.comparable);
}
/**
* Gets the major version.
*
* @return the major version
*/
public int getMajorVersion() {
return majorVersion != null ? majorVersion : 0;
}
/**
* Gets the minor version.
*
* @return the minor version
*/
public int getMinorVersion() {
return minorVersion != null ? minorVersion : 0;
}
/**
* Gets the incremental version.
*
* @return the incremental version
*/
public int getIncrementalVersion() {
return incrementalVersion != null ? incrementalVersion : 0;
}
/**
* Gets the builds the number.
*
* @return the builds the number
*/
public int getBuildNumber() {
return buildNumber != null ? buildNumber : 0;
}
/**
* Gets the qualifier.
*
* @return the qualifier
*/
public String getQualifier() {
return qualifier;
}
/**
* Parses the version.
*
* @param version the version
*/
public final void parseVersion(String version) {<FILL_FUNCTION_BODY>}
/**
* Gets the next integer token.
*
* @param tok the tok
* @return the next integer token
*/
private static Integer getNextIntegerToken(StringTokenizer tok) {
try {
String s = tok.nextToken();
if ((s.length() > 1) && s.startsWith("0")) {
throw new NumberFormatException("Number part has a leading 0: '" + s + "'");
}
return Integer.valueOf(s);
} catch (NoSuchElementException e) {
throw new NumberFormatException("Number is invalid");
}
}
/**
* Dump.
*
* @return the string
*/
public String dump() {
return "ArtifactVersion [version=" + version + ", majorVersion=" + majorVersion + ", minorVersion=" + minorVersion + ", incrementalVersion=" + incrementalVersion + ", buildNumber=" + buildNumber + ", qualifier=" + qualifier + ", comparable=" + comparable + "]";
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return comparable.toString();
}
} |
comparable = new ComparableVersion(version);
int index = version.indexOf("-");
String part1;
String part2 = null;
if (index < 0) {
part1 = version;
} else {
part1 = version.substring(0, index);
part2 = version.substring(index + 1);
}
if (part2 != null) {
try {
if ((part2.length() == 1) || !part2.startsWith("0")) {
buildNumber = Integer.valueOf(part2);
} else {
qualifier = part2;
}
} catch (NumberFormatException e) {
qualifier = part2;
}
}
if ((!part1.contains(".")) && !part1.startsWith("0")) {
try {
majorVersion = Integer.valueOf(part1);
} catch (NumberFormatException e) {
// qualifier is the whole version, including "-"
qualifier = version;
buildNumber = null;
}
} else {
boolean fallback = false;
StringTokenizer tok = new StringTokenizer(part1, ".");
try {
majorVersion = getNextIntegerToken(tok);
if (tok.hasMoreTokens()) {
minorVersion = getNextIntegerToken(tok);
}
if (tok.hasMoreTokens()) {
incrementalVersion = getNextIntegerToken(tok);
}
if (tok.hasMoreTokens()) {
qualifier = tok.nextToken();
fallback = Pattern.compile("\\d+").matcher(qualifier).matches();
}
// string tokenzier won't detect these and ignores them
if (part1.contains("..") || part1.startsWith(".") || part1.endsWith(".")) {
fallback = true;
}
} catch (NumberFormatException e) {
fallback = true;
}
if (fallback) {
// qualifier is the whole version, including "-"
qualifier = version;
majorVersion = null;
minorVersion = null;
incrementalVersion = null;
buildNumber = null;
}
}
| 1,097 | 563 | 1,660 | <no_super_class> |