Java Code Examples for javassist.bytecode.ClassFile

The following are top voted examples for showing how to use javassist.bytecode.ClassFile. 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   View source code 6 votes vote down vote up
BulkAccessor create() {
	final Method[] getters = new Method[getterNames.length];
	final Method[] setters = new Method[setterNames.length];
	findAccessors( targetBean, getterNames, setterNames, types, getters, setters );

	final Class beanClass;
	try {
		final ClassFile classfile = make( getters, setters );
		final ClassLoader loader = this.getClassLoader();
		if ( writeDirectory != null ) {
			FactoryHelper.writeFile( classfile, writeDirectory );
		}

		beanClass = FactoryHelper.toClass( classfile, loader, getDomain() );
		return (BulkAccessor) this.newInstance( beanClass );
	}
	catch ( Exception e ) {
		throw new BulkAccessorException( e.getMessage(), e );
	}
}
 
Example 2
Project: lams   File: BulkAccessorFactory.java   View source code 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 3
Project: lams   File: FieldTransformer.java   View source code 6 votes vote down vote up
/**
 * Transform the class defined by the given ClassFile descriptor.  The ClassFile descriptor itself is mutated
 *
 * @param classFile The class file descriptor
 *
 * @throws Exception Indicates a problem performing the transformation
 */
public void transform(ClassFile classFile) throws Exception {
	if ( classFile.isInterface() ) {
		return;
	}
	try {
		addFieldHandlerField( classFile );
		addGetFieldHandlerMethod( classFile );
		addSetFieldHandlerMethod( classFile );
		addFieldHandledInterface( classFile );
		addReadWriteMethods( classFile );
		transformInvokevirtualsIntoPutAndGetfields( classFile );
	}
	catch (CannotCompileException e) {
		throw new RuntimeException( e.getMessage(), e );
	}
}
 
Example 4
Project: lams   File: FieldTransformer.java   View source code 6 votes vote down vote up
private void transformInvokevirtualsIntoPutAndGetfields(ClassFile classfile) throws CannotCompileException, BadBytecode {
	for ( Object o : classfile.getMethods() ) {
		final MethodInfo methodInfo = (MethodInfo) o;
		final String methodName = methodInfo.getName();
		if ( methodName.startsWith( EACH_READ_METHOD_PREFIX )
				|| methodName.startsWith( EACH_WRITE_METHOD_PREFIX )
				|| methodName.equals( GETFIELDHANDLER_METHOD_NAME )
				|| methodName.equals( SETFIELDHANDLER_METHOD_NAME ) ) {
			continue;
		}

		final CodeAttribute codeAttr = methodInfo.getCodeAttribute();
		if ( codeAttr == null ) {
			continue;
		}

		final CodeIterator iter = codeAttr.iterator();
		while ( iter.hasNext() ) {
			int pos = iter.next();
			pos = transformInvokevirtualsIntoGetfields( classfile, iter, pos );
			transformInvokevirtualsIntoPutfields( classfile, iter, pos );
		}
		final StackMapTable smt = MapMaker.make( classPool, methodInfo );
		codeAttr.setAttribute( smt );
	}
}
 
Example 5
Project: lams   File: FieldTransformer.java   View source code 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 6
Project: lams   File: FieldTransformer.java   View source code 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 7
Project: JCL   File: CtNewNestedClass.java   View source code 6 votes vote down vote up
private static void updateInnerEntry(int mod, String name, CtClass clazz, boolean outer) {
    ClassFile cf = clazz.getClassFile2();
    InnerClassesAttribute ica = (InnerClassesAttribute)cf.getAttribute(
                                            InnerClassesAttribute.tag);
    if (ica == null)
        return;

    int n = ica.tableLength();
    for (int i = 0; i < n; i++)
        if (name.equals(ica.innerClass(i))) {
            int acc = ica.accessFlags(i) & AccessFlag.STATIC;
            ica.setAccessFlags(i, mod | acc);
            String outName = ica.outerClass(i);
            if (outName != null && outer)
                try {
                    CtClass parent = clazz.getClassPool().get(outName);
                    updateInnerEntry(mod, name, parent, false);
                }
                catch (NotFoundException e) {
                    throw new RuntimeException("cannot find the declaring class: "
                                               + outName);
                }

            break;
        }
}
 
Example 8
Project: JCL   File: CtClass.java   View source code 6 votes vote down vote up
/**
  * Returns a collection of the names of all the classes
  * referenced in this class.
  * That collection includes the name of this class.
  *
  * <p>This method may return <code>null</code>.
  *
  * @return a <code>Collection&lt;String&gt;</code> object.
  */
 public synchronized Collection<String> getRefClasses() {
     ClassFile cf = getClassFile2();
     if (cf != null) {
         @SuppressWarnings("serial")
ClassMap cm = new ClassMap() {
             public String put(String oldname, String newname) {
                 return put0(oldname, newname);
             }

             public String get(Object jvmClassName) {
                 String n = toJavaName((String)jvmClassName);
                 put0(n, n);
                 return null;
             }

             public void fix(String name) {}
         };
         cf.getRefClasses(cm);
         return cm.values();
     }
     else
         return null;
 }
 
Example 9
Project: JCL   File: DalvikClassClassPath.java   View source code 6 votes vote down vote up
@Override
public ClassFile getClassFile(String classname) throws NotFoundException {
	Class<?> clazz = null;
	try {
		clazz = this.apk.getClass(classname);
	} catch (ClassNotFoundException e) {
		throw new NotFoundException(e.getMessage(), e);
	}
	
	final Class<?> superClass = clazz.getSuperclass();
	final ClassFile cf = new ClassFile(clazz.isInterface(), classname, null == superClass ? null : superClass.getName());
	
	addFields(cf, clazz);
	addConstructors(cf, clazz);
	addMethods(cf, clazz);
	
	return cf;
}
 
Example 10
Project: JCL   File: CtNewClass.java   View source code 6 votes vote down vote up
CtNewClass(String name, ClassPool cp,
           boolean isInterface, CtClass superclass) {
    super(name, cp);
    wasChanged = true;
    String superName;
    if (isInterface || superclass == null)
        superName = null;
    else
        superName = superclass.getName();

    classfile = new ClassFile(isInterface, name, superName);
    if (isInterface && superclass != null)
        classfile.setInterfaces(new String[] { superclass.getName() });

    setModifiers(Modifier.setPublic(getModifiers()));
    hasConstructor = isInterface;
}
 
Example 11
Project: JCL   File: Dump.java   View source code 6 votes vote down vote up
/**
 * Main method.
 *
 * @param args           <code>args[0]</code> is the class file name.
 */
public static void main(String[] args) throws Exception {
    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);
}
 
Example 12
Project: JCL   File: FactoryHelper.java   View source code 6 votes vote down vote up
private static void writeFile0(ClassFile cf, String directoryName)
        throws CannotCompileException, IOException {
    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();
    }
}
 
Example 13
Project: JCL   File: CtClassType.java   View source code 6 votes vote down vote up
public boolean subtypeOf(CtClass clazz) throws NotFoundException {
    int i;
    String cname = clazz.getName();
    if (this == clazz || getName().equals(cname))
        return true;

    ClassFile file = getClassFile2();
    String supername = file.getSuperclass();
    if (supername != null && supername.equals(cname))
        return true;

    String[] ifs = file.getInterfaces();
    int num = ifs.length;
    for (i = 0; i < num; ++i)
        if (ifs[i].equals(cname))
            return true;

    if (supername != null && classPool.get(supername).subtypeOf(clazz))
        return true;

    for (i = 0; i < num; ++i)
        if (classPool.get(ifs[i]).subtypeOf(clazz))
            return true;

    return false;
}
 
Example 14
Project: JCL   File: CtClassType.java   View source code 6 votes vote down vote up
public void replaceClassName(ClassMap classnames)
    throws RuntimeException
{
    String oldClassName = getName();
    String newClassName
        = (String)classnames.get(Descriptor.toJvmName(oldClassName));
    if (newClassName != null) {
        newClassName = Descriptor.toJavaName(newClassName);
        // check this in advance although classNameChanged() below does.
        classPool.checkNotFrozen(newClassName);
    }

    super.replaceClassName(classnames);
    ClassFile cf = getClassFile2();
    cf.renameClass(classnames);
    nameReplaced();

    if (newClassName != null) {
        super.setName(newClassName);
        classPool.classNameChanged(oldClassName, this);
    }
}
 
Example 15
Project: JCL   File: CtClassType.java   View source code 6 votes vote down vote up
public CtClass[] getNestedClasses() throws NotFoundException {
    ClassFile cf = getClassFile2();
    InnerClassesAttribute ica
        = (InnerClassesAttribute)cf.getAttribute(InnerClassesAttribute.tag);
    if (ica == null)
        return new CtClass[0];

    String thisName = cf.getName() + "$";
    int n = ica.tableLength();
    ArrayList<CtClass> list = new ArrayList<CtClass>(n);
    for (int i = 0; i < n; i++) {
        String name = ica.innerClass(i);
        if (name != null)
            if (name.startsWith(thisName)) {
                // if it is an immediate nested class
                if (name.lastIndexOf('$') < thisName.length())
                    list.add(classPool.get(name));
            }
    }

    return (CtClass[])list.toArray(new CtClass[list.size()]);
}
 
Example 16
Project: JCL   File: CtClassType.java   View source code 6 votes vote down vote up
public CtClass getDeclaringClass() throws NotFoundException {
    ClassFile cf = getClassFile2();
    InnerClassesAttribute ica = (InnerClassesAttribute)cf.getAttribute(
                                            InnerClassesAttribute.tag);
    if (ica == null)
        return null;

    String name = getName();
    int n = ica.tableLength();
    for (int i = 0; i < n; ++i)
        if (name.equals(ica.innerClass(i))) {
            String outName = ica.outerClass(i);
            if (outName != null)
                return classPool.get(outName);
            else {
                // maybe anonymous or local class.
                EnclosingMethodAttribute ema
                    = (EnclosingMethodAttribute)cf.getAttribute(
                                                EnclosingMethodAttribute.tag);
                if (ema != null)
                    return classPool.get(ema.className());
            }
        }

    return null;
}
 
Example 17
Project: JCL   File: CtClassType.java   View source code 6 votes vote down vote up
private void modifyClassConstructor(ClassFile cf)
    throws CannotCompileException, NotFoundException
{
    if (fieldInitializers == null)
        return;

    Bytecode code = new Bytecode(cf.getConstPool(), 0, 0);
    Javac jv = new Javac(code, this);
    int stacksize = 0;
    boolean doInit = false;
    for (FieldInitLink fi = fieldInitializers; fi != null; fi = fi.next) {
        CtField f = fi.field;
        if (Modifier.isStatic(f.getModifiers())) {
            doInit = true;
            int s = fi.init.compileIfStatic(f.getType(), f.getName(),
                                            code, jv);
            if (stacksize < s)
                stacksize = s;
        }
    }

    if (doInit)    // need an initializer for static fileds.
        modifyClassConstructor(cf, code, stacksize, 0);
}
 
Example 18
Project: drill   File: ClassPathScanner.java   View source code 6 votes vote down vote up
@Override
public void scan(final Object cls) {
  final ClassFile classFile = (ClassFile)cls;
  AnnotationsAttribute annotations = ((AnnotationsAttribute)classFile.getAttribute(AnnotationsAttribute.visibleTag));
  if (annotations != null) {
    boolean isAnnotated = false;
    for (javassist.bytecode.annotation.Annotation a : annotations.getAnnotations()) {
      if (annotationsToScan.contains(a.getTypeName())) {
        isAnnotated = true;
      }
    }
    if (isAnnotated) {
      List<AnnotationDescriptor> classAnnotations = getAnnotationDescriptors(annotations);
      @SuppressWarnings("unchecked")
      List<FieldInfo> classFields = classFile.getFields();
      List<FieldDescriptor> fieldDescriptors = new ArrayList<>(classFields.size());
      for (FieldInfo field : classFields) {
        String fieldName = field.getName();
        AnnotationsAttribute fieldAnnotations = ((AnnotationsAttribute)field.getAttribute(AnnotationsAttribute.visibleTag));
        fieldDescriptors.add(new FieldDescriptor(fieldName, field.getDescriptor(), getAnnotationDescriptors(fieldAnnotations)));
      }
      functions.add(new AnnotatedClassDescriptor(classFile.getName(), classAnnotations, fieldDescriptors));
    }
  }
}
 
Example 19
Project: cacheonix-core   File: BulkAccessorFactory.java   View source code 6 votes vote down vote up
BulkAccessor create() {
	Method[] getters = new Method[getterNames.length];
	Method[] setters = new Method[setterNames.length];
	findAccessors( targetBean, getterNames, setterNames, types, getters, setters );

	Class beanClass;
	try {
		ClassFile classfile = make( getters, setters );
		ClassLoader loader = this.getClassLoader();
		if ( writeDirectory != null ) {
			FactoryHelper.writeFile( classfile, writeDirectory );
		}

		beanClass = FactoryHelper.toClass( classfile, loader, getDomain() );
		return ( BulkAccessor ) this.newInstance( beanClass );
	}
	catch ( Exception e ) {
		throw new BulkAccessorException( e.getMessage(), e );
	}
}
 
Example 20
Project: cacheonix-core   File: BulkAccessorFactory.java   View source code 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 21
Project: cacheonix-core   File: FieldTransformer.java   View source code 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 22
Project: cacheonix-core   File: FieldTransformer.java   View source code 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 23
Project: cacheonix-core   File: FieldTransformer.java   View source code 6 votes vote down vote up
private void addReadWriteMethods(ClassFile classfile)
		throws CannotCompileException {
	List fields = classfile.getFields();
	for (Iterator field_iter = fields.iterator(); field_iter.hasNext();) {
		FieldInfo finfo = (FieldInfo) field_iter.next();
		if ((finfo.getAccessFlags() & AccessFlag.STATIC) == 0
		    && (!finfo.getName().equals(HANDLER_FIELD_NAME))) {
			// case of non-static field
			if (filter.handleRead(finfo.getDescriptor(), finfo
					.getName())) {
				addReadMethod(classfile, finfo);
				readableFields.put(finfo.getName(), finfo
						.getDescriptor());
			}
			if (filter.handleWrite(finfo.getDescriptor(), finfo
					.getName())) {
				addWriteMethod(classfile, finfo);
				writableFields.put(finfo.getName(), finfo
						.getDescriptor());
			}
		}
	}
}
 
Example 24
Project: cacheonix-core   File: FieldTransformer.java   View source code 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 25
Project: cacheonix-core   File: FieldTransformer.java   View source code 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 26
Project: powermock   File: MainMockTransformer.java   View source code 6 votes vote down vote up
private void removeFinalModifierFromClass(final CtClass clazz) {
    if (strategy != INST_REDEFINE) {
        if (Modifier.isFinal(clazz.getModifiers())) {
            clazz.setModifiers(clazz.getModifiers() ^ Modifier.FINAL);
        }

        ClassFile classFile = clazz.getClassFile2();
        AttributeInfo attribute = classFile.getAttribute(InnerClassesAttribute.tag);
        if (attribute != null && attribute instanceof InnerClassesAttribute) {
            InnerClassesAttribute ica = (InnerClassesAttribute) attribute;
            String name = classFile.getName();
            int n = ica.tableLength();
            for (int i = 0; i < n; ++i) {
                if (name.equals(ica.innerClass(i))) {
                    int accessFlags = ica.accessFlags(i);
                    if (Modifier.isFinal(accessFlags)) {
                        ica.setAccessFlags(i, accessFlags ^ Modifier.FINAL);
                    }
                }
            }
        }
    }
}
 
Example 27
Project: anno4j   File: CheckForBehaviour.java   View source code 6 votes vote down vote up
public String getClassName(String name, InputStream stream) throws IOException {
	// NOTE package-info.class should be excluded
	if (!name.endsWith(".class") || name.contains("-"))
		return null;
	DataInputStream dstream = new DataInputStream(stream);
	try {
		ClassFile cf = new ClassFile(dstream);
		if (!cf.isInterface() && !isAnnotationPresent(cf)) {
			// behaviour that implements a concept
			for (String fname : cf.getInterfaces()) {
				String cn = fname.replace('.', '/') + ".class";
				InputStream in = cl.getResource(cn).openStream();
				try {
					if (super.getClassName(cn, in) != null)
						return cf.getName();
				} finally {
					in.close();
				}
			}
		}
	} finally {
		dstream.close();
		stream.close();
	}
	return null;
}
 
Example 28
Project: playorm   File: Discoverer.java   View source code 6 votes vote down vote up
/**
   * Discovers Class Annotations
   * 
   * @param classFile
   */
  private void discoverAndIntimateForClassAnnotations (ClassFile classFile) {
  	Set<Annotation> annotations = new HashSet<Annotation>();
  	
AnnotationsAttribute visible 	= (AnnotationsAttribute) classFile.getAttribute(AnnotationsAttribute.visibleTag);
AnnotationsAttribute invisible 	= (AnnotationsAttribute) classFile.getAttribute(AnnotationsAttribute.invisibleTag);

if (visible != null) {
	annotations.addAll(Arrays.asList(visible.getAnnotations()));
}
if (invisible != null) {
	annotations.addAll(Arrays.asList(invisible.getAnnotations()));
}

// now tell listeners
for (Annotation annotation : annotations) {
	Set<ClassAnnotationDiscoveryListener> listeners = classAnnotationListeners.get(annotation.getTypeName());
	if (null == listeners) {
		continue;
	}

	for (ClassAnnotationDiscoveryListener listener : listeners) {
		listener.discovered(classFile.getName(), annotation.getTypeName());
	}
}
  }
 
Example 29
Project: JMXMPAgent   File: FibonnoitreClassFileTransformer.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 * @see java.lang.instrument.ClassFileTransformer#transform(java.lang.ClassLoader, java.lang.String, java.lang.Class, java.security.ProtectionDomain, byte[])
 */
@Override
public byte[] transform(final ClassLoader classLoader, final String className, final Class<?> clazz, final ProtectionDomain protectionDomain, final byte[] byteCode) throws IllegalClassFormatException {
	final LoaderClassPath lcp = new LoaderClassPath(classLoader);
	try {
		final CtClass cc = classPool.get(bin(className));
		final ClassFile ccFile = cc.getClassFile();
		final ConstPool constpool = ccFile.getConstPool();			
		for(CtMethod ctm: cc.getMethods()) {
			if(ctm.getAnnotation(fibAnn)==null) continue;
			instrumentMethod(ctm, constpool);
		}
	} catch (Exception ex) {
		return null;
	} finally {
		classPool.removeClassPath(lcp);
	}
	
	return null;
}
 
Example 30
Project: ceylon-jboss-loader   File: CarScanner.java   View source code 6 votes vote down vote up
/**
 * Scans a class representation for annotations.
 * @param cf The ClassFile
 * @return A lit of annotations
 */
private List<Annotation> scanClass(final ClassFile cf) {

   AnnotationsAttribute visible = (AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.visibleTag);
   AnnotationsAttribute invisible = (AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.invisibleTag);
   
   ArrayList<Annotation> list = new ArrayList<Annotation>();

   if (visible != null) {
       list.addAll(Arrays.asList(visible.getAnnotations()));
   }
   
   if (invisible != null) {
       list.addAll(Arrays.asList(invisible.getAnnotations()));
   }
   
   return list;
}
 
Example 31
Project: mimic   File: MimicProcessorTest.java   View source code 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 32
Project: spassMeter   File: CodeModifier.java   View source code 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 33
Project: spassMeter   File: CodeModifier.java   View source code 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 34
Project: rapidoid   File: ClasspathScanner.java   View source code 6 votes vote down vote up
private static boolean isAnnotated(ClassFile cfile, Class<? extends Annotation>[] annotated) throws IOException {
	List attributes = U.safe(cfile.getAttributes());

	for (Object attribute : attributes) {
		if (attribute instanceof AnnotationsAttribute) {
			AnnotationsAttribute annotations = (AnnotationsAttribute) attribute;

			for (Class<? extends Annotation> ann : annotated) {
				if (annotations.getAnnotation(ann.getName()) != null) {
					return true;
				}
			}
		}
	}

	return false;
}
 
Example 35
Project: EndHQ-Libraries   File: CtNewNestedClass.java   View source code 6 votes vote down vote up
private static void updateInnerEntry(int mod, String name, CtClass clazz, boolean outer) {
    ClassFile cf = clazz.getClassFile2();
    InnerClassesAttribute ica = (InnerClassesAttribute)cf.getAttribute(
                                            InnerClassesAttribute.tag);
    if (ica == null)
        return;

    int n = ica.tableLength();
    for (int i = 0; i < n; i++)
        if (name.equals(ica.innerClass(i))) {
            int acc = ica.accessFlags(i) & AccessFlag.STATIC;
            ica.setAccessFlags(i, mod | acc);
            String outName = ica.outerClass(i);
            if (outName != null && outer)
                try {
                    CtClass parent = clazz.getClassPool().get(outName);
                    updateInnerEntry(mod, name, parent, false);
                }
                catch (NotFoundException e) {
                    throw new RuntimeException("cannot find the declaring class: "
                                               + outName);
                }

            break;
        }
}
 
Example 36
Project: EndHQ-Libraries   File: CtClass.java   View source code 6 votes vote down vote up
/**
 * Returns a collection of the names of all the classes
 * referenced in this class.
 * That collection includes the name of this class.
 *
 * <p>This method may return <code>null</code>.
 *
 * @return a <code>Collection&lt;String&gt;</code> object.
 */
public synchronized Collection getRefClasses() {
    ClassFile cf = getClassFile2();
    if (cf != null) {
        ClassMap cm = new ClassMap() {
            public void put(String oldname, String newname) {
                put0(oldname, newname);
            }

            public Object get(Object jvmClassName) {
                String n = toJavaName((String)jvmClassName);
                put0(n, n);
                return null;
            }

            public void fix(String name) {}
        };
        cf.getRefClasses(cm);
        return cm.values();
    }
    else
        return null;
}
 
Example 37
Project: EndHQ-Libraries   File: CtNewClass.java   View source code 6 votes vote down vote up
CtNewClass(String name, ClassPool cp,
           boolean isInterface, CtClass superclass) {
    super(name, cp);
    wasChanged = true;
    String superName;
    if (isInterface || superclass == null)
        superName = null;
    else
        superName = superclass.getName();

    classfile = new ClassFile(isInterface, name, superName);
    if (isInterface && superclass != null)
        classfile.setInterfaces(new String[] { superclass.getName() });

    setModifiers(Modifier.setPublic(getModifiers()));
    hasConstructor = isInterface;
}
 
Example 38
Project: EndHQ-Libraries   File: Dump.java   View source code 6 votes vote down vote up
/**
 * Main method.
 *
 * @param args           <code>args[0]</code> is the class file name.
 */
public static void main(String[] args) throws Exception {
    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);
}
 
Example 39
Project: EndHQ-Libraries   File: FactoryHelper.java   View source code 6 votes vote down vote up
private static void writeFile0(ClassFile cf, String directoryName)
        throws CannotCompileException, IOException {
    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();
    }
}
 
Example 40
Project: EndHQ-Libraries   File: CtClassType.java   View source code 6 votes vote down vote up
public boolean subtypeOf(CtClass clazz) throws NotFoundException {
    int i;
    String cname = clazz.getName();
    if (this == clazz || getName().equals(cname))
        return true;

    ClassFile file = getClassFile2();
    String supername = file.getSuperclass();
    if (supername != null && supername.equals(cname))
        return true;

    String[] ifs = file.getInterfaces();
    int num = ifs.length;
    for (i = 0; i < num; ++i)
        if (ifs[i].equals(cname))
            return true;

    if (supername != null && classPool.get(supername).subtypeOf(clazz))
        return true;

    for (i = 0; i < num; ++i)
        if (classPool.get(ifs[i]).subtypeOf(clazz))
            return true;

    return false;
}