Example usage for org.objectweb.asm Opcodes ACC_PUBLIC

List of usage examples for org.objectweb.asm Opcodes ACC_PUBLIC

Introduction

In this page you can find the example usage for org.objectweb.asm Opcodes ACC_PUBLIC.

Prototype

int ACC_PUBLIC

To view the source code for org.objectweb.asm Opcodes ACC_PUBLIC.

Click Source Link

Usage

From source file:net.sourceforge.cobertura.instrument.pass3.TestUnitCodeProvider.java

License:GNU General Public License

/**
 * Generates://from  w  ww. j  av a  2s.c o  m
 * public static final transient Map __cobertura_counters;
 */
public void generateCountersField(ClassVisitor cv) {
    FieldVisitor fv = cv.visitField(
            Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_TRANSIENT,
            COBERTURA_COUNTERS_FIELD_NAME, COBERTURA_COUNTERS_FIELD_TYPE, null, null);
    fv.visitEnd();
}

From source file:net.sourceforge.cobertura.instrument.pass3.TestUnitCodeProvider.java

License:GNU General Public License

/**
 * Generates:/*w w w  .j  a  v  a 2 s .  co m*/
 *   public static TestUnitInformationHolder[] __cobertura_get_and_reset_counters()
 *   {
 *     TestUnitInformationHolder[] local = __cobertura_counters;
 *     __cobertura_counters = new TestUnitInformationHolder[__cobertura_counters.length];
 *     return local;
 *   }
 */
public void generateCoberturaGetAndResetCountersMethod(ClassVisitor cv, String className) {
    MethodVisitor mv = cv.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
            COBERTURA_GET_AND_RESET_COUNTERS_METHOD_NAME, "()" + COBERTURA_COUNTERS_FIELD_TYPE, null, null);
    mv.visitCode();
    /*cobertura_counters.*/
    mv.visitFieldInsn(Opcodes.GETSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME,
            COBERTURA_COUNTERS_FIELD_TYPE);
    mv.visitVarInsn(Opcodes.ASTORE, 0);
    /*cobertura_counters.*/
    mv.visitFieldInsn(Opcodes.GETSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME,
            COBERTURA_COUNTERS_FIELD_TYPE);
    mv.visitInsn(Opcodes.ARRAYLENGTH);

    mv.visitTypeInsn(Opcodes.ANEWARRAY, Type.getInternalName(TestUnitInformationHolder.class));
    mv.visitFieldInsn(Opcodes.PUTSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME,
            COBERTURA_COUNTERS_FIELD_TYPE);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitInsn(Opcodes.ARETURN);
    mv.visitMaxs(0, 0);//will be recalculated by writer
    mv.visitEnd();
}

From source file:net.sourceforge.cobertura.reporting.ComplexityCalculator.java

License:Open Source License

/**
 * Computes CCN for a method.//from   www  . ja v a  2 s .  c  o  m
 *
 * @param classData        class data for the class which contains the method to compute CCN for
 * @param methodName       the name of the method to compute CCN for
 * @param methodDescriptor the descriptor of the method to compute CCN for
 * @return CCN for the method
 * @throws NullPointerException if <code>classData</code> is <code>null</code>
 */
public int getCCNForMethod(ClassData classData, String methodName, String methodDescriptor) {
    if (!calculateMethodComplexity) {
        return 0;
    }

    Validate.notNull(classData, "classData must not be null");
    Validate.notNull(methodName, "methodName must not be null");
    Validate.notNull(methodDescriptor, "methodDescriptor must not be null");

    int complexity = 0;
    List<FunctionMetric> methodMetrics = getFunctionMetricsForSingleFile(classData.getSourceFileName());

    // golden method = method for which we need ccn
    String goldenMethodName = methodName;
    boolean isConstructor = false;
    if (goldenMethodName.equals("<init>")) {
        isConstructor = true;
        goldenMethodName = classData.getBaseName();
    }
    // fully-qualify the method
    goldenMethodName = classData.getName() + "." + goldenMethodName;
    // replace nested class separator $ by .
    goldenMethodName = goldenMethodName.replaceAll(Pattern.quote("$"), ".");

    TraceSignatureVisitor v = new TraceSignatureVisitor(Opcodes.ACC_PUBLIC);
    SignatureReader r = new SignatureReader(methodDescriptor);
    r.accept(v);

    // for the scope of this method, signature = signature of the method excluding the method name
    String goldenSignature = v.getDeclaration();
    // get parameter type list string which is enclosed by round brackets ()
    goldenSignature = goldenSignature.substring(1, goldenSignature.length() - 1);

    // collect all the signatures with the same method name as golden method
    Map<String, Integer> candidateSignatureToCcn = new HashMap<String, Integer>();
    for (FunctionMetric singleMethodMetrics : methodMetrics) {
        String candidateMethodName = singleMethodMetrics.name.substring(0,
                singleMethodMetrics.name.indexOf('('));
        String candidateSignature = stripTypeParameters(singleMethodMetrics.name
                .substring(singleMethodMetrics.name.indexOf('(') + 1, singleMethodMetrics.name.length() - 1));
        if (goldenMethodName.equals(candidateMethodName)) {
            candidateSignatureToCcn.put(candidateSignature, singleMethodMetrics.ccn);
        }
    }

    // if only one signature, no signature matching needed
    if (candidateSignatureToCcn.size() == 1) {
        return candidateSignatureToCcn.values().iterator().next();
    }

    // else, do signature matching and find the best match

    // update golden signature using reflection
    if (!goldenSignature.isEmpty()) {
        try {
            String[] goldenParameterTypeStrings = goldenSignature.split(",");
            Class<?>[] goldenParameterTypes = new Class[goldenParameterTypeStrings.length];
            for (int i = 0; i < goldenParameterTypeStrings.length; i++) {
                goldenParameterTypes[i] = ClassUtils.getClass(goldenParameterTypeStrings[i].trim(), false);
            }
            Class<?> klass = ClassUtils.getClass(classData.getName(), false);
            if (isConstructor) {
                Constructor<?> realMethod = klass.getDeclaredConstructor(goldenParameterTypes);
                goldenSignature = realMethod.toGenericString();
            } else {
                Method realMethod = klass.getDeclaredMethod(methodName, goldenParameterTypes);
                goldenSignature = realMethod.toGenericString();
            }
            // replace varargs ellipsis with array notation
            goldenSignature = goldenSignature.replaceAll("\\.\\.\\.", "[]");
            // extract the parameter type list string
            goldenSignature = goldenSignature.substring(goldenSignature.indexOf("(") + 1,
                    goldenSignature.length() - 1);
            // strip the type parameters to get raw types
            goldenSignature = stripTypeParameters(goldenSignature);
        } catch (Exception e) {
            logger.error("Error while getting method CC for " + goldenMethodName, e);
            return 0;
        }
    }
    // replace nested class separator $ by .
    goldenSignature = goldenSignature.replaceAll(Pattern.quote("$"), ".");

    // signature matching - due to loss of fully qualified parameter types from JavaCC, get ccn for the closest match
    double signatureMatchPercentTillNow = 0;
    for (Entry<String, Integer> candidateSignatureToCcnEntry : candidateSignatureToCcn.entrySet()) {
        String candidateSignature = candidateSignatureToCcnEntry.getKey();
        double currentMatchPercent = matchSignatures(candidateSignature, goldenSignature);
        if (currentMatchPercent == 1) {
            return candidateSignatureToCcnEntry.getValue();
        }
        if (currentMatchPercent > signatureMatchPercentTillNow) {
            complexity = candidateSignatureToCcnEntry.getValue();
            signatureMatchPercentTillNow = currentMatchPercent;
        }
    }

    return complexity;
}

From source file:net.yrom.tools.WriteStyleablesProcessor.java

License:Apache License

@Override
public void proceed() {
    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC | Opcodes.ACC_SUPER,
            RSymbols.R_STYLEABLES_CLASS_NAME, null, "java/lang/Object", null);
    for (String name : symbols.getStyleables().keySet()) {
        writer.visitField(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL, name, "[I", null, null);
    }//w  ww. j a va 2 s . c o m

    writeClinit(writer);
    writer.visitEnd();
    byte[] bytes = writer.toByteArray();
    try {
        if (!dir.isDirectory() && !dir.mkdirs()) {
            throw new RuntimeException("Cannot mkdir " + dir);
        }
        Files.write(dir.toPath().resolve(RSymbols.R_STYLEABLES_CLASS_NAME + ".class"), bytes);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:org.actorsguildframework.internal.codegenerator.ActorProxyCreator.java

License:Apache License

/**
 * Create or get a MessageCaller implementation for the given method.
 * @param ownerClass the class that owns the message
 * @param method the method to invoke/*from  www  . j  a v a  2s.  c o  m*/
 * @return the message caller
 * @throws NoSuchMethodException 
 * @throws SecurityException 
 */
@SuppressWarnings("unchecked")
public static Class<MessageCaller<?>> createMessageCaller(Class<?> ownerClass, Method method)
        throws SecurityException, NoSuchMethodException {

    String className = String.format("%s_%s_%d__MESSAGECALLER", ownerClass.getName(), method.getName(),
            getMethodNumber(method));
    String classNameInternal = className.replace('.', '/');
    java.lang.reflect.Type fullReturnType = method.getGenericReturnType();
    if ((!(fullReturnType instanceof ParameterizedType))
            && AsyncResult.class.isAssignableFrom(((Class) ((ParameterizedType) fullReturnType).getRawType())))
        throw new RuntimeException("Something's wrong here: should not be called for such a method");
    String returnSignature = GenericTypeHelper
            .getSignature(((ParameterizedType) fullReturnType).getActualTypeArguments()[0]);

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    MethodVisitor mv;

    cw.visit(codeVersion, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER + Opcodes.ACC_SYNTHETIC,
            classNameInternal, "L" + classNameInternal + "<" + returnSignature + ">;",
            "org/actorsguildframework/internal/MessageCaller", null);
    cw.visitSource(null, null);

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "org/actorsguildframework/internal/MessageCaller", "<init>",
                "()V");
        mv.visitInsn(Opcodes.RETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", "L" + classNameInternal + ";", null, l0, l1, 0);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "invoke",
                "(Lorg/actorsguildframework/Actor;[Ljava/lang/Object;)Lorg/actorsguildframework/AsyncResult;",
                "(Lorg/actorsguildframework/Actor;[Ljava/lang/Object;)Lorg/actorsguildframework/AsyncResult<"
                        + returnSignature + ">;",
                null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);

        mv.visitVarInsn(Opcodes.ALOAD, 1);
        mv.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(method.getDeclaringClass()) + "__ACTORPROXY");

        int idx = 0;
        for (Class<?> t : method.getParameterTypes()) {
            mv.visitVarInsn(Opcodes.ALOAD, 2);
            mv.visitIntInsn(Opcodes.BIPUSH, idx);
            mv.visitInsn(Opcodes.AALOAD);
            if (t.isPrimitive()) {
                String wrapperDescr = GenerationUtils.getWrapperInternalName(t);
                mv.visitTypeInsn(Opcodes.CHECKCAST, wrapperDescr);
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, wrapperDescr, t.getName() + "Value",
                        "()" + Type.getDescriptor(t));
            } else {
                if (isArgumentFreezingRequired(method, idx, t)) {
                    mv.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(SerializableFreezer.class));
                    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(SerializableFreezer.class),
                            "get", Type.getMethodDescriptor(SerializableFreezer.class.getMethod("get")));
                }
                if (!t.equals(Object.class))
                    mv.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(t));
            }
            idx++;
        }
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
                Type.getInternalName(method.getDeclaringClass()) + "__ACTORPROXY",
                String.format(SUPER_CALLER_NAME_FORMAT, method.getName()), Type.getMethodDescriptor(method));

        mv.visitInsn(Opcodes.ARETURN);

        Label l2 = new Label();
        mv.visitLabel(l2);
        mv.visitLocalVariable("this", "L" + classNameInternal + ";", null, l0, l2, 0);
        mv.visitLocalVariable("instance", "Lorg/actorsguildframework/Actor;", null, l0, l2, 1);
        mv.visitLocalVariable("arguments", "[Ljava/lang/Object;", null, l0, l2, 2);

        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getMessageName", "()Ljava/lang/String;", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitLdcInsn(method.getName());
        mv.visitInsn(Opcodes.ARETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", "L" + classNameInternal + ";", null, l0, l1, 0);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }
    cw.visitEnd();

    return (Class<MessageCaller<?>>) GenerationUtils.loadClass(className, cw.toByteArray());
}

From source file:org.actorsguildframework.internal.codegenerator.ActorProxyCreator.java

License:Apache License

/**
 * Creates a synchronized delegate method for a message method.
 * @param actorClass the actor class//from  ww w.j a  va2  s .c  o m
 * @param classNameDescriptor the descriptor of the resulting class
 * @param cw the class writer to write to
 * @param method the method being invoked
 * @param simpleDescriptor the descriptor of the method
 * @param genericSignature the generic signature of the method
 * @param isSynchronized true to make the method synchronized, false otherwise
 */
private static void writeSuperProxyMethod(Class<?> actorClass, String classNameDescriptor, ClassWriter cw,
        Method method, String simpleDescriptor, String genericSignature, boolean isSynchronized)
        throws NoSuchMethodException {
    MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC + (isSynchronized ? Opcodes.ACC_SYNCHRONIZED : 0),
            String.format(SUPER_CALLER_NAME_FORMAT, method.getName()), simpleDescriptor, genericSignature,
            null);
    mv.visitCode();
    Label l0 = new Label();
    mv.visitLabel(l0);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    for (int j = 0; j < method.getParameterTypes().length; j++)
        mv.visitVarInsn(Type.getType(method.getParameterTypes()[j]).getOpcode(Opcodes.ILOAD), j + 1);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(actorClass), method.getName(),
            simpleDescriptor);
    mv.visitInsn(Type.getType(method.getReturnType()).getOpcode(Opcodes.IRETURN));
    Label l1 = new Label();
    mv.visitLabel(l1);
    mv.visitLocalVariable("this", classNameDescriptor, null, l0, l1, 0);
    for (int j = 0; j < method.getParameterTypes().length; j++)
        mv.visitLocalVariable("arg" + j, Type.getDescriptor(method.getParameterTypes()[j]),
                GenericTypeHelper.getSignatureIfGeneric(method.getGenericParameterTypes()[j]), l0, l1, j + 1);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}

From source file:org.actorsguildframework.internal.codegenerator.ActorProxyCreator.java

License:Apache License

/**
 * Creates and loads the actor's proxy class.
 * @param actorClass the Actor class//from  ww w .  j  ava  2 s .c  om
 * @param acd the actor's class descriptor
 * @throws ConfigurationException if the agent is not configured correctly
 */
@SuppressWarnings("unchecked")
private static Class<?> generateProxyClass(Class<?> actorClass, final ActorClassDescriptor acd)
        throws NoSuchMethodException {
    BeanClassDescriptor bcd = acd.getBeanClassDescriptor();

    String className = String.format("%s__ACTORPROXY", actorClass.getName());
    final String classNameInternal = className.replace('.', '/');
    String classNameDescriptor = "L" + classNameInternal + ";";

    final Type actorState = Type
            .getType(acd.getConcurrencyModel().isMultiThreadingCapable() ? MultiThreadedActorState.class
                    : SingleThreadedActorState.class);

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    MethodVisitor mv;
    cw.visit(codeVersion, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER + Opcodes.ACC_SYNTHETIC,
            classNameInternal, null, Type.getInternalName(actorClass),
            new String[] { "org/actorsguildframework/internal/ActorProxy" });

    cw.visitSource(null, null);

    {
        for (int i = 0; i < acd.getMessageCount(); i++)
            cw.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL + Opcodes.ACC_STATIC,
                    String.format(MESSAGE_CALLER_NAME_FORMAT, i),
                    "Lorg/actorsguildframework/internal/MessageCaller;",
                    "Lorg/actorsguildframework/internal/MessageCaller<*>;", null).visitEnd();

        cw.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL, "actorState__ACTORPROXY",
                actorState.getDescriptor(), null, null).visitEnd();
    }

    BeanCreator.writePropFields(bcd, cw);

    {
        mv = cw.visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null);
        mv.visitCode();

        for (int i = 0; i < acd.getMessageCount(); i++) {
            Class<?> caller = createMessageCaller(acd.getMessage(i).getOwnerClass(),
                    acd.getMessage(i).getMethod());
            String mcName = Type.getInternalName(caller);
            mv.visitTypeInsn(Opcodes.NEW, mcName);
            mv.visitInsn(Opcodes.DUP);
            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, mcName, "<init>", "()V");
            mv.visitFieldInsn(Opcodes.PUTSTATIC, classNameInternal,
                    String.format(MESSAGE_CALLER_NAME_FORMAT, i),
                    "Lorg/actorsguildframework/internal/MessageCaller;");
        }
        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }

    BeanCreator.writeConstructor(actorClass, bcd, classNameInternal, cw, new BeanCreator.SnippetWriter() {
        @Override
        public void write(MethodVisitor mv) {
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitTypeInsn(Opcodes.NEW, actorState.getInternalName());
            mv.visitInsn(Opcodes.DUP);
            mv.visitVarInsn(Opcodes.ALOAD, 1);
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, actorState.getInternalName(), "<init>",
                    "(Lorg/actorsguildframework/internal/Controller;Lorg/actorsguildframework/Actor;)V");
            mv.visitFieldInsn(Opcodes.PUTFIELD, classNameInternal, "actorState__ACTORPROXY",
                    actorState.getDescriptor());
        }
    });

    BeanCreator.writePropAccessors(bcd, classNameInternal, cw);

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getState__ACTORPROXYMETHOD",
                "()Lorg/actorsguildframework/internal/ActorState;", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitFieldInsn(Opcodes.GETFIELD, classNameInternal, "actorState__ACTORPROXY",
                actorState.getDescriptor());
        mv.visitInsn(Opcodes.ARETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", classNameDescriptor, null, l0, l1, 0);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }

    for (int i = 0; i < acd.getMessageCount(); i++) {
        MessageImplDescriptor mid = acd.getMessage(i);
        Method method = mid.getMethod();
        String simpleDescriptor = Type.getMethodDescriptor(method);
        String genericSignature = GenericTypeHelper.getSignature(method);

        writeProxyMethod(classNameInternal, classNameDescriptor, cw, i, actorState, acd.getConcurrencyModel(),
                mid, method, simpleDescriptor, genericSignature);

        writeSuperProxyMethod(actorClass, classNameDescriptor, cw, method, simpleDescriptor, genericSignature,
                !acd.getConcurrencyModel().isMultiThreadingCapable());
    }

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_SYNCHRONIZED, "toString", "()Ljava/lang/String;",
                null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "toString", "()Ljava/lang/String;");
        mv.visitInsn(Opcodes.ARETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", classNameDescriptor, null, l0, l1, 0);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }
    cw.visitEnd();

    try {
        return (Class<? extends ActorProxy>) GenerationUtils.loadClass(className, cw.toByteArray());
    } catch (Exception e) {
        throw new ConfigurationException("Failure loading ActorProxy", e);
    }
}

From source file:org.actorsguildframework.internal.codegenerator.ActorProxyCreator.java

License:Apache License

/**
 * Writes a proxy method for messages./* ww w. j a  v  a 2 s .com*/
 * @param classNameInternal the internal class name
 * @param classNameDescriptor the class name descriptor
 * @param cw the ClassWriter
 * @param index the message index
 * @param type the ActorState type to use
 * @param concurrencyModel the concurrency model of the message
 * @param messageDescriptor the message's descriptor
 * @param method the method to override
 * @param simpleDescriptor a simple descriptor of the message
 * @param genericSignature the signature of the message
 */
private static void writeProxyMethod(String classNameInternal, String classNameDescriptor, ClassWriter cw,
        int index, Type actorState, ConcurrencyModel concurrencyModel, MessageImplDescriptor messageDescriptor,
        Method method, String simpleDescriptor, String genericSignature) throws NoSuchMethodException {
    MethodVisitor mv;
    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, method.getName(), simpleDescriptor, genericSignature, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitIntInsn(Opcodes.BIPUSH, method.getParameterTypes().length);
        mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
        for (int j = 0; j < method.getParameterTypes().length; j++) {
            mv.visitInsn(Opcodes.DUP);
            mv.visitIntInsn(Opcodes.BIPUSH, j);
            Class<?> paraType = method.getParameterTypes()[j];
            if (paraType.isPrimitive()) {
                String wrapperClass = GenerationUtils.getWrapperInternalName(paraType);
                Type primType = Type.getType(paraType);
                mv.visitVarInsn(primType.getOpcode(Opcodes.ILOAD), j + 1);
                mv.visitMethodInsn(Opcodes.INVOKESTATIC, wrapperClass, "valueOf",
                        "(" + primType.getDescriptor() + ")" + "L" + wrapperClass + ";");
            } else if (isArgumentFreezingRequired(method, j, paraType)) {
                mv.visitVarInsn(Opcodes.ALOAD, j + 1);
                mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(SerializableFreezer.class),
                        "freeze",
                        Type.getMethodDescriptor(SerializableFreezer.class.getMethod("freeze", Object.class)));
            } else if (paraType.isInterface()) {
                mv.visitVarInsn(Opcodes.ALOAD, j + 1);
                mv.visitInsn(Opcodes.DUP);
                mv.visitTypeInsn(Opcodes.INSTANCEOF, "org/actorsguildframework/Actor");
                Label lEndif = new Label();
                mv.visitJumpInsn(Opcodes.IFNE, lEndif);
                mv.visitTypeInsn(Opcodes.NEW, Type.getInternalName(ActorRuntimeException.class));
                mv.visitInsn(Opcodes.DUP);
                mv.visitLdcInsn(String.format(
                        "Argument %d is an non-Serializable interface, but you did not give an Actor. If a message's argument type is an interface that does not extend Serializable, only Actors are acceptable as argument.",
                        j));
                mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(ActorRuntimeException.class),
                        "<init>", "(Ljava/lang/String;)V");
                mv.visitInsn(Opcodes.ATHROW);
                mv.visitLabel(lEndif);
            } else
                mv.visitVarInsn(Opcodes.ALOAD, j + 1);

            mv.visitInsn(Opcodes.AASTORE);
        }
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitVarInsn(Opcodes.ASTORE, method.getParameterTypes().length + 1); // method.getParameterTypes().length+1 ==> 'args' local variable
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitFieldInsn(Opcodes.GETFIELD, classNameInternal, "actorState__ACTORPROXY",
                actorState.getDescriptor());
        mv.visitFieldInsn(Opcodes.GETSTATIC, classNameInternal,
                String.format(MESSAGE_CALLER_NAME_FORMAT, index),
                "Lorg/actorsguildframework/internal/MessageCaller;");
        mv.visitFieldInsn(Opcodes.GETSTATIC, "org/actorsguildframework/annotations/ThreadUsage",
                messageDescriptor.getThreadUsage().name(),
                "Lorg/actorsguildframework/annotations/ThreadUsage;");
        mv.visitVarInsn(Opcodes.ALOAD, method.getParameterTypes().length + 1);
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, actorState.getInternalName(), "queueMessage",
                "(Lorg/actorsguildframework/internal/MessageCaller;Lorg/actorsguildframework/annotations/ThreadUsage;[Ljava/lang/Object;)Lorg/actorsguildframework/internal/AsyncResultImpl;");
        mv.visitInsn(Opcodes.ARETURN);
        Label l4 = new Label();
        mv.visitLabel(l4);
        mv.visitLocalVariable("this", classNameDescriptor, null, l0, l4, 0);
        for (int j = 0; j < method.getParameterTypes().length; j++)
            mv.visitLocalVariable("arg" + j, Type.getDescriptor(method.getParameterTypes()[j]),
                    GenericTypeHelper.getSignatureIfGeneric(method.getGenericParameterTypes()[j]), l0, l4,
                    j + 1);
        mv.visitLocalVariable("args", "[Ljava/lang/Object;", null, l1, l4,
                method.getParameterTypes().length + 1);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }
}

From source file:org.actorsguildframework.internal.codegenerator.BeanCreator.java

License:Apache License

/**
 * Creates and loads the bean's factory class.
 * @param beanClass the Bean class/*  w  w  w . j av  a2  s  .c om*/
 * @param generatedBeanClassName the name of the class that this factory will produce
 * @param bcd the bean class descriptor
 * @param synchronizeInitializers true to synchronize the initializer invocations (actors
 *       do this), false otherwise
 * @return the new factory
 */
public static BeanFactory generateFactoryClass(Class<?> beanClass, String generatedBeanClassName,
        BeanClassDescriptor bcd, boolean synchronizeInitializers) {
    String className = String.format("%s__BEANFACTORY", beanClass.getName());
    String classNameInternal = className.replace('.', '/');

    String generatedBeanClassNameInternal = generatedBeanClassName.replace('.', '/');

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    MethodVisitor mv;
    cw.visit(codeVersion, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER + Opcodes.ACC_SYNTHETIC,
            classNameInternal, null, "java/lang/Object",
            new String[] { Type.getInternalName(BeanFactory.class) });

    cw.visitSource(null, null);

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
        mv.visitInsn(Opcodes.RETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", "L" + classNameInternal + ";", null, l0, l1, 0);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "createNewInstance",
                "(Lorg/actorsguildframework/internal/Controller;Lorg/actorsguildframework/Props;)Ljava/lang/Object;",
                null, null);
        mv.visitCode();
        final int initCount = bcd.getInitializerCount();
        Label tryStart = new Label();
        Label tryEnd = new Label();
        Label tryFinally = new Label();
        Label tryFinallyEnd = new Label();
        if (synchronizeInitializers && (initCount > 0)) {
            mv.visitTryCatchBlock(tryStart, tryEnd, tryFinally, null);
            mv.visitTryCatchBlock(tryFinally, tryFinallyEnd, tryFinally, null);
        }

        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitTypeInsn(Opcodes.NEW, generatedBeanClassNameInternal);
        mv.visitInsn(Opcodes.DUP);
        mv.visitVarInsn(Opcodes.ALOAD, 1);
        mv.visitVarInsn(Opcodes.ALOAD, 2);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, generatedBeanClassNameInternal, "<init>",
                "(Lorg/actorsguildframework/internal/Controller;Lorg/actorsguildframework/Props;)V");

        if (synchronizeInitializers) {
            mv.visitInsn(Opcodes.DUP);
            mv.visitInsn(Opcodes.MONITORENTER);
            mv.visitLabel(tryStart);
        }

        for (int i = 0; i < initCount; i++) {
            Method m = bcd.getInitializers(i);
            mv.visitInsn(Opcodes.DUP);
            mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, generatedBeanClassNameInternal, m.getName(),
                    Type.getMethodDescriptor(m));
        }

        if (synchronizeInitializers) {
            if (initCount > 0) {
                mv.visitInsn(Opcodes.DUP);
                mv.visitInsn(Opcodes.MONITOREXIT);
                mv.visitLabel(tryEnd);
                mv.visitJumpInsn(Opcodes.GOTO, tryFinallyEnd);
            }
            mv.visitLabel(tryFinally);
            mv.visitInsn(Opcodes.DUP);
            mv.visitInsn(Opcodes.MONITOREXIT);
            mv.visitLabel(tryFinallyEnd);
        }

        mv.visitInsn(Opcodes.ARETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", "L" + classNameInternal + ";", null, l0, l1, 0);
        mv.visitLocalVariable("controller", "Lorg/actorsguildframework/internal/Controller;", null, l0, l1, 1);
        mv.visitLocalVariable("props", "Lorg/actorsguildframework/Props;", null, l0, l1, 2);
        mv.visitLocalVariable("synchronizeInitializer", "Z", null, l0, l1, 3);
        mv.visitMaxs(4, 3);
        mv.visitEnd();
    }
    cw.visitEnd();

    Class<?> newClass = GenerationUtils.loadClass(className, cw.toByteArray());
    try {
        return (BeanFactory) newClass.newInstance();
    } catch (Exception e) {
        throw new ConfigurationException("Failure loading ActorProxyFactory", e);
    }
}

From source file:org.actorsguildframework.internal.codegenerator.BeanCreator.java

License:Apache License

/**
 * Creates and loads the bean implementation class.
 * @param beanClass the bean class//from  w  w  w . jav a  2 s. co m
 * @param bcd the BeanClassDescriptor to use
 * @throws ConfigurationException if the agent is not configured correctly
 */
private static Class<?> generateBeanClass(Class<?> beanClass, BeanClassDescriptor bcd)
        throws NoSuchMethodException {

    String className = String.format("%s__BEAN", beanClass.getName());
    String classNameInternal = className.replace('.', '/');

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    MethodVisitor mv;
    cw.visit(codeVersion, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER + Opcodes.ACC_SYNTHETIC,
            classNameInternal, null, Type.getInternalName(beanClass), new String[] {});

    cw.visitSource(null, null);

    // write @Prop fields
    writePropFields(bcd, cw);

    // static constructor
    {
        mv = cw.visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null);
        mv.visitCode();
        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }

    // constructor(Controller, Props)
    writeConstructor(beanClass, bcd, classNameInternal, cw, null);

    // Write @Prop accessors
    writePropAccessors(bcd, classNameInternal, cw);

    cw.visitEnd();

    try {
        return (Class<?>) GenerationUtils.loadClass(className, cw.toByteArray());
    } catch (Exception e) {
        throw new ConfigurationException("Failure loading generated Bean", e);
    }
}