Example usage for org.objectweb.asm Opcodes ACC_PROTECTED

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

Introduction

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

Prototype

int ACC_PROTECTED

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

Click Source Link

Usage

From source file:appeng.transformer.asm.ASMTweaker.java

License:Open Source License

private void makePublic(ClassNode classNode, PublicLine set) {
    for (MethodNode mn : classNode.methods) {
        if (mn.name.equals(set.name) && mn.desc.equals(set.desc)) {
            mn.access = (mn.access & (~(Opcodes.ACC_FINAL | Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED)))
                    | Opcodes.ACC_PUBLIC;
            this.log(mn.name + mn.desc + " - Transformed");
        }//from   www. j a  v  a 2  s  .c  o  m
    }
}

From source file:blue.origami.asm.OAnno.java

License:Apache License

public void add(String spec) {
    String[] annos = spec.split(",");
    for (String s : annos) {
        s = s.toLowerCase();/*from   w ww.  j a v  a 2  s  . c  om*/
        switch (s) {
        case "public":
            acc |= Opcodes.ACC_PUBLIC;
            acc &= ~Opcodes.ACC_PROTECTED;
            acc &= ~Opcodes.ACC_PRIVATE;
            break;
        case "protected":
            acc |= Opcodes.ACC_PROTECTED;
            acc &= ~Opcodes.ACC_PUBLIC;
            acc &= ~Opcodes.ACC_PRIVATE;
            break;
        case "private":
            acc |= Opcodes.ACC_PRIVATE;
            acc &= ~Opcodes.ACC_PUBLIC;
            acc &= ~Opcodes.ACC_PROTECTED;
            break;
        case "static":
            acc |= Opcodes.ACC_STATIC;
            break;
        case "abstract":
            acc |= Opcodes.ACC_ABSTRACT;
            break;
        case "interface":
            acc |= Opcodes.ACC_INTERFACE;
            break;
        case "final":
            acc |= Opcodes.ACC_FINAL;
            break;
        case "native":
            acc |= Opcodes.ACC_NATIVE;
            break;
        case "synchronized":
            acc |= Opcodes.ACC_SYNCHRONIZED;
            break;
        case "strictfp":
            acc |= Opcodes.ACC_STRICT;
            break;
        }
    }
}

From source file:blue.origami.asm.OAnno.java

License:Apache License

public final boolean isProtected() {
    return ((acc & Opcodes.ACC_PROTECTED) == Opcodes.ACC_PROTECTED);
}

From source file:bndtools.diff.JarDiff.java

License:Open Source License

private static Set<ClassInfo> getClassesFromPackage(PackageInfo pi, Jar jar, String packageName,
        String version) {// w ww  .  ja va2  s  .c  o m
    packageName = packageName.replace('.', '/');
    Map<String, Map<String, Resource>> dirs = jar.getDirectories();
    if (dirs == null) {
        return Collections.emptySet();
    }
    Map<String, Resource> res = dirs.get(packageName);
    if (res == null) {
        return Collections.emptySet();
    }
    Set<ClassInfo> ret = new TreeSet<ClassInfo>();

    for (Map.Entry<String, Resource> me : res.entrySet()) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        if (me.getKey().endsWith(".class")) {
            InputStream is = null;
            try {
                is = me.getValue().openInputStream();
                byte[] bytes = new byte[8092];
                int bytesRead = 0;
                while ((bytesRead = is.read(bytes, 0, 8092)) != -1) {
                    baos.write(bytes, 0, bytesRead);
                }

                byte[] classBytes = baos.toByteArray();
                MessageDigest md = MessageDigest.getInstance("SHA1");
                md.update(classBytes);
                byte[] digest = md.digest();
                ClassReader cr = new ClassReader(classBytes);
                ClassInfo ca = new ClassInfo(pi, digest);
                cr.accept(ca, 0);

                for (int i = 0; i < ca.methods.size(); i++) {
                    MethodNode mn = (MethodNode) ca.methods.get(i);
                    // Ignore anything but public and protected methods
                    if ((mn.access & Opcodes.ACC_PUBLIC) == Opcodes.ACC_PUBLIC
                            || (mn.access & Opcodes.ACC_PROTECTED) == Opcodes.ACC_PROTECTED) {
                        MethodInfo mi = new MethodInfo(mn, ca);
                        ca.addPublicMethod(mi);
                    }
                }
                for (int i = 0; i < ca.fields.size(); i++) {
                    FieldNode mn = (FieldNode) ca.fields.get(i);
                    // Ignore anything but public fields
                    if ((mn.access & Opcodes.ACC_PUBLIC) == Opcodes.ACC_PUBLIC
                            || (mn.access & Opcodes.ACC_PROTECTED) == Opcodes.ACC_PROTECTED) {
                        FieldInfo mi = new FieldInfo(mn, ca);
                        ca.addPublicField(mi);
                    }
                }
                ret.add(ca);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    return ret;
}

From source file:ca.weblite.asm.JavaExtendedStubCompiler.java

License:Apache License

public Map<String, byte[]> compile(List<Type> types, File sourceFile) throws IOException {
    final Map<String, byte[]> outMap = new HashMap<>();
    final Set<String> typeNames = (types == null) ? null : new HashSet<String>();
    if (types != null) {
        for (Type type : types) {
            typeNames.add(type.getInternalName());
        }/*from  ww w. ja  v  a 2  s.  c o  m*/
    }
    JavaCompiler compiler = JavacTool.create();
    MyFileObject[] fos = new MyFileObject[] { new MyFileObject(sourceFile) };

    JavacTask task = (JavacTask) compiler.getTask(null, null, null, null, null, Arrays.asList(fos));
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    TreePathScanner scanner;

    final LinkedList<ClassFinder> scopeStack = new LinkedList<>();
    scanner = new TreePathScanner() {

        String packageName;
        ClassNode superClass;
        LinkedList<String> stack = new LinkedList<>();
        LinkedList<ClassInfo> classInfoStack = new LinkedList<>();
        LinkedList<ClassWriter> cwStack = new LinkedList<>();
        LinkedList<List<? extends TypeParameterTree>> typeParametersStack = new LinkedList<>();

        @Override
        public Object visitCompilationUnit(CompilationUnitTree cut, Object p) {

            packageName = cut.getPackageName().toString();
            ClassFinder scope = new ClassFinder(context.get(ClassLoader.class), null);
            scopeStack.push(scope);
            scope.addImport(packageName + ".*");
            return super.visitCompilationUnit(cut, p);
        }

        private String getThisInternalName(String simpleName) {
            simpleName = simpleName.replaceAll("\\.", "$");
            StringBuilder sb = new StringBuilder();
            Iterator<String> it = stack.descendingIterator();
            sb.append(packageName.replaceAll("\\.", "/"));
            sb.append("/");

            while (it.hasNext()) {
                sb.append(it.next()).append("$");
            }
            sb.append(simpleName);
            return sb.toString();
        }

        @Override
        public Object visitImport(ImportTree it, Object p) {
            if (!it.isStatic()) {
                String path = it.getQualifiedIdentifier().toString();
                scopeStack.peek().addImport(path);
            }
            return super.visitImport(it, p);
        }

        Object visitConstructor(final MethodTree mt, Object p) {
            ClassWriter classWriter = cwStack.peek();
            List<Type> argTypes = new ArrayList<Type>();
            boolean isVarArgs = false;
            for (VariableTree v : mt.getParameters()) {

                if (v.toString().endsWith("... " + v.getName())) {
                    isVarArgs = true;
                }
                String type = v.getType().toString();
                String fullType = type;
                String signature = null;
                try {
                    signature = TypeUtil.getTypeSignature(type, scopeStack.peek());
                } catch (Throwable t) {
                    System.out.println("Failed to find signature for type");
                }
                if (type.indexOf("<") != -1) {
                    type = type.substring(0, type.indexOf("<"));
                }
                int dim = 0;
                if (TypeUtil.isArrayType(type)) {
                    dim = TypeUtil.getArrayTypeDimension(type);
                    type = TypeUtil.getArrayElementType(type);
                }
                if (TypeUtil.isPrimitiveType(type)) {
                    String descriptor = TypeUtil.getDescriptor(type);
                    argTypes.add(Type.getType(TypeUtil.getArrayDescriptor(descriptor, dim)));
                } else {
                    ClassNode stub = scopeStack.peek().findStub(type);
                    assert stub != null;
                    argTypes.add(Type.getObjectType(stub.name));
                }

            }

            String methodDescriptor = null;
            String methodSignature = null;
            if (argTypes.isEmpty()) {
                methodDescriptor = Type.getMethodDescriptor(Type.getType("V"));
            } else {
                methodDescriptor = Type.getMethodDescriptor(Type.getType("V"), argTypes.toArray(new Type[0]));

            }

            int flags = getFlags(mt.getModifiers().getFlags());
            if (isVarArgs) {
                flags |= Opcodes.ACC_VARARGS;

            }
            classWriter.visitMethod(flags, mt.getName().toString(), methodDescriptor, null, null);
            classInfoStack.peek().numConstructors++;
            return null;
        }

        @Override
        public Object visitMethod(MethodTree mt, Object p) {
            if (mt.getReturnType() == null) {
                // It's a constructor
                return visitConstructor(mt, p);
            } else {
                boolean isVarArgs = false;
                ClassWriter classWriter = cwStack.peek();

                List<Type> argTypes = new ArrayList<>();
                List<String> sigArgTypes = new ArrayList<>();
                for (VariableTree v : mt.getParameters()) {
                    String type = v.getType().toString();
                    if (v.toString().endsWith("... " + v.getName())) {
                        isVarArgs = true;
                    }
                    sigArgTypes.add(type);
                    int dim = 0;
                    if (TypeUtil.isArrayType(type)) {
                        dim = TypeUtil.getArrayTypeDimension(type);
                        type = TypeUtil.getArrayElementType(type);
                    }
                    if (TypeUtil.isPrimitiveType(type)) {
                        String descriptor = TypeUtil.getDescriptor(type);
                        argTypes.add(Type.getType(TypeUtil.getArrayDescriptor(descriptor, dim)));
                    } else {

                        if (isGenericType(type)) {
                            type = "Object";
                        }

                        int arrowPos = type.indexOf("<");
                        if (arrowPos != -1) {
                            type = type.substring(0, arrowPos);
                        }
                        ClassNode stub = scopeStack.peek().findStub(type);
                        if (stub == null) {
                            throw new RuntimeException("Could not find class for " + type);
                        }
                        Type argType = Type.getObjectType(stub.name);
                        argType = Type.getType(TypeUtil.getArrayDescriptor(argType.getInternalName(), dim));
                        argTypes.add(argType);
                    }

                }

                String returnType = mt.getReturnType().toString();
                if (isGenericType(returnType)) {
                    returnType = "Object";
                }

                String methodSignature = null;
                try {
                    methodSignature = TypeUtil.getMethodSignature(scopeStack.peek(), returnType,
                            sigArgTypes.toArray(new String[0]));
                } catch (Exception ex) {
                    System.out.println(
                            "Failed to get signature for method " + mt + " message: " + ex.getMessage());
                }
                int dim = 0;

                Type returnTypeType = null;
                if (TypeUtil.isArrayType(returnType)) {
                    dim = TypeUtil.getArrayTypeDimension(returnType);
                    returnType = TypeUtil.getArrayElementType(returnType);
                    if (isGenericType(returnType)) {
                        returnType = "Object";
                    }

                }
                if (TypeUtil.isPrimitiveType(returnType)) {
                    String descriptor = TypeUtil.getDescriptor(returnType);
                    returnTypeType = Type.getType(TypeUtil.getArrayDescriptor(descriptor, dim));

                } else {
                    int arrowPos = returnType.indexOf("<");
                    if (arrowPos != -1) {
                        returnType = returnType.substring(0, arrowPos);
                    }
                    ClassNode stub = scopeStack.peek().findStub(returnType);
                    if (stub == null) {
                        System.out.println("Type params is " + mt.getTypeParameters());
                        System.out.println("Type kind is " + mt.getReturnType().getKind());
                        throw new RuntimeException("Could not find class for " + returnType);
                    }

                    returnTypeType = Type.getObjectType(stub.name);
                    returnTypeType = Type
                            .getType(TypeUtil.getArrayDescriptor(returnTypeType.getInternalName(), dim));

                }

                String methodDescriptor = null;
                if (argTypes.isEmpty()) {
                    methodDescriptor = Type.getMethodDescriptor(returnTypeType);
                } else {
                    methodDescriptor = Type.getMethodDescriptor(returnTypeType, argTypes.toArray(new Type[0]));
                }

                int flags = getFlags(mt.getModifiers().getFlags());
                if (isVarArgs) {
                    flags |= Opcodes.ACC_VARARGS;
                    //System.out.println("VarArgs "+flags);
                }
                classWriter.visitMethod(flags, mt.getName().toString(), methodDescriptor, methodSignature,
                        null);

            }
            //methodStack.push(mt);
            //Object out= super.visitMethod(mt, p); 
            //methodStack.pop();
            return null;
        }

        //private boolean LinkedList<MethodTree> methodStack  =new LinkedList<>();
        @Override
        public Object visitVariable(VariableTree vt, Object p) {

            ClassWriter classWriter = cwStack.peek();

            String varType = vt.getType().toString();
            if (isGenericType(varType)) {
                varType = "Object";
            }
            String signature = null;
            try {
                signature = TypeUtil.getTypeSignature(varType, scopeStack.peek());
            } catch (Exception ex) {
                System.out.println("Failed to generate signature for type " + varType);
            }
            int dim = 0;

            Type varTypeType = null;
            if (TypeUtil.isArrayType(varType)) {
                dim = TypeUtil.getArrayTypeDimension(varType);
                varType = TypeUtil.getArrayElementType(varType);

            }
            if (TypeUtil.isPrimitiveType(varType)) {
                String descriptor = TypeUtil.getDescriptor(varType);
                varTypeType = Type.getType(TypeUtil.getArrayDescriptor(descriptor, dim));

            } else {
                int arrowPos = varType.indexOf("<");
                if (arrowPos != -1) {
                    varType = varType.substring(0, arrowPos);
                }
                ClassNode stub = scopeStack.peek().findStub(varType);
                if (stub == null) {
                    throw new RuntimeException("Could not find class for " + varType);
                }

                varTypeType = Type.getObjectType(stub.name);
                varTypeType = Type.getType(TypeUtil.getArrayDescriptor(varTypeType.getInternalName(), dim));

            }

            classWriter.visitField(getFlags(vt.getModifiers().getFlags()), vt.getName().toString(),
                    varTypeType.toString(), signature, null);

            return super.visitVariable(vt, p); //To change body of generated methods, choose Tools | Templates.
        }

        boolean isGenericType(String type) {
            for (List<? extends TypeParameterTree> types : typeParametersStack) {
                for (TypeParameterTree tree : types) {
                    if (type.equals(tree.getName().toString())) {
                        return true;
                    }
                }
            }
            return false;
        }

        /**
         * Converts modifier flags from Javac Tree into int flags usable in 
         * TypeMirror
         * @param mods
         * @return 
         */
        int getFlags(Set<Modifier> mods) {
            int flags = 0;
            for (Modifier m : mods) {
                switch (m) {
                case ABSTRACT:
                    flags |= Opcodes.ACC_ABSTRACT;
                    break;
                case FINAL:
                    flags |= Opcodes.ACC_FINAL;
                    break;
                case PRIVATE:
                    flags |= Opcodes.ACC_PRIVATE;
                    break;
                case PROTECTED:
                    flags |= Opcodes.ACC_PROTECTED;
                    break;
                case PUBLIC:

                    flags |= Opcodes.ACC_PUBLIC;
                    break;
                case STATIC:
                    flags |= Opcodes.ACC_STATIC;
                    break;

                }
            }

            return flags;
        }

        @Override
        public Object visitClass(ClassTree ct, Object p) {
            //System.out.println("Visiting class "+ct);
            //System.out.println("Type parameters: "+ct.getTypeParameters());
            typeParametersStack.push(ct.getTypeParameters());
            String simpleName = ct.getSimpleName().toString();
            String internalName = getThisInternalName(simpleName);
            int lastDollar = internalName.lastIndexOf("$");
            String externalName = lastDollar == -1 ? null : internalName.substring(0, lastDollar);
            String supername = "java.lang.Object";
            String[] interfaces = null;
            boolean targetClass = false;
            if (!cwStack.isEmpty()) {
                cwStack.peek().visitInnerClass(internalName, externalName, simpleName,
                        getFlags(ct.getModifiers().getFlags()));
            }

            targetClass = true;
            // This is the one that we'
            //String supername = "java.lang.Object";
            if (ct.getExtendsClause() != null) {
                supername = ct.getExtendsClause().toString().trim();
            }
            String unresolvedSuperName = supername;

            int bracketPos = supername.indexOf("<");
            supername = bracketPos == -1 ? supername : supername.substring(0, bracketPos);
            ClassNode node = scopeStack.peek().findStub(supername);
            if (node == null) {
                throw new RuntimeException("Could not find super stub " + supername);
            }
            supername = node.name;

            String impl = ct.getImplementsClause().toString();
            String[] unresolvedInterfaces = null;
            if (impl != null && !"".equals(impl)) {
                interfaces = impl.split(",");
                unresolvedInterfaces = new String[interfaces.length];
                for (int i = 0; i < interfaces.length; i++) {

                    String iface = interfaces[i];
                    unresolvedInterfaces[i] = interfaces[i];
                    iface = iface.trim();
                    ClassNode inode = scopeStack.peek().findStub(iface);
                    assert inode != null;
                    if (inode == null) {
                        throw new RuntimeException("Could not find stub for interface " + iface);
                    }
                    System.out.println("interface " + iface);
                    interfaces[i] = inode.name;
                }
            }
            String signature = TypeUtil.getClassSignature(scopeStack.peek(), null, unresolvedSuperName,
                    unresolvedInterfaces);
            int flags = getFlags(ct.getModifiers().getFlags());

            switch (ct.getKind()) {
            case INTERFACE:
                flags |= Opcodes.ACC_INTERFACE;
                break;

            case ENUM:
                flags |= Opcodes.ACC_ENUM;
                break;

            }

            ClassWriter classWriter = new ClassWriter(49);
            classWriter.visit(49, flags, internalName, signature, supername, interfaces

            );
            cwStack.push(classWriter);
            classInfoStack.push(new ClassInfo());
            stack.push(simpleName);
            ClassFinder scope = new ClassFinder(context.get(ClassLoader.class), scopeStack.peek());

            scope.addImport(internalName.replaceAll("/", ".").replaceAll("\\$", ".") + ".*"

            );
            scope.addImport(internalName.replaceAll("/", ".").replaceAll("\\$", "."));
            scope.addImport(supername.replaceAll("/", ".").replaceAll("\\$", ".") + ".*"

            );
            scope.addImport(supername.replaceAll("/", ".").replaceAll("\\$", "."));

            if (interfaces != null) {
                for (int i = 0; i < interfaces.length; i++) {
                    scope.addImport(interfaces[i].replaceAll("/", ".").replaceAll("\\$", ".") + ".*"

                    );
                    scope.addImport(interfaces[i].replaceAll("/", ".").replaceAll("\\$", "."));
                }
            }
            for (TypeParameterTree tpTree : ct.getTypeParameters()) {
                //System.out.println("Name: "+tpTree.getName());
                //System.out.println("Kind: "+tpTree.getKind().name());
                //System.out.println("Bounds: "+tpTree.getBounds());
                String bounds = (tpTree.getBounds() != null && !tpTree.getBounds().isEmpty())
                        ? tpTree.getBounds().get(0).toString()
                        : "java.lang.Object";
                scope.addTypeParameter(tpTree.getName().toString(), bounds);
            }
            scopeStack.push(scope);
            Object out = super.visitClass(ct, p);
            stack.pop();
            scopeStack.pop();
            ClassInfo classInfo = classInfoStack.pop();
            if (classInfo.numConstructors == 0) {
                // there are no declared constructors in this class 
                // we need to add a default constructor.
                cwStack.peek().visitMethod(Opcodes.ACC_PUBLIC, "<init>",
                        Type.getMethodDescriptor(Type.getType("V")), null, null);
                classInfo.numConstructors++;
            }

            if (targetClass) {
                byte[] bytes = cwStack.peek().toByteArray();
                outMap.put(internalName, bytes);
                cwStack.pop();
            }

            typeParametersStack.pop();

            return out;
        }

    };
    scanner.scan(asts, null);
    return outMap;
}

From source file:ca.weblite.asm.TypeUtil.java

/**
 * Converts modifier flags from Javac Tree into int flags usable in TypeMirror
 * @param mods/*from  w ww . java  2 s  .  co  m*/
 * @return 
 */
public static int getFlags(Set<Modifier> mods) {
    int flags = 0;
    for (Modifier m : mods) {
        switch (m) {
        case ABSTRACT:
            flags |= Opcodes.ACC_ABSTRACT;
            break;
        case FINAL:
            flags |= Opcodes.ACC_FINAL;
            break;
        case PRIVATE:
            flags |= Opcodes.ACC_PRIVATE;
            break;
        case PROTECTED:
            flags |= Opcodes.ACC_PROTECTED;
            break;
        case PUBLIC:

            flags |= Opcodes.ACC_PUBLIC;
            break;
        case STATIC:
            flags |= Opcodes.ACC_STATIC;
            break;

        }
    }

    return flags;
}

From source file:ca.weblite.mirah.ant.mirrors.ClassReader.java

/**
 * Generates the the mirah mirrors for a specific java source file.  This 
 * file must be a .java file.  It cannot be a directory.
 * // w  w w. ja v a2  s  .  c  o m
 * @param javaSourceFile
 * @throws IOException 
 */
public void parse() throws IOException {

    File javaSourceFile = sourceFile;
    JavaCompiler compiler = JavacTool.create();
    MyFileObject[] fos = new MyFileObject[] { new MyFileObject(javaSourceFile) };

    JavacTask task = (JavacTask) compiler.getTask(null, null, null, null, null, Arrays.asList(fos));
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    final Stack<Set<String>> typeParams = new Stack<Set<String>>();
    TreePathScanner scanner;
    scanner = new TreePathScanner() {

        private boolean isGenericType(String type) {
            Stack<Set> desk = new Stack<Set>();
            boolean found = false;
            while (!typeParams.empty()) {
                Set params = typeParams.pop();
                desk.push(params);
                if (params.contains(type)) {
                    found = true;

                    break;
                }

            }
            while (!desk.empty()) {
                typeParams.push(desk.pop());
            }
            return found;
        }

        String formatType(String type) {
            int pos = type.indexOf("<");
            if (pos >= 0) {
                type = type.substring(0, pos);
            }
            if (isGenericType(type)) {
                return "Object";
            }
            return type;
        }

        @Override
        public Object visitCompilationUnit(CompilationUnitTree cut, Object p) {
            PackageScope scope = new PackageScope(scopeStack.peek(), cut.getPackageName().toString());
            scope.addImport(scope.getPackageName() + ".*");
            scope.addImport("java.lang.*");
            scope.addImport("*");
            packageScope = scope;
            scopeStack.push(scope);
            return super.visitCompilationUnit(cut, p);

        }

        @Override
        public Object visitImport(ImportTree it, Object p) {

            String path = it.getQualifiedIdentifier().toString();
            packageScope.addImport(path);

            return super.visitImport(it, p);
        }

        private void decorateClassNode(ClassTree ct, ClassNode classNode) {
            int flags = getFlags(ct.getModifiers().getFlags());
            switch (ct.getKind()) {
            case INTERFACE:
                flags |= Opcodes.ACC_INTERFACE;
                break;

            case ENUM:
                flags |= Opcodes.ACC_ENUM;
                break;

            }
            classNode.access = flags;
            classNode.sourceFile = sourceFile.getPath();
            String extendsClause = "java.lang.Object";
            if (ct.getExtendsClause() != null) {
                extendsClause = ct.getExtendsClause().toString();
            }

            String superPath = scopeStack.peek().resolveName(extendsClause, false);

            ClassIndex.Node superNode = scopeStack.peek().getLoader().find(superPath);

            if (superNode == null) {
                throw new RuntimeException("Failed to find super class " + superPath);
            }

            classNode.superName = superNode.internalName;

            classNode.interfaces = new ArrayList<String>();
            String impl = ct.getImplementsClause().toString();
            if (!"".equals(impl)) {
                String[] interfaces = impl.split(",");
                for (String iface : interfaces) {
                    iface = iface.trim();
                    String ipath = scopeStack.peek().resolveName(iface, false);
                    ClassIndex.Node iNode = scopeStack.peek().getLoader().find(ipath);
                    if (iNode == null) {
                        throw new RuntimeException("Failed to load " + "interface " + ipath);
                    }

                    classNode.interfaces.add(iNode.internalName);
                }
            }
        }

        @Override
        public Object visitClass(ClassTree ct, Object p) {
            ClassScope clsScope = null;
            ClassNode currClassNode = null;
            if (scopeStack.peek() == packageScope) {
                String path = packageScope.getPackageName() + "." + ct.getSimpleName();
                ClassIndex.Node n = packageScope.getLoader().find(path);
                if (n == null) {
                    throw new RuntimeException("Failed to find class " + path);
                }
                node.name = n.internalName;
                currClassNode = node;
                decorateClassNode(ct, node);

                clsScope = new ClassScope(scopeStack.peek(), n);

            } else {
                // This must be an internal class
                ClassNode parentClass = classNodeStack.peek();
                if (parentClass.innerClasses == null) {
                    parentClass.innerClasses = new ArrayList<>();
                }
                String path = scopeStack.peek().resolveName(ct.getSimpleName().toString(), false);

                ClassIndex.Node n = packageScope.getLoader().find(path);
                if (n == null) {
                    throw new RuntimeException("Failed to find class " + path);
                }
                InnerClassNode innerNode = new InnerClassNode(n.internalName, parentClass.name, n.simpleName,
                        getFlags(ct.getModifiers().getFlags()));
                parentClass.innerClasses.add(innerNode);

                ClassNode cls = new ClassNode();
                cls.name = n.internalName;
                cls.outerClass = parentClass.name;

                decorateClassNode(ct, cls);
                clsScope = new ClassScope(scopeStack.peek(), n);
                currClassNode = cls;
            }

            scopeStack.push(clsScope);
            classNodeStack.push(currClassNode);
            Object out = super.visitClass(ct, p);
            classNodeStack.pop();
            scopeStack.pop();

            return out;

        }

        /**
         * Converts modifier flags from Javac Tree into int flags usable in 
         * TypeMirror
         * @param mods
         * @return 
         */
        int getFlags(Set<Modifier> mods) {
            int flags = 0;
            for (Modifier m : mods) {
                switch (m) {
                case ABSTRACT:
                    flags |= Opcodes.ACC_ABSTRACT;
                    break;
                case FINAL:
                    flags |= Opcodes.ACC_FINAL;
                    break;
                case PRIVATE:
                    flags |= Opcodes.ACC_PRIVATE;
                    break;
                case PROTECTED:
                    flags |= Opcodes.ACC_PROTECTED;
                    break;
                case PUBLIC:

                    flags |= Opcodes.ACC_PUBLIC;
                    break;
                case STATIC:
                    flags |= Opcodes.ACC_STATIC;
                    break;
                }
            }

            return flags;
        }

        @Override
        public Object visitVariable(final VariableTree vt, Object p) {
            String typeName = vt.getType().toString();
            String typePath = scopeStack.peek().resolveName(vt.getType().toString(), false);
            String typeDescriptor = scopeStack.peek().resolveName(vt.getType().toString(), true);
            String name = vt.getName().toString();
            int flags = getFlags(vt.getModifiers().getFlags());

            FieldNode fieldNode = new FieldNode(flags, name, typeDescriptor, null, null);

            ClassNode cls = classNodeStack.peek();
            if (cls.fields == null) {
                cls.fields = new ArrayList<FieldNode>();

            }
            cls.fields.add(fieldNode);

            return super.visitVariable(vt, p);
        }

        String generateMethodDescriptor(MethodTree mt) {
            StringBuilder sb = new StringBuilder();
            sb.append("(");
            for (VariableTree v : mt.getParameters()) {
                String type = scopeStack.peek().resolveName(v.getType().toString(), true);
                sb.append(type);

            }
            sb.append(")");
            String returnType = scopeStack.peek().resolveName(mt.getReturnType().toString(), true);
            sb.append(returnType);

            return sb.toString();
        }

        @Override
        public Object visitMethod(final MethodTree mt, Object p) {

            MethodNode m = new MethodNode();

            int flags = getFlags(mt.getModifiers().getFlags());
            m.access = flags;
            m.desc = generateMethodDescriptor(mt);
            m.name = mt.getName().toString();
            ClassNode cls = classNodeStack.peek();
            if (cls.methods == null) {
                cls.methods = new ArrayList<MethodNode>();
            }
            cls.methods.add(m);

            return mt;
        }
    };
    scanner.scan(asts, null);

}

From source file:ca.weblite.mirah.ant.mirrors.ClassReaderTest.java

@Test
public void testParseClass() throws IOException {
    ClassNode node = new ClassNode();
    ResourceLoader loader = new ResourceLoader();

    System.out.println(System.getProperties());
    loader.setClassPath(System.getProperty("sun.boot.class.path") + File.pathSeparator
            + System.getProperty("java.class.path"));
    loader.setJavaSourcePath("test");
    File file = new File("test/ca/weblite/mirah/ant/mirrors/SampleJavaClass.java");
    loader.fillIndex();//  w w  w .j a  v a2s. c  o m
    assertTrue("java.util.Map not found", loader.find("java.util.Map") != null);
    ClassReader reader = new ClassReader(node, file, loader);
    reader.parse();

    assertEquals("Class name is incorrect", "ca/weblite/mirah/ant/mirrors/SampleJavaClass", node.name);

    boolean foundSomeField = false;
    boolean foundObjField = false;
    boolean foundPrivateField = false;
    boolean foundPublicField = false;
    boolean foundProtectedField = false;
    for (Object o : node.fields) {
        FieldNode n = (FieldNode) o;
        System.out.println("Field " + n.name + " desc " + n.desc);
        if ("someField".equals(n.name) && "I".equals(n.desc)) {
            foundSomeField = true;
        }
        if ("someObjField".equals(n.name) && "Ljava/lang/Object;".equals(n.desc)) {
            foundObjField = true;
            assertTrue("someObjeField is not public", ((n.access & Opcodes.ACC_PUBLIC) == 0));
            assertTrue("someObjeField is not private", ((n.access & Opcodes.ACC_PRIVATE) == 0));
            assertTrue("someObjeField is not protected", ((n.access & Opcodes.ACC_PROTECTED) == 0));
            assertTrue("someObjeField is not abstract", ((n.access & Opcodes.ACC_ABSTRACT) == 0));
            assertTrue("someObjeField is not static", ((n.access & Opcodes.ACC_STATIC) == 0));
        }

        if ("privateField".equals(n.name) && "Ljava/lang/Object;".equals(n.desc)) {
            foundPrivateField = true;
            assertTrue("privateField is not public", ((n.access & Opcodes.ACC_PUBLIC) == 0));
            assertTrue("privateField should be private", ((n.access & Opcodes.ACC_PRIVATE) != 0));
            assertTrue("privateField is not protected", ((n.access & Opcodes.ACC_PROTECTED) == 0));
            assertTrue("privateField is not abstract", ((n.access & Opcodes.ACC_ABSTRACT) == 0));
            assertTrue("privateField is not static", ((n.access & Opcodes.ACC_STATIC) == 0));
        }

        if ("protectedField".equals(n.name) && "Ljava/lang/Object;".equals(n.desc)) {
            foundProtectedField = true;
            assertTrue("protectedField should not public", ((n.access & Opcodes.ACC_PUBLIC) == 0));
            assertTrue("protectedField should not be private", ((n.access & Opcodes.ACC_PRIVATE) == 0));
            assertTrue("protectedField should be protected", ((n.access & Opcodes.ACC_PROTECTED) != 0));
            assertTrue("protectedField should not be abstract", ((n.access & Opcodes.ACC_ABSTRACT) == 0));
            assertTrue("protectedField should not static", ((n.access & Opcodes.ACC_STATIC) == 0));
        }

        if ("publicField".equals(n.name) && "Ljava/lang/Object;".equals(n.desc)) {
            foundPublicField = true;
            assertTrue("publicField should be public", ((n.access & Opcodes.ACC_PUBLIC) != 0));
            assertTrue("publicField should not be private", ((n.access & Opcodes.ACC_PRIVATE) == 0));
            assertTrue("publicField should not be protected", ((n.access & Opcodes.ACC_PROTECTED) == 0));
            assertTrue("publicField should not be abstract", ((n.access & Opcodes.ACC_ABSTRACT) == 0));
            assertTrue("publicField should not static", ((n.access & Opcodes.ACC_STATIC) == 0));
        }
    }
    assertTrue("someField was not found", foundSomeField);
    assertTrue("object field was not found", foundObjField);
    assertTrue("private field was not found", foundPrivateField);
    assertTrue("public field was not found", foundPublicField);
    assertTrue("protected field was not found", foundProtectedField);
}

From source file:ch.sourcepond.utils.podescoin.internal.Access.java

License:Apache License

public static boolean isProtected(final int access) {
    return (access & Opcodes.ACC_PROTECTED) != 0;
}

From source file:Client.JClassPatcher.java

License:Open Source License

private String decodeAccess(int access) {
    String res = "";

    if ((access & Opcodes.ACC_PUBLIC) == Opcodes.ACC_PUBLIC)
        res += "public ";
    if ((access & Opcodes.ACC_PRIVATE) == Opcodes.ACC_PRIVATE)
        res += "private ";
    if ((access & Opcodes.ACC_PROTECTED) == Opcodes.ACC_PROTECTED)
        res += "protected ";

    if ((access & Opcodes.ACC_STATIC) == Opcodes.ACC_STATIC)
        res += "static ";
    if ((access & Opcodes.ACC_FINAL) == Opcodes.ACC_FINAL)
        res += "final ";
    if ((access & Opcodes.ACC_VOLATILE) == Opcodes.ACC_VOLATILE)
        res += "protected ";
    if ((access & Opcodes.ACC_SYNCHRONIZED) == Opcodes.ACC_SYNCHRONIZED)
        res += "synchronized ";
    if ((access & Opcodes.ACC_ABSTRACT) == Opcodes.ACC_ABSTRACT)
        res += "abstract ";
    if ((access & Opcodes.ACC_INTERFACE) == Opcodes.ACC_INTERFACE)
        res += "interface ";

    return res;//  www.  j  ava  2s .co  m
}