Java Code Examples for javassist.bytecode.ConstPool

The following are top voted examples for showing how to use javassist.bytecode.ConstPool. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: lams   File: BulkAccessorFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Declares a constructor that takes no parameter.
 *
 * @param classfile The class descriptor
 *
 * @throws CannotCompileException Indicates trouble with the underlying Javassist calls
 */
private void addDefaultConstructor(ClassFile classfile) throws CannotCompileException {
	final ConstPool constPool = classfile.getConstPool();
	final String constructorSignature = "()V";
	final MethodInfo constructorMethodInfo = new MethodInfo( constPool, MethodInfo.nameInit, constructorSignature );

	final Bytecode code = new Bytecode( constPool, 0, 1 );
	// aload_0
	code.addAload( 0 );
	// invokespecial
	code.addInvokespecial( BulkAccessor.class.getName(), MethodInfo.nameInit, constructorSignature );
	// return
	code.addOpcode( Opcode.RETURN );

	constructorMethodInfo.setCodeAttribute( code.toCodeAttribute() );
	constructorMethodInfo.setAccessFlags( AccessFlag.PUBLIC );
	classfile.addMethod( constructorMethodInfo );
}
 
Example 2
Project: lams   File: FieldTransformer.java   Source Code and License 6 votes vote down vote up
private int transformInvokevirtualsIntoGetfields(ClassFile classfile, CodeIterator iter, int pos) {
	final ConstPool constPool = classfile.getConstPool();
	final int c = iter.byteAt( pos );
	if ( c != Opcode.GETFIELD ) {
		return pos;
	}

	final int index = iter.u16bitAt( pos + 1 );
	final String fieldName = constPool.getFieldrefName( index );
	final String className = constPool.getFieldrefClassName( index );
	if ( !filter.handleReadAccess( className, fieldName ) ) {
		return pos;
	}

	final String fieldReaderMethodDescriptor = "()" + constPool.getFieldrefType( index );
	final int fieldReaderMethodIndex = constPool.addMethodrefInfo(
			constPool.getThisClassInfo(),
			EACH_READ_METHOD_PREFIX + fieldName,
			fieldReaderMethodDescriptor
	);
	iter.writeByte( Opcode.INVOKEVIRTUAL, pos );
	iter.write16bit( fieldReaderMethodIndex, pos + 1 );
	return pos;
}
 
Example 3
Project: lams   File: FieldTransformer.java   Source Code and License 6 votes vote down vote up
private int transformInvokevirtualsIntoPutfields(ClassFile classfile, CodeIterator iter, int pos) {
	final ConstPool constPool = classfile.getConstPool();
	final int c = iter.byteAt( pos );
	if ( c != Opcode.PUTFIELD ) {
		return pos;
	}

	final int index = iter.u16bitAt( pos + 1 );
	final String fieldName = constPool.getFieldrefName( index );
	final String className = constPool.getFieldrefClassName( index );
	if ( !filter.handleWriteAccess( className, fieldName ) ) {
		return pos;
	}

	final String fieldWriterMethodDescriptor = "(" + constPool.getFieldrefType( index ) + ")V";
	final int fieldWriterMethodIndex = constPool.addMethodrefInfo(
			constPool.getThisClassInfo(),
			EACH_WRITE_METHOD_PREFIX + fieldName,
			fieldWriterMethodDescriptor
	);
	iter.writeByte( Opcode.INVOKEVIRTUAL, pos );
	iter.write16bit( fieldWriterMethodIndex, pos + 1 );
	return pos;
}
 
Example 4
Project: enigma-vk   File: MethodParametersAttribute.java   Source Code and License 6 votes vote down vote up
public static void updateClass(MethodInfo info, List<String> names) {
	
	// add the names to the class const pool
	ConstPool constPool = info.getConstPool();
	List<Integer> parameterNameIndices = new ArrayList<Integer>();
	for (String name : names) {
		if (name != null) {
			parameterNameIndices.add(constPool.addUtf8Info(name));
		} else {
			parameterNameIndices.add(0);
		}
	}
	
	// add the attribute to the method
	info.addAttribute(new MethodParametersAttribute(constPool, parameterNameIndices));
}
 
Example 5
Project: enigma-vk   File: ClassRenamer.java   Source Code and License 6 votes vote down vote up
private static void renameLocalVariableTypeAttribute(LocalVariableTypeAttribute attribute, ReplacerClassMap map) {
	
	// adapted from LocalVariableAttribute.renameClass()
	ConstPool cp = attribute.getConstPool();
	int n = attribute.tableLength();
	byte[] info = attribute.get();
	for (int i = 0; i < n; ++i) {
		int pos = i * 10 + 2;
		int index = ByteArray.readU16bit(info, pos + 6);
		if (index != 0) {
			String signature = cp.getUtf8Info(index);
			String newSignature = renameLocalVariableSignature(signature, map);
			if (newSignature != null) {
				ByteArray.write16bit(cp.addUtf8Info(newSignature), info, pos + 6);
			}
		}
	}
}
 
Example 6
Project: enigma-vk   File: LocalVariableRenamer.java   Source Code and License 6 votes vote down vote up
public void rename(CtClass c) {
	for (CtBehavior behavior : c.getDeclaredBehaviors()) {
		
		// if there's a local variable table, just rename everything to v1, v2, v3, ... for now
		CodeAttribute codeAttribute = behavior.getMethodInfo().getCodeAttribute();
		if (codeAttribute == null) {
			continue;
		}
		
		BehaviorEntry behaviorEntry = EntryFactory.getBehaviorEntry(behavior);
		ConstPool constants = c.getClassFile().getConstPool();
		
		LocalVariableAttribute table = (LocalVariableAttribute)codeAttribute.getAttribute(LocalVariableAttribute.tag);
		if (table != null) {
			renameLVT(behaviorEntry, constants, table);
		}
		
		LocalVariableTypeAttribute typeTable = (LocalVariableTypeAttribute)codeAttribute.getAttribute(LocalVariableAttribute.typeTag);
		if (typeTable != null) {
			renameLVTT(typeTable, table);
		}
	}
}
 
Example 7
Project: enigma-vk   File: ConstPoolEditor.java   Source Code and License 6 votes vote down vote up
public static ConstPool newConstPool() {
	// const pool expects the name of a class to initialize itself
	// but we want an empty pool
	// so give it a bogus name, and then clear the entries afterwards
	ConstPool pool = new ConstPool("a");
	
	ConstPoolEditor editor = new ConstPoolEditor(pool);
	int size = pool.getSize();
	for (int i = 0; i < size - 1; i++) {
		editor.removeLastItem();
	}
	
	// make sure the pool is actually empty
	// although, in this case "empty" means one thing in it
	// the JVM spec says index 0 should be reserved
	assert (pool.getSize() == 1);
	assert (editor.getItem(0) == null);
	assert (editor.getItem(1) == null);
	assert (editor.getItem(2) == null);
	assert (editor.getItem(3) == null);
	
	// also, clear the cache
	editor.getCache().clear();
	
	return pool;
}
 
Example 8
Project: JCL   File: Annotation.java   Source Code and License 6 votes vote down vote up
/**
 * 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 (int i = 0; i < methods.length; i++) {
        CtClass returnType = methods[i].getReturnType();
        addMemberValue(methods[i].getName(),
                       createMemberValue(cp, returnType));
        
    }
}
 
Example 9
Project: JCL   File: Analyzer.java   Source Code and License 6 votes vote down vote up
private ExceptionInfo[] buildExceptionInfo(MethodInfo method) {
    ConstPool constPool = method.getConstPool();
    ClassPool classes = clazz.getClassPool();

    ExceptionTable table = method.getCodeAttribute().getExceptionTable();
    ExceptionInfo[] exceptions = new ExceptionInfo[table.size()];
    for (int i = 0; i < table.size(); i++) {
        int index = table.catchType(i);
        Type type;
        try {
            type = index == 0 ? Type.THROWABLE : Type.get(classes.get(constPool.getClassInfo(index)));
        } catch (NotFoundException e) {
            throw new IllegalStateException(e.getMessage());
        }

        exceptions[i] = new ExceptionInfo(table.startPc(i), table.endPc(i), table.handlerPc(i), type);
    }

    return exceptions;
}
 
Example 10
Project: JCL   File: Tracer.java   Source Code and License 6 votes vote down vote up
private void doLDC(int index) {
    TypeData[] stackTypes = this.stackTypes;
    int tag = cpool.getTag(index);
    if (tag == ConstPool.CONST_String)
        stackTypes[stackTop++] = new TypeData.ClassName("java.lang.String");
    else if (tag == ConstPool.CONST_Integer)
        stackTypes[stackTop++] = INTEGER;
    else if (tag == ConstPool.CONST_Float)
        stackTypes[stackTop++] = FLOAT;
    else if (tag == ConstPool.CONST_Long) {
        stackTypes[stackTop++] = LONG;
        stackTypes[stackTop++] = TOP;
    }
    else if (tag == ConstPool.CONST_Double) {
        stackTypes[stackTop++] = DOUBLE;
        stackTypes[stackTop++] = TOP;
    }
    else if (tag == ConstPool.CONST_Class)
        stackTypes[stackTop++] = new TypeData.ClassName("java.lang.Class");
    else
        throw new RuntimeException("bad LDC: " + tag);
}
 
Example 11
Project: JCL   File: ClassPoolTail.java   Source Code and License 6 votes vote down vote up
public List<FieldInfo> getClassFields(String classname, ConstPool cp) {
	ClassPathList list = pathList;
    List<FieldInfo> fields = null;
    while (list != null) {
    	if (!(list.path instanceof DalvikClassPath)) {
    		list = list.next;
    		continue;
    	}
    	
        fields = ((DalvikClassPath)list.path).getClassFields(classname, cp);
        
        if (fields == null)
            list = list.next;
        else
            return fields;
    }

    return null;    // not found
}
 
Example 12
Project: JCL   File: ClassPoolTail.java   Source Code and License 6 votes vote down vote up
public List<MethodInfo> getClassMethods(String classname, ConstPool cp) {
	ClassPathList list = pathList;
    List<MethodInfo> methods = null;
    while (list != null) {
    	if (!(list.path instanceof DalvikClassPath)) {
    		list = list.next;
    		continue;
    	}
    	
    	methods = ((DalvikClassPath)list.path).getClassMethods(classname, cp);
        
        if (methods == null)
            list = list.next;
        else
            return methods;
    }

    return null;    // not found
}
 
Example 13
Project: Enigma   File: MethodParametersAttribute.java   Source Code and License 6 votes vote down vote up
public static void updateClass(MethodInfo info, List<String> names) {

        // add the names to the class const pool
        ConstPool constPool = info.getConstPool();
        List<Integer> parameterNameIndices = new ArrayList<>();
        for (String name : names) {
            if (name != null) {
                parameterNameIndices.add(constPool.addUtf8Info(name));
            } else {
                parameterNameIndices.add(0);
            }
        }

        // add the attribute to the method
        info.addAttribute(new MethodParametersAttribute(constPool, parameterNameIndices));
    }
 
Example 14
Project: jVoid   File: JavassistUtils.java   Source Code and License 6 votes vote down vote up
/**
 * This is basically the InstructionPrinter.getMethodBytecode but with a
 * CtBehaviour parameter instead of a CtMethod
 * 
 * @param behavior
 * @return
 */
public static String getBehaviourBytecode(CtBehavior behavior) {
    MethodInfo info = behavior.getMethodInfo2();
    CodeAttribute code = info.getCodeAttribute();
    if (code == null) {
        return "";
    }

    ConstPool pool = info.getConstPool();
    StringBuilder sb = new StringBuilder(1024);

    CodeIterator iterator = code.iterator();
    while (iterator.hasNext()) {
        int pos;
        try {
            pos = iterator.next();
        } catch (BadBytecode e) {
            throw new JVoidIntrumentationException("BadBytecoode", e);
        }

        sb.append(pos + ": " + InstructionPrinter.instructionString(iterator, pos, pool) + "\n");
    }
    return sb.toString();
}
 
Example 15
Project: metaworks_framework   File: DirectCopyClassTransformer.java   Source Code and License 6 votes vote down vote up
protected Annotation getEntityListeners(ConstPool constantPool, Annotation existingEntityListeners, Annotation templateEntityListeners) {
    Annotation listeners = new Annotation(EntityListeners.class.getName(), constantPool);
    ArrayMemberValue listenerArray = new ArrayMemberValue(constantPool);
    Set<MemberValue> listenerMemberValues = new HashSet<MemberValue>();
    {
        ArrayMemberValue templateListenerValues = (ArrayMemberValue) templateEntityListeners.getMemberValue("value");
        listenerMemberValues.addAll(Arrays.asList(templateListenerValues.getValue()));
        logger.debug("Adding template values to new EntityListeners");
    }
    if (existingEntityListeners != null) {
        ArrayMemberValue oldListenerValues = (ArrayMemberValue) existingEntityListeners.getMemberValue("value");
        listenerMemberValues.addAll(Arrays.asList(oldListenerValues.getValue()));
        logger.debug("Adding previous values to new EntityListeners");
    }
    listenerArray.setValue(listenerMemberValues.toArray(new MemberValue[listenerMemberValues.size()]));
    listeners.addMemberValue("value", listenerArray);

    return listeners;

}
 
Example 16
Project: cacheonix-core   File: BulkAccessorFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Declares a constructor that takes no parameter.
 *
 * @param classfile
 * @throws CannotCompileException
 */
private void addDefaultConstructor(ClassFile classfile) throws CannotCompileException {
	ConstPool cp = classfile.getConstPool();
	String cons_desc = "()V";
	MethodInfo mi = new MethodInfo( cp, MethodInfo.nameInit, cons_desc );

	Bytecode code = new Bytecode( cp, 0, 1 );
	// aload_0
	code.addAload( 0 );
	// invokespecial
	code.addInvokespecial( BulkAccessor.class.getName(), MethodInfo.nameInit, cons_desc );
	// return
	code.addOpcode( Opcode.RETURN );

	mi.setCodeAttribute( code.toCodeAttribute() );
	mi.setAccessFlags( AccessFlag.PUBLIC );
	classfile.addMethod( mi );
}
 
Example 17
Project: cacheonix-core   File: FieldTransformer.java   Source Code and License 6 votes vote down vote up
private void addGetFieldHandlerMethod(ClassFile classfile)
		throws CannotCompileException {
	ConstPool cp = classfile.getConstPool();
	int this_class_index = cp.getThisClassInfo();
	MethodInfo minfo = new MethodInfo(cp, GETFIELDHANDLER_METHOD_NAME,
	                                  GETFIELDHANDLER_METHOD_DESCRIPTOR);
	/* local variable | this | */
	Bytecode code = new Bytecode(cp, 2, 1);
	// aload_0 // load this
	code.addAload(0);
	// getfield // get field "$JAVASSIST_CALLBACK" defined already
	code.addOpcode(Opcode.GETFIELD);
	int field_index = cp.addFieldrefInfo(this_class_index,
	                                     HANDLER_FIELD_NAME, HANDLER_FIELD_DESCRIPTOR);
	code.addIndex(field_index);
	// areturn // return the value of the field
	code.addOpcode(Opcode.ARETURN);
	minfo.setCodeAttribute(code.toCodeAttribute());
	minfo.setAccessFlags(AccessFlag.PUBLIC);
	classfile.addMethod(minfo);
}
 
Example 18
Project: cacheonix-core   File: FieldTransformer.java   Source Code and License 6 votes vote down vote up
private void addSetFieldHandlerMethod(ClassFile classfile)
		throws CannotCompileException {
	ConstPool cp = classfile.getConstPool();
	int this_class_index = cp.getThisClassInfo();
	MethodInfo minfo = new MethodInfo(cp, SETFIELDHANDLER_METHOD_NAME,
	                                  SETFIELDHANDLER_METHOD_DESCRIPTOR);
	/* local variables | this | callback | */
	Bytecode code = new Bytecode(cp, 3, 3);
	// aload_0 // load this
	code.addAload(0);
	// aload_1 // load callback
	code.addAload(1);
	// putfield // put field "$JAVASSIST_CALLBACK" defined already
	code.addOpcode(Opcode.PUTFIELD);
	int field_index = cp.addFieldrefInfo(this_class_index,
	                                     HANDLER_FIELD_NAME, HANDLER_FIELD_DESCRIPTOR);
	code.addIndex(field_index);
	// return
	code.addOpcode(Opcode.RETURN);
	minfo.setCodeAttribute(code.toCodeAttribute());
	minfo.setAccessFlags(AccessFlag.PUBLIC);
	classfile.addMethod(minfo);
}
 
Example 19
Project: cacheonix-core   File: FieldTransformer.java   Source Code and License 6 votes vote down vote up
private int transformInvokevirtualsIntoGetfields(ClassFile classfile,
                                                 CodeIterator iter, int pos) {
	ConstPool cp = classfile.getConstPool();
	int c = iter.byteAt(pos);
	if (c != Opcode.GETFIELD) {
		return pos;
	}
	int index = iter.u16bitAt(pos + 1);
	String fieldName = cp.getFieldrefName(index);
	String className = cp.getFieldrefClassName(index);
	if ((!classfile.getName().equals(className))
	    || (!readableFields.containsKey(fieldName))) {
		return pos;
	}
	String desc = "()" + (String) readableFields.get(fieldName);
	int read_method_index = cp.addMethodrefInfo(cp.getThisClassInfo(),
	                                            EACH_READ_METHOD_PREFIX + fieldName, desc);
	iter.writeByte(Opcode.INVOKEVIRTUAL, pos);
	iter.write16bit(read_method_index, pos + 1);
	return pos;
}
 
Example 20
Project: cacheonix-core   File: FieldTransformer.java   Source Code and License 6 votes vote down vote up
private int transformInvokevirtualsIntoPutfields(ClassFile classfile,
                                                 CodeIterator iter, int pos) {
	ConstPool cp = classfile.getConstPool();
	int c = iter.byteAt(pos);
	if (c != Opcode.PUTFIELD) {
		return pos;
	}
	int index = iter.u16bitAt(pos + 1);
	String fieldName = cp.getFieldrefName(index);
	String className = cp.getFieldrefClassName(index);
	if ((!classfile.getName().equals(className))
	    || (!writableFields.containsKey(fieldName))) {
		return pos;
	}
	String desc = "(" + (String) writableFields.get(fieldName) + ")V";
	int write_method_index = cp.addMethodrefInfo(cp.getThisClassInfo(),
	                                             EACH_WRITE_METHOD_PREFIX + fieldName, desc);
	iter.writeByte(Opcode.INVOKEVIRTUAL, pos);
	iter.write16bit(write_method_index, pos + 1);
	return pos;
}
 
Example 21
Project: SparkCommerce   File: DirectCopyClassTransformer.java   Source Code and License 6 votes vote down vote up
protected Annotation getEntityListeners(ConstPool constantPool, Annotation existingEntityListeners, Annotation templateEntityListeners) {
    Annotation listeners = new Annotation(EntityListeners.class.getName(), constantPool);
    ArrayMemberValue listenerArray = new ArrayMemberValue(constantPool);
    Set<MemberValue> listenerMemberValues = new HashSet<MemberValue>();
    {
        ArrayMemberValue templateListenerValues = (ArrayMemberValue) templateEntityListeners.getMemberValue("value");
        listenerMemberValues.addAll(Arrays.asList(templateListenerValues.getValue()));
        logger.debug("Adding template values to new EntityListeners");
    }
    if (existingEntityListeners != null) {
        ArrayMemberValue oldListenerValues = (ArrayMemberValue) existingEntityListeners.getMemberValue("value");
        listenerMemberValues.addAll(Arrays.asList(oldListenerValues.getValue()));
        logger.debug("Adding previous values to new EntityListeners");
    }
    listenerArray.setValue(listenerMemberValues.toArray(new MemberValue[listenerMemberValues.size()]));
    listeners.addMemberValue("value", listenerArray);

    return listeners;

}
 
Example 22
Project: Wurst-Enigma   File: MethodParametersAttribute.java   Source Code and License 6 votes vote down vote up
public static void updateClass(MethodInfo info, List<String> names)
{
	
	// add the names to the class const pool
	ConstPool constPool = info.getConstPool();
	List<Integer> parameterNameIndices = new ArrayList<Integer>();
	for(String name : names)
		if(name != null)
			parameterNameIndices.add(constPool.addUtf8Info(name));
		else
			parameterNameIndices.add(0);
	
	// add the attribute to the method
	info.addAttribute(new MethodParametersAttribute(constPool,
		parameterNameIndices));
}
 
Example 23
Project: Wurst-Enigma   File: ConstPoolEditor.java   Source Code and License 6 votes vote down vote up
public static ConstPool newConstPool()
{
	// const pool expects the name of a class to initialize itself
	// but we want an empty pool
	// so give it a bogus name, and then clear the entries afterwards
	ConstPool pool = new ConstPool("a");
	
	ConstPoolEditor editor = new ConstPoolEditor(pool);
	int size = pool.getSize();
	for(int i = 0; i < size - 1; i++)
		editor.removeLastItem();
	
	// make sure the pool is actually empty
	// although, in this case "empty" means one thing in it
	// the JVM spec says index 0 should be reserved
	assert pool.getSize() == 1;
	assert editor.getItem(0) == null;
	assert editor.getItem(1) == null;
	assert editor.getItem(2) == null;
	assert editor.getItem(3) == null;
	
	// also, clear the cache
	editor.getCache().clear();
	
	return pool;
}
 
Example 24
Project: blcdemo   File: DirectCopyClassTransformer.java   Source Code and License 6 votes vote down vote up
protected Annotation getEntityListeners(ConstPool constantPool, Annotation existingEntityListeners, Annotation templateEntityListeners) {
    Annotation listeners = new Annotation(EntityListeners.class.getName(), constantPool);
    ArrayMemberValue listenerArray = new ArrayMemberValue(constantPool);
    Set<MemberValue> listenerMemberValues = new HashSet<MemberValue>();
    {
        ArrayMemberValue templateListenerValues = (ArrayMemberValue) templateEntityListeners.getMemberValue("value");
        listenerMemberValues.addAll(Arrays.asList(templateListenerValues.getValue()));
        logger.debug("Adding template values to new EntityListeners");
    }
    if (existingEntityListeners != null) {
        ArrayMemberValue oldListenerValues = (ArrayMemberValue) existingEntityListeners.getMemberValue("value");
        listenerMemberValues.addAll(Arrays.asList(oldListenerValues.getValue()));
        logger.debug("Adding previous values to new EntityListeners");
    }
    listenerArray.setValue(listenerMemberValues.toArray(new MemberValue[listenerMemberValues.size()]));
    listeners.addMemberValue("value", listenerArray);

    return listeners;

}
 
Example 25
Project: korat   File: JavassistInstructionVisitor.java   Source Code and License 6 votes vote down vote up
public JavassistInstructionVisitor(ClassPool classPool,
        ConstPool constPool, OperandStack localStack) {

    this.classPool = classPool;
    this.constPool = constPool;
    this.operandStack = localStack;
    try {
        this.objectType = classPool.get("java.lang.Object");
        this.stringType = classPool.get("java.lang.String");
        this.classType = classPool.get("java.lang.Class");
        this.booleanType = CtClass.booleanType;
        this.byteType = CtClass.byteType;
        this.charType = CtClass.charType;
        this.doubleType = CtClass.doubleType;
        this.floatType = CtClass.floatType;
        this.intType = CtClass.intType;
        this.longType = CtClass.longType;
        this.shortType = CtClass.shortType;
        this.voidType = CtClass.voidType;
    } catch (NotFoundException e) {
    }

}
 
Example 26
Project: guice-ext-annotations   File: JavassistUtils.java   Source Code and License 6 votes vote down vote up
/**
 * @param classPool class pool to use
 * @param constPool constants pool
 * @param ann       annotation to copy
 * @return javassist annotation object (copy of original annotation)
 * @throws Exception on errors
 */
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public static Annotation copyAnnotation(final ClassPool classPool, final ConstPool constPool,
                                        final java.lang.annotation.Annotation ann) throws Exception {
    final Class<? extends java.lang.annotation.Annotation> annotationType = ann.annotationType();
    final Annotation copy = new Annotation(annotationType.getName(), constPool);
    final Method[] methods = annotationType.getDeclaredMethods();
    for (final Method method : methods) {
        final CtClass ctType = classPool.get(method.getReturnType().getName());
        final MemberValue memberValue = Annotation.createMemberValue(constPool, ctType);
        final Object value = method.invoke(ann);
        memberValue.accept(new AnnotationMemberValueVisitor(classPool, constPool, value));
        copy.addMemberValue(method.getName(), memberValue);
    }
    return copy;
}
 
Example 27
Project: JMXMPAgent   File: FibonnoitreClassFileTransformer.java   Source Code and License 6 votes vote down vote up
protected void instrumentMethod(final CtMethod ctm, final ConstPool constpool) {
	try {
		if(ctm.getAnnotation(susAnn)==null) {
			AnnotationsAttribute attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag);
			javassist.bytecode.annotation.Annotation annot = new javassist.bytecode.annotation.Annotation(susAnn.getName(), constpool);
			attr.addAnnotation(annot);
			ctm.getMethodInfo().addAttribute(attr);
		}
		/*
		 * Install latch. Needs to be accessible in finally block, so we need a singleton registry.
		 * Spin up fiber and invoke this method in fiber
		 * 	-- static method
		 *  -- non static method
		 * Fiber execution: accumulate all pending sub-fibers
		 * finally block:
		 *  -- if running in thread, skip.
		 * 	-- send batch
		 *  -- wait for all sub-fibers to complete
		 *  -- drop thread latch
		 *  
		 */
	} catch (Exception ex) {
		ex.printStackTrace(System.err);
		throw new RuntimeException(ex);
	}
}
 
Example 28
Project: mimic   File: MimicProcessorTest.java   Source Code and License 6 votes vote down vote up
private void addMimicAnnotation(CtClass dst, String sourceClassName,
        boolean isMimicingInterfaces, boolean isMimicingFields,
        boolean isMimicingConstructors, boolean isMimicingMethods) {
    ClassFile cf = dst.getClassFile();
    ConstPool cp = cf.getConstPool();
    AnnotationsAttribute attr = new AnnotationsAttribute(cp,
            AnnotationsAttribute.visibleTag);

    Annotation a = new Annotation(Mimic.class.getName(), cp);
    a.addMemberValue("sourceClass", new ClassMemberValue(sourceClassName,
            cp));
    a.addMemberValue("isMimicingInterfaces", new BooleanMemberValue(
            isMimicingInterfaces, cp));
    a.addMemberValue("isMimicingFields", new BooleanMemberValue(
            isMimicingFields, cp));
    a.addMemberValue("isMimicingConstructors", new BooleanMemberValue(
            isMimicingConstructors, cp));
    a.addMemberValue("isMimicingMethods", new BooleanMemberValue(
            isMimicingMethods, cp));
    attr.setAnnotation(a);
    cf.addAttribute(attr);
    cf.setVersionToJava5();
}
 
Example 29
Project: hyaline-dto   File: JavassistBasedClassBuilder.java   Source Code and License 6 votes vote down vote up
private void handleMethodDescriptions(DTODescription description, String targetFieldName, ClassPool classPool,
		CtClass hyalineProxyClass, ConstPool constpool) throws CannotCompileException, CannotBuildClassException {
	for (MethodDescription method : description.getMethods().values()) {
		// Handle only getters and setters
		String methodName = method.getMethod().getName();

		// check the method is not final
		if (!Modifier.isFinal(method.getMethod().getModifiers())) {
			if (methodName.startsWith("get") || methodName.startsWith("set") || methodName.startsWith("is")) {
				CtMethod ctMethod;
				try {
					ctMethod = createMethodFromDescription(classPool, targetFieldName, constpool, method,
							hyalineProxyClass, description);
					if (ctMethod != null) {
						// could correlate method name to accessed field
						hyalineProxyClass.addMethod(ctMethod);
					}
				} catch (FieldNotFoundException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
 
Example 30
Project: hyaline-dto   File: JavassistUtils.java   Source Code and License 6 votes vote down vote up
public static Annotation createJavassistAnnotation(ConstPool constpool,
		java.lang.annotation.Annotation annotation)
		throws CannotBuildClassException {

	Annotation annotationCopy = new Annotation(annotation.annotationType()
			.getName(), constpool);
	for (Method m : annotation.annotationType().getDeclaredMethods()) {
		try {
			Object value = m.invoke(annotation);
			annotationCopy.addMemberValue(m.getName(),
					JavassistUtils.createMemberValue(value, constpool));
		} catch (IllegalAccessException | IllegalArgumentException
				| InvocationTargetException e) {
			e.printStackTrace();
			throw new CannotBuildClassException(
					"Could not copy info from annotation "
							+ annotation.annotationType().getName());
		}
	}
	return annotationCopy;
}
 
Example 31
Project: statefulj   File: SpringMVCBinder.java   Source Code and License 6 votes vote down vote up
@Override
protected void addEndpointMapping(CtMethod ctMethod, String method, String request) {
	MethodInfo methodInfo = ctMethod.getMethodInfo();
	ConstPool constPool = methodInfo.getConstPool();

	AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
	Annotation requestMapping = new Annotation(RequestMapping.class.getName(), constPool);

	ArrayMemberValue valueVals = new ArrayMemberValue(constPool);
	StringMemberValue valueVal = new StringMemberValue(constPool);
	valueVal.setValue(request);
	valueVals.setValue(new MemberValue[]{valueVal});

	requestMapping.addMemberValue("value", valueVals);

	ArrayMemberValue methodVals = new ArrayMemberValue(constPool);
	EnumMemberValue methodVal = new EnumMemberValue(constPool);
	methodVal.setType(RequestMethod.class.getName());
	methodVal.setValue(method);
	methodVals.setValue(new MemberValue[]{methodVal});

	requestMapping.addMemberValue("method", methodVals);
	attr.addAnnotation(requestMapping);
	methodInfo.addAttribute(attr);
}
 
Example 32
Project: ameba-dev   File: EbeanEnhancer.java   Source Code and License 6 votes vote down vote up
private void addDbCommentAnnotation(AnnotationsAttribute attribute) {
    if (attribute.getAnnotation(DbComment.class.getName()) != null) return;

    StringBuilder builder = new StringBuilder();
    String display = appendDbCommentValue(attribute, Display.class);
    if (StringUtils.isNotBlank(display))
        builder.append(display);
    String desc = appendDbCommentValue(attribute, Description.class);
    if (StringUtils.isNotBlank(desc))
        builder.append(" ").append(desc);

    if (builder.length() > 0) {
        Map<String, MemberValue> valueMap = Maps.newHashMap();
        ConstPool cp = attribute.getConstPool();
        valueMap.put("value", new StringMemberValue(builder.toString()
                .replace("'", "''")
                .replace("\r", " ")
                .replace("\n", " "), cp));
        addAnnotation(attribute, DbComment.class, valueMap);
    }
}
 
Example 33
Project: spassMeter   File: CodeModifier.java   Source Code and License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void addAnnotation(IClass cls, Class<? extends Annotation> ann, 
    HashMap<String, Object> values) 
    throws InstrumenterException {
    CtClass cl = ((JAClass) cls).getCtClass();
    ClassFile ccFile = cl.getClassFile();
    ConstPool constpool = ccFile.getConstPool();
    AnnotationsAttribute attr = new AnnotationsAttribute(constpool, 
        AnnotationsAttribute.visibleTag);
    javassist.bytecode.annotation.Annotation marker 
        = new javassist.bytecode.annotation.Annotation(
            ann.getName(), constpool);
    setValues(marker, constpool, values);
    attr.addAnnotation(marker);
    cl.getClassFile().addAttribute(attr);
}
 
Example 34
Project: spassMeter   File: CodeModifier.java   Source Code and License 6 votes vote down vote up
/**
 * Sets the values for an annotation.
 * 
 * @param annotation the annotation
 * @param cp the class pool
 * @param values the values as name-value mappings
 * 
 * @since 1.00
 */
private void setValues(javassist.bytecode.annotation.Annotation annotation, 
    ConstPool cp, HashMap<String, Object> values) {
    if (null != values) {
        Iterator<HashMap.Entry<String, Object>> iter 
            = values.entries().iterator();
        while (iter.hasNext()) {
            HashMap.Entry<String, Object> ent = iter.next();
            MemberValue mVal = createMemberValue(ent.getValue(), cp);
            if (null != mVal) {
                annotation.addMemberValue(ent.getKey(), mVal);
            }
        }
    }
    
}
 
Example 35
Project: spassMeter   File: CodeModifier.java   Source Code and License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void addAnnotation(IBehavior behavior, 
    Class<? extends Annotation> ann, HashMap<String, Object> values) 
    throws InstrumenterException {

    CtBehavior b = ((JABehavior) behavior).getBehavior();
    CtClass cl = ((JAClass) behavior.getDeclaringClass()).getCtClass();
    ClassFile ccFile = cl.getClassFile();
    ConstPool constpool = ccFile.getConstPool();
    AnnotationsAttribute attr = new AnnotationsAttribute(constpool, 
        AnnotationsAttribute.visibleTag);
    javassist.bytecode.annotation.Annotation marker 
        = new javassist.bytecode.annotation.Annotation(
            ann.getName(), constpool);
    setValues(marker, constpool, values);
    attr.addAnnotation(marker);
    b.getMethodInfo().addAttribute(attr);
}
 
Example 36
Project: statefulj   File: JavassistUtils.java   Source Code and License 6 votes vote down vote up
public static void addClassAnnotation(CtClass clazz, Class<?> annotationClass, Object... values) {
	ClassFile ccFile = clazz.getClassFile();
	ConstPool constPool = ccFile.getConstPool();
	AnnotationsAttribute attr = getAnnotationsAttribute(ccFile);
	Annotation annot = new Annotation(annotationClass.getName(), constPool);
	
	for(int i = 0; i < values.length; i = i + 2) {
		String valueName = (String)values[i];
		Object value = values[i+1];
		if (valueName != null && value != null) {
			MemberValue memberValue = createMemberValue(constPool, value);
			annot.addMemberValue(valueName, memberValue);
		}
	}
	
	attr.addAnnotation(annot);
}
 
Example 37
Project: statefulj   File: AbstractRestfulBinder.java   Source Code and License 6 votes vote down vote up
protected Annotation[] addIdParameter(
		CtMethod ctMethod, 
		Class<?> idType,
		ClassPool cp) throws NotFoundException, CannotCompileException {
	// Clone the parameter Class
	//
	CtClass ctParm = cp.get(idType.getName());
	
	// Add the parameter to the method
	//
	ctMethod.addParameter(ctParm);
	
	// Add the Parameter Annotations to the Method
	//
	MethodInfo methodInfo = ctMethod.getMethodInfo();
	ConstPool constPool = methodInfo.getConstPool();
	Annotation annot = new Annotation(getPathAnnotationClass().getName(), constPool);
	
	StringMemberValue valueVal = new StringMemberValue("id", constPool); 
	annot.addMemberValue("value", valueVal);
	
	return new Annotation[]{ annot };
}
 
Example 38
Project: moxiemocks   File: MagicLambdaHelper.java   Source Code and License 6 votes vote down vote up
private static MethodAdapter guessMethod(ClassPool classPool, ConstPool constPool, int descriptorRef, boolean isStatic, boolean isInterface) throws ClassNotFoundException, NotFoundException {
    String magicMethodClassName, magicMethodName, magicMethodDescriptor;
    if (isInterface) {
        magicMethodClassName = constPool.getInterfaceMethodrefClassName(descriptorRef);
        magicMethodName = constPool.getInterfaceMethodrefName(descriptorRef);
        magicMethodDescriptor = constPool.getInterfaceMethodrefType(descriptorRef);
    } else {
        magicMethodClassName = constPool.getMethodrefClassName(descriptorRef);
        magicMethodName = constPool.getMethodrefName(descriptorRef);
        magicMethodDescriptor = constPool.getMethodrefType(descriptorRef);
    }
    Class magicMethodClass = Class.forName(magicMethodClassName);
    CtClass[] magicMethodParamCtTypes = Descriptor.getParameterTypes(magicMethodDescriptor, classPool);
    Class[] magicMethodParamTypes = new Class[magicMethodParamCtTypes.length];
    for (int i = 0; i < magicMethodParamCtTypes.length; i++) {
        magicMethodParamTypes[i] = getJvmClassForCtClass(magicMethodParamCtTypes[i]);
    }

    return MoxieUtils.guessMethod(magicMethodClass, magicMethodName, isStatic, magicMethodParamTypes, null);
}
 
Example 39
Project: statefulj   File: JavassistUtils.java   Source Code and License 6 votes vote down vote up
public static void addMethodAnnotations(CtMethod ctMethod, Method method) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
	if (method != null) {
		MethodInfo methodInfo = ctMethod.getMethodInfo();
		ConstPool constPool = methodInfo.getConstPool();
		AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
		methodInfo.addAttribute(attr);
		for(java.lang.annotation.Annotation anno : method.getAnnotations()) {

			// If it's a Transition skip
			// TODO : Make this a parameterized set of Filters instead of hardcoding
			//
			Annotation clone = null;
			if (anno instanceof Transitions || anno instanceof Transition) {
				// skip
			} else {
				clone = cloneAnnotation(constPool, anno);
				attr.addAnnotation(clone);
			}
		}
	}
}
 
Example 40
Project: EndHQ-Libraries   File: Annotation.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
    }

    for (int i = 0; i < methods.length; i++) {
        CtClass returnType = methods[i].getReturnType();
        addMemberValue(methods[i].getName(),
                       createMemberValue(cp, returnType));
        
    }
}