Example usage for org.aspectj.apache.bcel.classfile ClassParser ClassParser

List of usage examples for org.aspectj.apache.bcel.classfile ClassParser ClassParser

Introduction

In this page you can find the example usage for org.aspectj.apache.bcel.classfile ClassParser ClassParser.

Prototype

public ClassParser(String file_name) throws IOException 

Source Link

Document

Parse class from given .class file

Usage

From source file:br.jabuti.criteria.AllNodes.java

License:Open Source License

public static void main(String args[]) throws Exception {
    JavaClass java_class;
    java_class = new ClassParser(args[0]).parse(); // May throw IOException
    ConstantPoolGen cp = new ConstantPoolGen(java_class.getConstantPool());

    ClassGen cg = new ClassGen(java_class);

    Method[] methods = java_class.getMethods();
    for (int i = 0; i < methods.length; i++) {
        System.out.println("\n\n--------------------------");
        System.out.println(methods[i].getName());
        System.out.println("--------------------------");
        MethodGen mg = new MethodGen(methods[i], java_class.getClassName(), cp);

        CFG g = new CFG(mg, cg);

        AllNodes an = new AllNodes(g);

        System.out.println("Number of Requirements: " + an.getNumberOfRequirements());

        System.out.println("Number of Possible Requirements: " + an.getNumberOfPossibleRequirements());

        Object[] reqs = an.getRequirements();
        System.out.println("Requirements: ");

        for (int j = 0; j < reqs.length; j++) {
            Requirement req = (Requirement) reqs[j];
            System.out.print(req);
            System.out.print(" active: ");
            if (an.isActive(req)) {
                System.out.print("true");
            } else {
                System.out.print("false");
            }//from w ww.j a  v a  2  s .  c o m

            System.out.print(" covered: ");
            if (an.isCovered(req)) {
                System.out.print("true");
            } else {
                System.out.print("false");
            }

            System.out.print(" feasible: ");
            if (an.isFeasible(req)) {
                System.out.print("true");
            } else {
                System.out.print("false");
            }
            System.out.println();
        }
        System.out.println();

        an.addPath(new String[] { "0", "4" }, "path 1");
        an.addPath(new String[] { "0", "48", "207" }, "path 3");
        an.addPath(new String[] { "0", "76", "207" }, "path 2");

        int[] cv = an.getCoverage();
        System.out.println();

        System.out.println("Number of Possible Covered Requirements: " + an.getNumberOfPossibleCovered());

        HashSet hs = an.getCoveredRequirements();
        if (hs.isEmpty())
            System.out.println("No covered requirement.");
        else
            System.out.println("There are covered requirements.");

        hs = an.getPossibleCoveredRequirements();
        if (hs.isEmpty())
            System.out.println("No possible covered requirement.");
        else
            System.out.println("There are possible covered requirements.");

        System.out.println("Covered: ");
        for (int j = 0; j < cv.length; j++) {
            System.out.print(cv[j] + "  ");
        }
        System.out.println();

        hs = an.getCoveredRequirements("path 1");
        System.out.println("Covered requirements by Path 1");
        Iterator it = hs.iterator();
        while (it.hasNext()) {
            System.out.print(it.next() + " ");
        }

        // Marcando todos os requisitos como inativos e reativando-os
        for (int j = 0; j < reqs.length; j++) {
            an.setInactive((Requirement) reqs[j]);
        }
        hs = an.getInactiveRequirements();
        for (int j = 0; j < reqs.length; j++) {
            an.setActive((Requirement) reqs[j]);
        }

        // Marcando todos os requisitos como infeasible e reativando-os
        for (int j = 0; j < reqs.length; j++) {
            an.setInfeasible((Requirement) reqs[j]);
        }
        hs = an.getInfeasibleRequirements();
        for (int j = 0; j < reqs.length; j++) {
            an.setFeasible((Requirement) reqs[j]);
        }

        // Obtendo os requisitos por meio de seus rtulos
        /* for (int j = 0; j < req.length; j++) {
            Object o = an.getRequirementByLabel( req[j].toString() );
         }
         */

        // Removendo um caso de teste
        an.removePath("path 2");

        // Removendo todos os casos de teste
        an.removeAllPaths();
    }
}

From source file:br.jabuti.graph.datastructure.ig.InstructionGraph.java

License:Open Source License

/** A driver for testing the class. Creates the graph and calls
 * {@link InstructionGraph#calcStack}. The arguments determine
 * to which methods to apply./*www  . j a  va  2s . co  m*/
 *
 * @param args[0] A file name. Can be a classfile, a jar file or a
 * zip file. If jar or zip, the second and third arguments does not apply.
 * In this case, the output is only the name of the classes and of the
 * methods in the class. The test is applyied in all the listed
 * methods. If this is a single class file name, the output will be
 * the complete graph (as presented by {InstructionNode#print}) for
 * each selected method.
 * @param args[1] The name of a method. The test is applyed to all
 * methods in the class that match this name.
 * @param args[2] The signature of a method. Used to select one
 * between several homonymous methods.
 */

public static void main(String args[]) throws Exception {
    boolean all = true;
    String filename = args[0];
    ZipFile jf = null;

    if (filename.endsWith(".jar")) {
        jf = new JarFile(filename);
    } else if (filename.endsWith(".zip")) {
        jf = new ZipFile(filename);
    }

    if (jf == null) {
        JavaClass java_class;

        java_class = new ClassParser(filename).parse(); // May throw IOException

        ConstantPoolGen cp = new ConstantPoolGen(java_class.getConstantPool());
        Method[] methods = java_class.getMethods();

        for (int i = 0; i < methods.length; i++) {
            if (args.length >= 2 && (!args[1].equals(methods[i].getName()))) {
                continue;
            }
            if (args.length >= 3 && (!args[2].equals(methods[i].getSignature()))) {
                continue;
            }
            System.out.println("--------------------------");
            System.out.println(methods[i].getName());
            System.out.println(methods[i].getSignature());
            System.out.println("--------------------------");
            MethodGen mg = new MethodGen(methods[i], java_class.getClassName(), cp);

            if (mg.getInstructionList() == null) {
                continue;
            }
            InstructionGraph g = new InstructionGraph(mg);

            // g.calcReqLocal();
            g.calcStack(all);
            g.print(System.out);
        }
        return;
    }

    Enumeration en = jf.entries();
    ZipEntry ze = null;

    while (en.hasMoreElements()) {
        ze = (ZipEntry) en.nextElement();
        if (!ze.getName().endsWith(".class")) {
            System.out.println("Not a class file: " + ze.getName());
            continue;
        }

        System.out.println("\n\n**************************");
        System.out.println(ze.getName());
        System.out.println("**************************");

        JavaClass java_class;

        java_class = new ClassParser(jf.getInputStream(ze), ze.getName()).parse(); // May throw IOException

        ConstantPoolGen cp = new ConstantPoolGen(java_class.getConstantPool());
        Method[] methods = java_class.getMethods();

        for (int i = 0; i < methods.length; i++) {
            System.out.println("Memory : " + Runtime.getRuntime().freeMemory());
            System.out.println("--------------------------");
            System.out.println(methods[i].getName());
            System.out.println("--------------------------");
            MethodGen mg = new MethodGen(methods[i], java_class.getClassName(), cp);

            if (mg.getInstructionList() == null) {
                continue;
            }
            InstructionGraph g = new InstructionGraph(mg);

            // g.calcReqLocal();
            g.calcStack(all);
            System.out.println("Memory : " + Runtime.getRuntime().freeMemory());
            g = null;
            System.out.println("Collecting garbage...");
            System.out.println();

        }
    }
}

From source file:br.jabuti.instrumenter.bytecode.bcel.ASMInstrumenter.java

License:Open Source License

/**
 * This is a test driver. It takes a class name on args[0], inserts
 * some instructions in several points of each method in the class
 * and then dump the instrumented class to "new_"<original_name> 
 * file/* w w  w  .ja v a  2  s  .  com*/
 */

public static void main(String args[]) throws Exception {
    // o melhor eh chamar com java ... ASMInstrumenter samples\arquivo.class
    // assim ele vai criar um novo arquivo new_samples\arquivo.class que
    // se pode testar

    JavaClass java_class;

    if ((java_class = Repository.lookupClass(args[0])) == null) {
        java_class = new ClassParser(args[0]).parse();
    } // May throw IOException

    ClassGen cg = new ClassGen(java_class);
    ConstantPoolGen cp = cg.getConstantPool();
    Method[] methods = cg.getMethods();

    for (int i = 0; i < methods.length; i++) {
        try {
            System.out.println("\n\n--------------------------");
            System.out.println(methods[i].getName());
            System.out.println("--------------------------");
            MethodGen mg = new MethodGen(methods[i], cg.getClassName(), cp);
            ASMInstrumenter gi = new ASMInstrumenter(mg, cg, cp);
            int nvars = mg.getMaxLocals() + 10;

            String s = "GETSTATIC java.lang.System out \"Ljava/io/PrintStream;\"  " + "astore " + nvars + " ";
            String s2 = "aload " + nvars + " ";
            String s3 = "LDC \"Entrando no metodo " + mg.getName() + "\" ";
            String s4 = "LDC \"Saindo do metodo " + mg.getName() + "\\n \" ";
            String s5 = "invokevirtual java.io.PrintStream println " + "\"(Ljava/lang/Object;)V\" ";

            gi.insertBefore(mg.getInstructionList().getStart(), s + s2 + s3 + s5);
            gi.insertBefore(mg.getInstructionList().getEnd(), s2 + s4 + s5);
            methods[i] = mg.getMethod();
        } catch (ParseException e) {
            System.err.println("Parser error " + e.getMessage());
        }
    }
    cg.setMethods(methods);
    java_class = cg.getJavaClass();
    java_class.dump("new_" + args[0]);
}

From source file:br.jabuti.lookup.java.bytecode.ClassClosure.java

License:Open Source License

/**
 *   Method responsable to parse the code of a given class name and found a list
 *   of all classes related with this one. In this list will be included neither system class
 *    if the variable <code> noSys </code> is true nor the ones spaecified in <code>toAvoid</code>.
 *
 *   @param className The name of the starting class. From it all the
 *   referenced classes are found and included in the structure. The
 *   class should be found in the classpath
 *
 *   @param noSys This param tells whether "system" classes should be part
 *   of the main program structure or just as peripheral classes. If
 *   <code>true</code>, classes with the following prefix are kept out
 *   of the main structure:<BR>/*from  w  w  w . j  a v  a2  s .  co  m*/
 *   <UL>
 *       <LI> java.
 *       <LI> javax.lang
 *       <LI> org.omg
 *   </UL> <BR>
 *   In addition, any referenced class for wich the code (a .class) file
 *   can not be found is considered out of the main structure.
 *
 *   @param toAvoid This is a string that indicates other classes that should be
 *   avoided in the main structure of the program. For example, if the
 *   program uses library packages <code>org.dummy</code> and
 *   <code>br.din.foo</code> the use of "org.dummy br.din.foo" as the third
 *   argument will keep the classes in these packages out of the program
 *   structure, even if their class files can be found in the classpath
 */
public String[] getClosure(String className, boolean noSys, String toAvoid) {
    String s = className;

    JavaClass classFile = null;

    s = findFile(s);
    if (s == null) {
        return new String[0];
    }
    try {
        classFile = new ClassParser(s).parse();
        String pck = RClass.getPackName(className);

        if (!pck.equals(classFile.getPackageName())) {
            Debug.D(pck + " " + classFile.getPackageName() + " " + pck.equals(classFile.getPackageName()));
            return new String[0];
        }
    } catch (IOException e) {
        return new String[0];
    }
    return getJCClosure(classFile, noSys, toAvoid);
}

From source file:br.jabuti.lookup.java.bytecode.ClassClosure.java

License:Open Source License

public String[] getJCClosure(JavaClass classFile, boolean noSys, String toAvoid) {
    Hashtable interestedClasses = new Hashtable();
    Vector classesToProcess = new Vector();
    Vector classesToAvoid = new Vector();

    if (!doMatch(classFile.getClassName(), noSys, toAvoid)) {
        interestedClasses.put(classFile.getClassName(), classFile);
        classesToProcess.add(classFile);
    } else {/* w  ww . jav a 2s .co  m*/
        classesToAvoid.add(classFile.getClassName());
    }
    for (int i = 0; i < classesToProcess.size(); i++) {
        classFile = (JavaClass) classesToProcess.elementAt(i);

        String[] cl = accessedClasses(classFile);

        for (int j = 0; j < cl.length; j++) {
            try {
                if (!doMatch(cl[j], noSys, toAvoid)) { // May throw IOException
                    String h = findFile(cl[j]);

                    if (h != null) {
                        classFile = new ClassParser(h).parse();
                        String pck = RClass.getPackName(cl[j]);

                        if (pck.equals(classFile.getPackageName())
                                && (!interestedClasses.containsKey(classFile.getClassName()))) {
                            classesToProcess.add(classFile);
                            interestedClasses.put(classFile.getClassName(), classFile);
                        }
                    }
                }
            } catch (FileNotFoundException e) {// System.out.println("Skipped " + s1);
            } catch (IOException e) {// System.out.println("Skipped " + s1);
            }
            if (!classesToAvoid.contains(cl[j])) {
                classesToAvoid.add(cl[j]);
            }
        }
    }
    return (String[]) classesToAvoid.toArray(new String[0]);
}