Package org.apache.bcel.generic

Examples of org.apache.bcel.generic.ClassGen


     *
     * @param context the transformation context
     * @param klass the class
     */
    public void transformInterface(final Context context, final Klass klass) {
        final ClassGen cg = klass.getClassGen();
            final ConstantPoolGen cpg = cg.getConstantPool();
            final InstructionFactory factory = new InstructionFactory(cg);

            if (classFilter(cg)) {
                return;
            }
            if (m_hasBeenTransformed.contains(cg.getClassName())) {
                return;
            }

            // mark the class as transformed
            m_hasBeenTransformed.add(cg.getClassName());

            addReadObjectMethod(cg, cpg, factory);
    }
View Full Code Here


        try {
            log(klass);

            // build the ClassGen
            ClassParser parser = new ClassParser(new ByteArrayInputStream(abyte), "<generated>");//@todo is this needed _"+klass+">");
            ClassGen cg = new ClassGen(parser.parse());

            // instrument
            if ( ! cg.isInterface() && ! Arrays.asList(cg.getInterfaceNames()).contains("java.util.EventListener") )
                cg.addInterface("java.util.EventListener");

            try {
                cg.getJavaClass().dump("_dump/"+klass.replace('.', '/')+".class");
            } catch (Exception e) {
                System.err.println("failed to dump " + klass);
                e.printStackTrace();
            }


            return cg.getJavaClass().getBytes();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
View Full Code Here

     *
     * @param context the transformation context
     * @param klass the class
     */
    public void transformInterface(final Context context, final Klass klass) {
        final ClassGen cg = klass.getClassGen();
        if (classFilter(cg)) {
            return;
        }
        if (m_transformed.contains(cg.getClassName())) {
            return;
        }
        m_transformed.add(cg.getClassName());

        final ConstantPoolGen cpg = cg.getConstantPool();
        final InstructionFactory factory = new InstructionFactory(cg);
        addIntroductions(context, cg, cpg, factory);
    }
View Full Code Here

     *
     * @param context the transformation context
     * @param klass the unextendable class set
     */
    public void transformInterface(final Context context, final Klass klass) {
        final ClassGen cg = klass.getClassGen();
        if (classFilter(cg)) {
            return;
        }
        if (!TransformationUtil.isSerializable(context, cg)) {
            return;
View Full Code Here

     *
     * @param context the transformation context
     * @param klass the class set.
     */
    public void transformCode(final Context context, final Klass klass) {
        final ClassGen cg = klass.getClassGen();
        ClassMetaData classMetaData = BcelMetaDataMaker.
                createClassMetaData(context.getJavaClass(cg));

        if (classFilter(classMetaData, cg)) {
            return;
        }

        final Method[] methods = cg.getMethods();

        // get the indexes for the <init> methods
        List initIndexes = new ArrayList();
        for (int i = 0; i < methods.length; i++) {
            if (methods[i].getName().equals("<init>")) {
                initIndexes.add(new Integer(i));
            }
        }

        final ConstantPoolGen cpg = cg.getConstantPool();
        final String className = cg.getClassName();
        final InstructionFactory factory = new InstructionFactory(cg);

        final Set setFieldJoinPoints = new HashSet();
        final Set getFieldJoinPoints = new HashSet();

        boolean isClassAdvised = false;
        for (int i = 0; i < methods.length; i++) {

            // filter methods
            if (methodFilter(methods[i])) {
                continue;
            }

            MethodGen mg = new MethodGen(methods[i], className, cpg);

            // do not modify anything within the hidden system methods
            if (mg.getMethod().getName().startsWith(TransformationUtil.ASPECTWERKZ_PREFIX)) {
                continue;
            }

            InstructionList il = mg.getInstructionList();
            InstructionHandle ih = il.getStart();

            // get the current field instruction
            FieldInstruction currentGetFieldIns = null;

            // search for all GETFIELD and GETSTATIC instructions and
            // inserts the pre and post advices
            while (ih != null) {
                Instruction ins = ih.getInstruction();

                // handle the java.util.Collection classes
                if (ins instanceof GETFIELD || ins instanceof GETSTATIC) {
                    FieldInstruction checkMe = (FieldInstruction)ins;
                    // if the field is an added join point field => skip it
                    // needed if a field of type collection is both setField
                    // and getField advised
                    if (!checkMe.getFieldName(cpg).startsWith(TransformationUtil.JOIN_POINT_PREFIX)) {
                        currentGetFieldIns = checkMe;
                    }
                }
                if (ins instanceof INVOKEINTERFACE) {
                    final InvokeInstruction invokeIns = (InvokeInstruction)ins;

                    // do we have a collection?
                    if (invokeIns.getClassName(cpg).equals("java.util.Collection") ||
                            invokeIns.getClassName(cpg).equals("java.util.Enumeration") ||
                            invokeIns.getClassName(cpg).equals("java.util.Iterator") ||
                            invokeIns.getClassName(cpg).equals("java.util.List") ||
                            invokeIns.getClassName(cpg).equals("java.util.Map") ||
                            invokeIns.getClassName(cpg).equals("java.util.Set") ||
                            invokeIns.getClassName(cpg).equals("java.util.SortedMap") ||
                            invokeIns.getClassName(cpg).equals("java.util.SortedSet")) {

                        String methodName = invokeIns.getName(cpg);

                        // is the collection modified?
                        if (methodName.equals("add") ||
                                methodName.equals("addAll") ||
                                methodName.equals("set") ||
                                methodName.equals("remove") ||
                                methodName.equals("removeAll") ||
                                methodName.equals("retainAll") ||
                                methodName.equals("clear") ||
                                methodName.equals("put") ||
                                methodName.equals("putAll")) {

                            if (currentGetFieldIns == null) {
                                // is not a member field, continue
                                ih = ih.getNext();
                                continue;
                            }

                            final String fieldName = currentGetFieldIns.getName(cpg);
                            final String signature = currentGetFieldIns.getFieldType(cpg).
                                    toString() + " " + fieldName;
                            final Type joinPointType = TransformationUtil.MEMBER_FIELD_SET_JOIN_POINT_TYPE;

                            FieldMetaData fieldMetaData =
                                    BcelMetaDataMaker.createFieldMetaData(currentGetFieldIns, cpg);

                            String uuid = setFieldFilter(classMetaData, fieldMetaData);

                            if (uuid != null) {
                                final String fieldClassName = currentGetFieldIns.getClassName(cpg);

                                if (fieldClassName.equals(cg.getClassName())) {

                                    // is NOT in static context
                                    if (!mg.isStatic()) {
                                        isClassAdvised = true;

                                        insertPreAdvice(
                                                il, ih, cg, fieldName,
                                                factory, joinPointType);

                                        insertPostAdvice(
                                                il, ih.getNext(), cg,
                                                fieldName, factory, joinPointType);

                                        // store the join point field data
                                        JoinPointFieldData data = new JoinPointFieldData(
                                                fieldName, signature, joinPointType, uuid);

                                        if (!setFieldJoinPoints.contains(data)) {
                                            setFieldJoinPoints.add(data);
                                        }
                                    }
                                }
                                // set the current get field instruction to null
                                currentGetFieldIns = null;
                            }
                        }
                    }
                }
                // handle the getField instructions
                else if (ins instanceof GETFIELD || ins instanceof GETSTATIC) {
                    final FieldInstruction gfIns = (FieldInstruction)ins;

                    String fieldName = gfIns.getName(cpg);
                    String signature = gfIns.getFieldType(cpg).toString() + " " + fieldName;
                    Type joinPointType = TransformationUtil.MEMBER_FIELD_GET_JOIN_POINT_TYPE;

                    FieldMetaData fieldMetaData = BcelMetaDataMaker.createFieldMetaData(gfIns, cpg);

                    String uuid = getFieldFilter(classMetaData, fieldMetaData);
                    if (uuid != null) {

                        final String fieldClassName = gfIns.getClassName(cpg);
                        if (fieldClassName.equals(cg.getClassName())) {

                            // is NOT in static context
                            if (!mg.isStatic()) {
                                isClassAdvised = true;

                                insertPreAdvice(
                                        il, ih, cg, fieldName,
                                        factory, joinPointType);

                                insertPostAdvice(
                                        il, ih.getNext(), cg,
                                        fieldName, factory, joinPointType);

                                // store the join point field data
                                JoinPointFieldData data = new JoinPointFieldData(
                                        fieldName, signature, joinPointType, uuid);

                                if (!getFieldJoinPoints.contains(data)) {
                                    getFieldJoinPoints.add(data);
                                }
                            }
                        }
                    }
                }
                // handle the setField instructions
                else if (ins instanceof PUTFIELD || ins instanceof PUTSTATIC) {
                    final FieldInstruction pfIns = (FieldInstruction)ins;

                    String fieldName = pfIns.getName(cpg);
                    String signature = pfIns.getFieldType(cpg).toString() + " " + fieldName;
                    Type joinPointType = TransformationUtil.MEMBER_FIELD_SET_JOIN_POINT_TYPE;

                    FieldMetaData fieldMetaData =
                            BcelMetaDataMaker.createFieldMetaData(pfIns, cpg);

                    String uuid = setFieldFilter(classMetaData, fieldMetaData);
                    if (uuid != null) {

                        final String fieldClassName = pfIns.getClassName(cpg);
                        if (fieldClassName.equals(cg.getClassName())) {

                            // is NOT in static context
                            if (!mg.isStatic()) {
                                isClassAdvised = true;

                                insertPreAdvice(
                                        il, ih, cg, fieldName,
                                        factory, joinPointType);

                                insertPostAdvice(
                                        il, ih.getNext(), cg,
                                        fieldName, factory, joinPointType);

                                // store the join point field data
                                JoinPointFieldData data = new JoinPointFieldData(
                                        fieldName, signature, joinPointType, uuid);

                                if (!setFieldJoinPoints.contains(data)) {
                                    setFieldJoinPoints.add(data);
                                }
                            }
                        }
                    }
                }
                ih = ih.getNext();
            }

            if (isClassAdvised) {
                mg.setMaxStack();
                methods[i] = mg.getMethod();
            }
        }

        // create the set field join point member fields
        for (Iterator it = setFieldJoinPoints.iterator(); it.hasNext();) {
            JoinPointFieldData data = (JoinPointFieldData)it.next();
            addJoinPointMemberField(cpg, cg, data.getName(), data.getType());

            // advise all the constructors
            for (Iterator it2 = initIndexes.iterator(); it2.hasNext();) {
                final int initIndex = ((Integer)it2.next()).intValue();

                methods[initIndex] = createJoinPointMemberField(
                        cpg, cg, methods[initIndex], factory,
                        data.getName(), data.getSignature(),
                        data.getType(), data.getUuid());

            }
        }
        // create the get field join point member fields
        for (Iterator it = getFieldJoinPoints.iterator(); it.hasNext();) {
            JoinPointFieldData data = (JoinPointFieldData)it.next();
            addJoinPointMemberField(cpg, cg, data.getName(), data.getType());

            // advise all the constructors
            for (Iterator it2 = initIndexes.iterator(); it2.hasNext();) {
                final int initIndex = ((Integer)it2.next()).intValue();

                methods[initIndex] = createJoinPointMemberField(
                        cpg, cg, methods[initIndex], factory,
                        data.getName(), data.getSignature(),
                        data.getType(), data.getUuid());

            }
        }

        cg.setMethods(methods);
    }
View Full Code Here

     * @param context the transformation context
     * @param klass the class set.
     */
    public void transformCode(final Context context, final Klass klass) {

        final ClassGen cg = klass.getClassGen();
        ClassMetaData classMetaData = BcelMetaDataMaker.
                createClassMetaData(context.getJavaClass(cg));

        // filter caller classes
        if (classFilter(classMetaData, cg)) {
            return;
        }

        final Method[] methods = cg.getMethods();

        // get the index for the <clinit> method (if there is one)
        boolean hasClInitMethod = false;
        int clinitIndex = -1;
        for (int i = 0; i < methods.length; i++) {
            if (methods[i].getName().equals("<clinit>")) {
                clinitIndex = i;
                hasClInitMethod = true;
                break;
            }
        }
        final ConstantPoolGen cpg = cg.getConstantPool();
        final String className = cg.getClassName();
        final InstructionFactory factory = new InstructionFactory(cg);

        final Set callerSideJoinPoints = new HashSet();

        Method clInitMethod = null;
        final Map methodSequences = new HashMap();
        final List newMethods = new ArrayList();
        boolean isClassAdvised = false;
        boolean isMethodChanged = false;

        for (int i = 0; i < methods.length; i++) {

            // filter caller methods
            if (methodFilterCaller(methods[i])) {
                continue;
            }

            final MethodGen mg = new MethodGen(methods[i], className, cpg);

            final InstructionList il = mg.getInstructionList();
            if (il == null) {
                continue;
            }
            InstructionHandle ih = il.getStart();
            isMethodChanged = false;
            // search for all InvokeInstruction instructions and
            // inserts the call side pointcuts
            while (ih != null) {
                final Instruction ins = ih.getInstruction();

                if (ins instanceof INVOKESPECIAL ||
                        ins instanceof INVOKESTATIC ||
                        ins instanceof INVOKEVIRTUAL) {

                    final InvokeInstruction invokeInstruction = (InvokeInstruction)ins;

                    // get the callee method name, signature and class name
                    final String calleeMethodName = invokeInstruction.getName(cpg);
                    final String calleeClassName = invokeInstruction.getClassName(cpg);
                    final String calleeMethodSignature = invokeInstruction.getSignature(cpg);

                    // filter callee classes
                    if (!m_definition.inTransformationScope(calleeClassName)) {
                        ih = ih.getNext();
                        continue;
                    }
                    // filter callee methods
                    if (methodFilterCallee(calleeMethodName)) {
                        ih = ih.getNext();
                        continue;
                    }

                    // create the class meta-data
                    ClassMetaData calleeSideClassMetaData;
                    try {
                        JavaClass javaClass = context.getRepository().loadClass(calleeClassName);
                        calleeSideClassMetaData = BcelMetaDataMaker.createClassMetaData(javaClass);
                    }
                    catch (ClassNotFoundException e) {
                        throw new WrappedRuntimeException(e);
                    }

                    // create the method meta-data
                    MethodMetaData calleeSideMethodMetaData =
                            BcelMetaDataMaker.createMethodMetaData(invokeInstruction, cpg);

                    // is this a caller side method pointcut?
                    if (m_definition.isCallerSideMethod(
                            calleeSideClassMetaData,
                            calleeSideMethodMetaData)) {

                        // get the caller method name and signature
                        Method method = mg.getMethod();
                        String callerMethodName = method.getName();
                        String callerMethodSignature = method.getSignature();

                        final Type joinPointType = TransformationUtil.CALLER_SIDE_JOIN_POINT_TYPE;

                        // take care of identification of overloaded methods
                        // by inserting a sequence number
                        if (methodSequences.containsKey(calleeMethodName)) {
                            int sequence = ((Integer)methodSequences.
                                    get(calleeMethodName)).intValue();

                            methodSequences.remove(calleeMethodName);
                            sequence++;
                            methodSequences.put(calleeMethodName, new Integer(sequence));
                        }
                        else {
                            methodSequences.put(calleeMethodName, new Integer(1));
                        }
                        final int methodSequence =
                                ((Integer)methodSequences.get(calleeMethodName)).intValue();

                        isClassAdvised = true;
                        isMethodChanged = true;

                        insertPreAdvice(
                                il, ih, cg,
                                calleeMethodName,
                                methodSequence,
                                factory,
                                joinPointType
                        );

                        insertPostAdvice(
                                il, ih.getNext(), cg,
                                calleeMethodName,
                                methodSequence,
                                factory,
                                joinPointType
                        );

                        StringBuffer key = new StringBuffer();
                        key.append(className);
                        key.append(TransformationUtil.DELIMITER);
                        key.append(calleeMethodName);
                        key.append(TransformationUtil.DELIMITER);
                        key.append(methodSequence);

                        // skip the creation of the join point if we already have one
                        if (!callerSideJoinPoints.contains(key.toString())) {
                            callerSideJoinPoints.add(key.toString());

                            addStaticJoinPointField(
                                    cpg, cg, calleeMethodName,
                                    methodSequence, joinPointType
                            );

                            if (hasClInitMethod) {
                                methods[clinitIndex] = createStaticJoinPointField(
                                        cpg, cg,
                                        methods[clinitIndex],
                                        callerMethodName,
                                        calleeClassName,
                                        calleeMethodName,
                                        methodSequence,
                                        callerMethodSignature,
                                        calleeMethodSignature,
                                        factory,
                                        joinPointType,
                                        m_definition.getUuid()
                                );
                            }
                            else if (clInitMethod == null) {
                                clInitMethod = createClInitMethodWithStaticJoinPointField(
                                        cpg, cg,
                                        callerMethodName,
                                        calleeClassName,
                                        calleeMethodName,
                                        methodSequence,
                                        callerMethodSignature,
                                        calleeMethodSignature,
                                        factory,
                                        joinPointType,
                                        m_definition.getUuid()
                                );
                            }
                            else {
                                clInitMethod = createStaticJoinPointField(
                                        cpg, cg,
                                        clInitMethod,
                                        callerMethodName,
                                        calleeClassName,
                                        calleeMethodName,
                                        methodSequence,
                                        callerMethodSignature,
                                        calleeMethodSignature,
                                        factory,
                                        joinPointType,
                                        m_definition.getUuid()
                                );
                            }
                        }
                    }
                }
                ih = ih.getNext();
            }

            if (isMethodChanged) {
                mg.setMaxStack();
                methods[i] = mg.getMethod();
            }
        }

        if (isClassAdvised) {
            // if we have transformed methods, create the static class field
            if (!hasClInitMethod && clInitMethod != null) {
                addStaticClassField(cpg, cg);
                clInitMethod = createStaticClassField(
                        cpg, cg,
                        clInitMethod,
                        factory
                );

                newMethods.add(clInitMethod);
            }
            else {
                addStaticClassField(cpg, cg);
                methods[clinitIndex] = createStaticClassField(
                        cpg, cg,
                        methods[clinitIndex],
                        factory
                );
            }
        }
        // update the old methods
        cg.setMethods(methods);

        // add the new methods
        for (Iterator it = newMethods.iterator(); it.hasNext();) {
            Method method = (Method)it.next();
            cg.addMethod(method);
        }
    }
View Full Code Here

/* 137 */       else if (!this.superclass.isAssignableFrom(targetType)) {
/* 138 */         throw new RuntimeException("unexpected: " + targetType);
/*     */       }
/*     */     }
/*     */
/* 142 */     ClassGen cg = new ClassGen(proxyClassName, superClassName, "<generated>", 17, interfaceNames);
/*     */
/* 148 */     ProxyImplementationFactory factory = new ProxyImplementationFactory(superClassName, proxyClassName, cg);
/*     */
/* 151 */     cg.addField(factory.createInvocationHandlerField());
/* 152 */     cg.addField(factory.createRuntimeField());
/* 153 */     cg.addMethod(factory.createConstructor());
/*     */
/* 157 */     cg.addMethod(factory.createGetInvocationHandler());
/* 158 */     cg.addMethod(factory.createGetTargetTypes());
/*     */
/* 160 */     boolean haveToString = false;
/*     */
/* 162 */     if (trace) log.trace("Creating proxy methods...");
/*     */
/* 165 */     for (int i = 0; i < this.methods.length; i++)
/*     */     {
/* 167 */       java.lang.reflect.Method m = this.methods[i];
/* 168 */       if (trace) log.trace("Reflected method: " + m);
/*     */
/* 170 */       String name = m.getName();
/* 171 */       Class rTypeClass = m.getReturnType();
/* 172 */       String rTypeName = rTypeClass.getName();
/* 173 */       Type rType = Utility.getType(rTypeClass);
/* 174 */       Type[] pTypes = Utility.getTypes(m.getParameterTypes());
/* 175 */       String[] exceptionNames = getNames(m.getExceptionTypes());
/*     */
/* 177 */       if ((name.equals("toString")) && (pTypes.length == 0)) {
/* 178 */         haveToString = true;
/*     */       }
/*     */
/* 181 */       org.apache.bcel.classfile.Method proxyMethod = factory.createProxyMethod(name, i, rType, pTypes, exceptionNames);
/*     */
/* 184 */       if (trace) log.trace("Created proxy method: " + proxyMethod);
/*     */
/* 186 */       cg.addMethod(proxyMethod);
/*     */     }
/*     */
/* 189 */     if (!haveToString) {
/* 190 */       cg.addMethod(factory.createToString());
/*     */     }
/*     */
/* 193 */     JavaClass jclass = cg.getJavaClass();
/* 194 */     if (trace) log.trace("Generated Java class: " + jclass);
/*     */
/* 197 */     if (CLASS_DUMP_PATH != null) {
/*     */       try {
/* 199 */         String filename = CLASS_DUMP_PATH + File.separator + proxyClassName + ".class";
View Full Code Here

/*  72 */       String superClass = SUPER_CLASS.getName();
/*  73 */       String fileName = className + ".class";
/*  74 */       int modifiers = 1;
/*  75 */       String[] interfaces = new String[0];
/*     */
/*  77 */       ClassGen clazz = new ClassGen(className, superClass, fileName, modifiers, interfaces);
/*  78 */       ConstantPoolGen cp = clazz.getConstantPool();
/*     */
/*  80 */       clazz.addMethod(createConstructor(cp, className).getMethod());
/*  81 */       clazz.addMethod(createInvoke(cp, info, className, resource.getClass().getName()).getMethod());
/*  82 */       clazz.update();
/*     */
/*  84 */       JavaClass c = clazz.getJavaClass();
/*     */
/*  86 */       ByteArrayOutputStream baos = new ByteArrayOutputStream(2000);
/*  87 */       BufferedOutputStream bos = new BufferedOutputStream(baos);
/*  88 */       c.dump(bos);
/*     */
View Full Code Here

    String peerName = PeerClassGen.getNativePeerClsName(className);
    this.path = PeerClassGen.peersLocation + peerName + ".class";

    try{
      this.peer = this.loadClass(peerName);
      _cg = new ClassGen(Repository.lookupClass(this.loadClass(peerName)));
    } catch (ClassNotFoundException e){
      // do nothing!
    }

    if (this.peer == null){
      _cg = new ClassGen(peerName, "gov.nasa.jpf.vm.NativePeer", peerName + ".class", Constants.ACC_PUBLIC, new String[] {});
      _cg.addEmptyConstructor(Constants.ACC_PUBLIC);
    }

    _cp = _cg.getConstantPool();
    _factory = new InstructionFactory(_cg, _cp);
View Full Code Here

        Class generatedClass;
        synchronized ( Type.class )
        {
            // Create BCEL class generator
            m_classGenerator =
                new ClassGen(
                    wrapperClassName,
                    WRAPPER_SUPERCLASS_NAME,
                    null,
                    Constants.ACC_FINAL
                |Constants.ACC_PUBLIC
View Full Code Here

TOP

Related Classes of org.apache.bcel.generic.ClassGen

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.