Example usage for org.objectweb.asm Opcodes V1_5

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

Introduction

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

Prototype

int V1_5

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

Click Source Link

Usage

From source file:org.adjective.stout.writer.ByteCodeWriter.java

License:Apache License

public byte[] write(ClassDescriptor cls) {
    begin(cls);//  ww w .  j a  va  2  s .co m
    ClassWriter writer = createClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
    ClassVisitor cv = writer;
    if (_trace) {
        cv = new TraceClassVisitor(cv, new PrintWriter(System.err));
    }
    if (_check) {
        cv = new CheckClassAdapter(cv);
    }

    String signature = null; // @TODO
    cv.visit(Opcodes.V1_5, getModifierCode(cls.getModifiers(), cls.getSort()), cls.getInternalName(), signature,
            getInternalName(cls.getSuperClass()), getInterfaceNames(cls));

    if (cls.getSourceFile() != null) {
        cv.visitSource(cls.getSourceFile(), "");
    }

    UnresolvedType outer = cls.getOuterClass();
    if (outer != null) {
        cv.visitOuterClass(outer.getInternalName(), null, null);
    }

    for (AnnotationDescriptor annotation : cls.getAnnotations()) {
        writeAnnotation(cv, annotation);
    }

    for (ClassDescriptor inner : cls.getInnerClasses()) {
        String name = inner.getInternalName();
        String simpleName = name.substring(name.lastIndexOf('/') + 1);
        cv.visitInnerClass(name, cls.getInternalName(), simpleName,
                getModifierCode(inner.getModifiers(), inner.getSort()));
    }

    for (FieldDescriptor field : cls.getFields()) {
        writeField(cv, field);
    }

    for (MethodDescriptor method : cls.getMethods()) {
        writeMethod(cv, cls, method);
    }

    cv.visitEnd();

    end(cls);
    return writer.toByteArray();
}

From source file:org.apache.aries.proxy.impl.ProxyUtils.java

License:Apache License

/**
 * Get the java version to be woven at.//from ww w.  j ava  2 s  . c o  m
 * @return
 */
public static int getWeavingJavaVersion() {
    if (weavingJavaVersion == -1) {
        //In order to avoid an inconsistent stack error the version of the woven byte code needs to match
        //the level of byte codes in the original class
        switch (JAVA_CLASS_VERSION) {
        case Opcodes.V1_8:
            LOGGER.debug("Weaving to Java 8");
            weavingJavaVersion = Opcodes.V1_8;
            break;
        case Opcodes.V1_7:
            LOGGER.debug("Weaving to Java 7");
            weavingJavaVersion = Opcodes.V1_7;
            break;
        case Opcodes.V1_6:
            LOGGER.debug("Weaving to Java 6");
            weavingJavaVersion = Opcodes.V1_6;
            break;
        case Opcodes.V1_5:
            LOGGER.debug("Weaving to Java 5");
            weavingJavaVersion = Opcodes.V1_5;
            break;
        default:
            //aries should work with Java 5 or above - also will highlight when a higher level (and unsupported) level of Java is released
            throw new IllegalArgumentException("Invalid Java version " + JAVA_CLASS_VERSION);
        }
    }
    return weavingJavaVersion;
}

From source file:org.apache.commons.weaver.privilizer.ActionGenerator.java

License:Apache License

private void begin() {
    owner.visitInnerClass(action.getInternalName(), owner.className, simpleName,
            Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC);

    final SignatureWriter type = new SignatureWriter();
    final SignatureVisitor actionImplemented = type.visitInterface();
    actionImplemented.visitClassType(actionInterface.getInternalName());
    final SignatureVisitor visitTypeArgument = actionImplemented.visitTypeArgument('=');
    new SignatureReader(Privilizer.wrap(methd.getReturnType()).getDescriptor()).accept(visitTypeArgument);
    actionImplemented.visitEnd();//from w  ww  .ja  v a 2  s.co  m

    final String signature = type.toString();

    visit(Opcodes.V1_5, Opcodes.ACC_SUPER | Opcodes.ACC_SYNTHETIC | Opcodes.ACC_FINAL, action.getInternalName(),
            signature, Type.getType(Object.class).getInternalName(),
            new String[] { actionInterface.getInternalName() });
}

From source file:org.apache.cxf.binding.corba.utils.CorbaAnyHelper.java

License:Apache License

private static synchronized void createFixedAnyConstructor() {
    if (fixedAnyConstructor != null) {
        return;/*from w ww .j  av a 2 s . c  o  m*/
    }

    ASMHelper helper = new ASMHelper();
    ClassWriter cw = helper.createClassWriter();
    FieldVisitor fv;

    cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER,
            "org/apache/cxf/binding/corba/utils/FixedAnyImpl", null, "com/sun/corba/se/impl/corba/AnyImpl",
            null);

    cw.visitSource("FixedAnyImpl.java", null);

    fv = cw.visitField(0, "obj", "Lorg/omg/CORBA/portable/Streamable;", null, null);
    fv.visitEnd();
    addFixedAnyConstructor(cw);
    addInsertOverride(cw);
    addExtractOverride(cw);
    addReadOverride(cw);
    addWriteOverride(cw);

    cw.visitEnd();

    byte[] b = cw.toByteArray();
    Class<?> c = helper.loadClass("org.apache.cxf.binding.corba.utils.FixedAnyImpl", CorbaAnyHelper.class, b);
    try {
        fixedAnyConstructor = c.getConstructor(ORB.class, Any.class);
    } catch (Exception e) {
        //shouldn't happen since we generated that constructor
    }
}

From source file:org.apache.cxf.jaxb.JAXBUtils.java

License:Apache License

private static Class<?> createNamespaceWrapperInternal(ASMHelper helper, ClassWriter cw) {
    String className = "org.apache.cxf.jaxb.NamespaceMapperInternal";
    FieldVisitor fv;/*from  w  ww . j  ava 2 s.  c  o  m*/
    MethodVisitor mv;
    cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER,
            "org/apache/cxf/jaxb/NamespaceMapperInternal", null,
            "com/sun/xml/internal/bind/marshaller/NamespacePrefixMapper", null);

    cw.visitSource("NamespaceMapper.java", null);

    fv = cw.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL, "nspref", "Ljava/util/Map;",
            "Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;", null);
    fv.visitEnd();

    mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "(Ljava/util/Map;)V",
            "(Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;)V", null);
    mv.visitCode();
    Label l0 = new Label();
    mv.visitLabel(l0);
    mv.visitLineNumber(30, l0);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "com/sun/xml/internal/bind/marshaller/NamespacePrefixMapper",
            "<init>", "()V");
    Label l1 = new Label();
    mv.visitLabel(l1);
    mv.visitLineNumber(31, l1);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitVarInsn(Opcodes.ALOAD, 1);
    mv.visitFieldInsn(Opcodes.PUTFIELD, "org/apache/cxf/jaxb/NamespaceMapperInternal", "nspref",
            "Ljava/util/Map;");
    Label l2 = new Label();
    mv.visitLabel(l2);
    mv.visitLineNumber(32, l2);
    mv.visitInsn(Opcodes.RETURN);
    Label l3 = new Label();
    mv.visitLabel(l3);
    mv.visitLocalVariable("this", "Lorg/apache/cxf/jaxb/NamespaceMapperInternal;", null, l0, l3, 0);
    mv.visitLocalVariable("nspref", "Ljava/util/Map;", "Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;",
            l0, l3, 1);
    mv.visitMaxs(2, 2);
    mv.visitEnd();

    mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getPreferredPrefix",
            "(Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String;", null, null);
    mv.visitCode();
    l0 = new Label();
    mv.visitLabel(l0);
    mv.visitLineNumber(38, l0);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitFieldInsn(Opcodes.GETFIELD, "org/apache/cxf/jaxb/NamespaceMapperInternal", "nspref",
            "Ljava/util/Map;");
    mv.visitVarInsn(Opcodes.ALOAD, 1);
    mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Map", "get",
            "(Ljava/lang/Object;)Ljava/lang/Object;");
    mv.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/String");
    mv.visitVarInsn(Opcodes.ASTORE, 4);
    l1 = new Label();
    mv.visitLabel(l1);
    mv.visitLineNumber(39, l1);
    mv.visitVarInsn(Opcodes.ALOAD, 4);
    l2 = new Label();
    mv.visitJumpInsn(Opcodes.IFNULL, l2);
    l3 = new Label();
    mv.visitLabel(l3);
    mv.visitLineNumber(40, l3);
    mv.visitVarInsn(Opcodes.ALOAD, 4);
    mv.visitInsn(Opcodes.ARETURN);
    mv.visitLabel(l2);
    mv.visitLineNumber(42, l2);
    mv.visitVarInsn(Opcodes.ALOAD, 2);
    mv.visitInsn(Opcodes.ARETURN);
    Label l4 = new Label();
    mv.visitLabel(l4);
    mv.visitLocalVariable("this", "Lorg/apache/cxf/jaxb/NamespaceMapperInternal;", null, l0, l4, 0);
    mv.visitLocalVariable("namespaceUri", "Ljava/lang/String;", null, l0, l4, 1);
    mv.visitLocalVariable("suggestion", "Ljava/lang/String;", null, l0, l4, 2);
    mv.visitLocalVariable("requirePrefix", "Z", null, l0, l4, 3);
    mv.visitLocalVariable("prefix", "Ljava/lang/String;", null, l1, l4, 4);
    mv.visitMaxs(2, 5);
    mv.visitEnd();
    cw.visitEnd();

    byte bts[] = cw.toByteArray();
    return helper.loadClass(className, JAXBUtils.class, bts);
}

From source file:org.apache.cxf.jaxb.WrapperHelperCompiler.java

License:Apache License

public WrapperHelper compile() {
    if (cw == null) {
        return null;
    }// w ww.  j a  v  a 2 s. c  om
    int count = 1;
    String newClassName = wrapperType.getName() + "_WrapperTypeHelper" + count;
    newClassName = newClassName.replaceAll("\\$", ".");
    newClassName = periodToSlashes(newClassName);

    Class<?> cls = super.findClass(newClassName.replace('/', '.'), wrapperType);
    while (cls != null) {
        try {
            WrapperHelper helper = WrapperHelper.class.cast(cls.newInstance());
            if (!helper.getSignature().equals(computeSignature())) {
                count++;
                newClassName = wrapperType.getName() + "_WrapperTypeHelper" + count;
                newClassName = newClassName.replaceAll("\\$", ".");
                newClassName = periodToSlashes(newClassName);
                cls = super.findClass(newClassName.replace('/', '.'), wrapperType);
            } else {
                return helper;
            }
        } catch (Exception e) {
            return null;
        }
    }

    cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER, newClassName, null, "java/lang/Object",
            new String[] { periodToSlashes(WrapperHelper.class.getName()) });

    addConstructor(newClassName, cw, objectFactory == null ? null : objectFactory.getClass());
    boolean b = addSignature();
    if (b) {
        b = addCreateWrapperObject(newClassName, objectFactory == null ? null : objectFactory.getClass());
    }
    if (b) {
        b = addGetWrapperParts(newClassName, wrapperType, getMethods, fields, cw);
    }

    try {
        if (b) {
            cw.visitEnd();
            byte bt[] = cw.toByteArray();
            Class<?> cl = loadClass(newClassName.replace('/', '.'), wrapperType, bt);
            Object o = cl.newInstance();
            return WrapperHelper.class.cast(o);
        }
    } catch (Throwable e) {
        // ignore, we'll just fall down to reflection based
    }
    return null;
}

From source file:org.apache.cxf.jaxws.WrapperClassGenerator.java

License:Apache License

private void createWrapperClass(MessagePartInfo wrapperPart, MessageInfo messageInfo, OperationInfo op,
        Method method, boolean isRequest) {

    QName wrapperElement = messageInfo.getName();

    boolean anonymous = factory.getAnonymousWrapperTypes();

    ClassWriter cw = createClassWriter();
    String pkg = getPackageName(method) + ".jaxws_asm" + (anonymous ? "_an" : "");
    String className = pkg + "." + StringUtils.capitalize(op.getName().getLocalPart());
    if (!isRequest) {
        className = className + "Response";
    }//from   ww w. j  ava  2  s  .co m
    String pname = pkg + ".package-info";
    Class<?> def = findClass(pname, method.getDeclaringClass());
    if (def == null) {
        generatePackageInfo(pname, wrapperElement.getNamespaceURI(), method.getDeclaringClass());
    }

    def = findClass(className, method.getDeclaringClass());
    if (def != null) {
        wrapperPart.setTypeClass(def);
        wrapperBeans.add(def);
        return;
    }
    String classFileName = periodToSlashes(className);
    cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, classFileName, null, "java/lang/Object",
            null);

    AnnotationVisitor av0 = cw.visitAnnotation("Ljavax/xml/bind/annotation/XmlRootElement;", true);
    av0.visit("name", wrapperElement.getLocalPart());
    av0.visit("namespace", wrapperElement.getNamespaceURI());
    av0.visitEnd();

    av0 = cw.visitAnnotation("Ljavax/xml/bind/annotation/XmlAccessorType;", true);
    av0.visitEnum("value", "Ljavax/xml/bind/annotation/XmlAccessType;", "FIELD");
    av0.visitEnd();

    av0 = cw.visitAnnotation("Ljavax/xml/bind/annotation/XmlType;", true);
    if (!anonymous) {
        av0.visit("name", wrapperElement.getLocalPart());
        av0.visit("namespace", wrapperElement.getNamespaceURI());
    } else {
        av0.visit("name", "");
    }
    av0.visitEnd();

    // add constructor
    MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
    mv.visitCode();
    Label lbegin = new Label();
    mv.visitLabel(lbegin);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
    mv.visitInsn(Opcodes.RETURN);
    Label lend = new Label();
    mv.visitLabel(lend);
    mv.visitLocalVariable("this", "L" + classFileName + ";", null, lbegin, lend, 0);
    mv.visitMaxs(1, 1);
    mv.visitEnd();

    for (MessagePartInfo mpi : messageInfo.getMessageParts()) {
        generateMessagePart(cw, mpi, method, classFileName);
    }

    cw.visitEnd();

    Class<?> clz = loadClass(className, method.getDeclaringClass(), cw.toByteArray());
    wrapperPart.setTypeClass(clz);
    wrapperBeans.add(clz);
}

From source file:org.apache.cxf.jaxws.WrapperClassGenerator.java

License:Apache License

private void generatePackageInfo(String className, String ns, Class clz) {
    ClassWriter cw = createClassWriter();
    String classFileName = periodToSlashes(className);
    cw.visit(Opcodes.V1_5, Opcodes.ACC_ABSTRACT + Opcodes.ACC_INTERFACE, classFileName, null,
            "java/lang/Object", null);

    boolean q = qualified;
    SchemaInfo si = interfaceInfo.getService().getSchema(ns);
    if (si != null) {
        q = si.isElementFormQualified();
    }/* ww w. ja  va2  s. co m*/
    AnnotationVisitor av0 = cw.visitAnnotation("Ljavax/xml/bind/annotation/XmlSchema;", true);
    av0.visit("namespace", ns);
    av0.visitEnum("elementFormDefault", getClassCode(XmlNsForm.class), q ? "QUALIFIED" : "UNQUALIFIED");
    av0.visitEnd();
    cw.visitEnd();

    loadClass(className, clz, cw.toByteArray());
}

From source file:org.brutusin.instrumentation.utils.TreeInstructions.java

License:Apache License

public static InsnList getClassConstantReference(Type type, int majorVersion) {
    InsnList il = new InsnList();

    if (majorVersion >= Opcodes.V1_5) {
        il.add(new LdcInsnNode(type));

    } else {//w  w w. j av a  2  s .  c o  m
        String fullyQualifiedName = type.getInternalName().replaceAll("/", ".");
        il.add(new LdcInsnNode(fullyQualifiedName));
        il.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Class", "forName",
                "(Ljava/lang/String;)Ljava/lang/Class;", false));
    }
    return il;
}

From source file:org.codehaus.groovy.runtime.ProxyGeneratorAdapter.java

License:Apache License

/**
 * Construct a proxy generator. This generator is used when we need to create a proxy object for a class or an
 * interface given a map of closures./*from  www  . j  av  a  2  s.c  o  m*/
 *
 * @param closureMap    the delegates implementations
 * @param superClass    corresponding to the superclass class visitor
 * @param interfaces    extra interfaces the proxy should implement
 * @param proxyLoader   the class loader which should be used to load the generated proxy
 * @param delegateClass if not null, generate a delegate field with the corresponding class
 * @param emptyBody     if set to true, the unimplemented abstract methods will receive an empty body instead of
 *                      throwing an {@link UnsupportedOperationException}.
 */
public ProxyGeneratorAdapter(final Map<Object, Object> closureMap, final Class superClass,
        final Class[] interfaces, final ClassLoader proxyLoader, final boolean emptyBody,
        final Class delegateClass) {
    super(CompilerConfiguration.ASM_API_VERSION, new ClassWriter(0));
    this.loader = proxyLoader != null ? createInnerLoader(proxyLoader, interfaces)
            : findClassLoader(superClass, interfaces);
    this.visitedMethods = new LinkedHashSet<Object>();
    this.delegatedClosures = closureMap.isEmpty() ? EMPTY_DELEGATECLOSURE_MAP : new HashMap<String, Boolean>();
    boolean wildcard = false;
    for (Map.Entry<Object, Object> entry : closureMap.entrySet()) {
        String name = entry.getKey().toString();
        if ("*".equals(name)) {
            wildcard = true;
        }
        this.delegatedClosures.put(name, Boolean.FALSE);
    }
    this.hasWildcard = wildcard;

    Class fixedSuperClass = adjustSuperClass(superClass, interfaces);
    // if we have to delegate to another object, generate the appropriate delegate field
    // and collect the name of the methods for which delegation is active
    this.generateDelegateField = delegateClass != null;
    this.objectDelegateMethods = generateDelegateField
            ? createDelegateMethodList(fixedSuperClass, delegateClass, interfaces)
            : EMPTY_STRING_SET;
    this.delegateClass = delegateClass;

    // a proxy is supposed to be a concrete class, so it cannot extend an interface.
    // If the provided superclass is an interface, then we replace the superclass with Object
    // and add this interface to the list of implemented interfaces
    this.superClass = fixedSuperClass;

    // create the base list of classes which have possible methods to be overloaded
    this.classList = new LinkedHashSet<Class>();
    this.classList.add(superClass);
    if (generateDelegateField) {
        classList.add(delegateClass);
        Collections.addAll(this.classList, delegateClass.getInterfaces());
    }
    if (interfaces != null) {
        Collections.addAll(this.classList, interfaces);
    }
    this.proxyName = proxyName();
    this.emptyBody = emptyBody;

    // generate bytecode
    ClassWriter writer = (ClassWriter) cv;
    this.visit(Opcodes.V1_5, ACC_PUBLIC, proxyName, null, null, null);
    byte[] b = writer.toByteArray();
    //        CheckClassAdapter.verify(new ClassReader(b), true, new PrintWriter(System.err));
    cachedClass = loader.defineClass(proxyName.replace('/', '.'), b);
    // cache no-arg constructor
    Class[] args = generateDelegateField ? new Class[] { Map.class, delegateClass } : new Class[] { Map.class };
    Constructor constructor;
    try {
        constructor = cachedClass.getConstructor(args);
    } catch (NoSuchMethodException e) {
        constructor = null;
    }
    cachedNoArgConstructor = constructor;
}