List of usage examples for org.aspectj.apache.bcel.generic ClassGen ClassGen
public ClassGen(JavaClass clazz)
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"); }/* w ww . j a va 2 s . co 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.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//from w ww .j av a2 s . c o m */ 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.metrics.klass.MetricCCAVG.java
License:Open Source License
@Override public double getResult(Program prog, String className) { double theValue = 0.0; RClass rc = prog.get(className);//from ww w . j a v a 2 s . co m if (!(rc instanceof RClassCode)) { return -1.0; } RClassCode rcc = (RClassCode) rc; JavaClass theClazz = rcc.getTheClass(); ConstantPoolGen cp = new ConstantPoolGen(theClazz.getConstantPool()); ClassGen cg = new ClassGen(theClazz); Method[] methods = theClazz.getMethods(); int k = 0; for (int i = 0; i < methods.length; i++) { if (methods[i].isAbstract()) { continue; } MethodGen mg = new MethodGen(methods[i], theClazz.getClassName(), cp); double d = getCyclomaticComplexity(mg, cg); if (d < 0.0) { return -1; } theValue += d; k++; } return k > 0 ? theValue / k : 0.0; }
From source file:br.jabuti.metrics.klass.MetricCCMAX.java
License:Open Source License
@Override public double getResult(Program prog, String className) { double theValue = 0.0; RClass rc = prog.get(className);/*from w w w. j a v a 2 s . c o m*/ if (!(rc instanceof RClassCode)) { return -1.0; } RClassCode rcc = (RClassCode) rc; JavaClass theClazz = rcc.getTheClass(); ConstantPoolGen cp = new ConstantPoolGen(theClazz.getConstantPool()); ClassGen cg = new ClassGen(theClazz); Method[] methods = theClazz.getMethods(); for (int i = 0; i < methods.length; i++) { if (methods[i].isAbstract()) { continue; } MethodGen mg = new MethodGen(methods[i], theClazz.getClassName(), cp); double d = getCyclomaticComplexity(mg, cg); if (d < 0.0) { return -1; } theValue = (d > theValue) ? d : theValue; } return theValue; }
From source file:br.jabuti.metrics.klass.MetricLCOM.java
License:Open Source License
protected double lcom(Program prog, String className, boolean isStatic) { RClass rc = prog.get(className);/* w ww .j a v a 2 s .co m*/ if (!(rc instanceof RClassCode)) { return -1.0; } List<Collection<CFGNode>> dmethod = new ArrayList<Collection<CFGNode>>(); RClassCode rcc = (RClassCode) rc; JavaClass theClazz = rcc.getTheClass(); ConstantPoolGen cp = new ConstantPoolGen(theClazz.getConstantPool()); ClassGen cg = new ClassGen(theClazz); Method[] methods = theClazz.getMethods(); for (int i = 0; i < methods.length; i++) { if (methods[i].isAbstract()) { continue; } if (methods[i].isStatic()) { continue; } MethodGen mg = new MethodGen(methods[i], theClazz.getClassName(), cp); CFG g = null; try { g = getCFG(mg, cg); } catch (Exception e) { return -1.0; } Collection<CFGNode> defUses = findDefUse(g); // keeps only the non static accesses for (Iterator<CFGNode> it = defUses.iterator(); it.hasNext();) { CFGNode node = it.next(); String s = it.toString(); if (!s.startsWith("L@0.")) { it.remove(); } } dmethod.add(defUses); } int doShare = 0, notShare = 0; // now compare the methods for (int i = 0; i < dmethod.size() - 1; i++) { Collection v = (Collection) dmethod.get(i); r1: for (int j = i + 1; j < dmethod.size(); j++) { Collection v1 = (Collection) dmethod.get(j); for (Iterator it1 = v.iterator(); it1.hasNext();) { String s = (String) it1.next(); if (v1.contains(s)) { Debug.D("Methods " + i + " and " + j + " share " + s); doShare++; continue r1; } } Debug.D("Methods " + i + " and " + j + " do not share "); notShare++; } } double lcom = (double) notShare - doShare; return lcom >= 0 ? lcom : 0.0; }
From source file:br.jabuti.metrics.klass.MetricRFC.java
License:Open Source License
@Override public double getResult(Program prog, String className) { RClass rc = prog.get(className);/*from w w w .j a va2s .co m*/ if (!(rc instanceof RClassCode)) { return -1.0; } RClassCode rcc = (RClassCode) rc; JavaClass theClazz = rcc.getTheClass(); ConstantPoolGen cp = new ConstantPoolGen(theClazz.getConstantPool()); ClassGen cg = new ClassGen(theClazz); Method[] methods = theClazz.getMethods(); int theValue = 0; for (Method method : methods) { if (method.isAbstract()) { continue; } MethodGen mg = new MethodGen(method, theClazz.getClassName(), cp); CFG g = null; try { g = getCFG(mg, cg); } catch (Exception e) { return -1.0; } Set<String> hs = new HashSet<String>(); for (int j = 0; j < g.size(); j++) { CFGNode gn = (CFGNode) g.get(j); if (!(gn instanceof GraphCallNode)) { continue; } GraphCallNode gcn = (GraphCallNode) gn; for (int h = 0; h < gcn.getClasse().length; h++) { hs.add(gcn.getClasse()[h] + gcn.getName()); } } theValue += hs.size(); theValue++; } return (double) theValue; }
From source file:br.jabuti.metrics.klass.MetricWMCCC.java
License:Open Source License
@Override public double getResult(Program prog, String className) { double theValue = 0.0; RClass rc = prog.get(className);/*from www. ja v a 2 s . c o m*/ if (!(rc instanceof RClassCode)) { return -1.0; } RClassCode rcc = (RClassCode) rc; JavaClass theClazz = rcc.getTheClass(); ConstantPoolGen cp = new ConstantPoolGen(theClazz.getConstantPool()); ClassGen cg = new ClassGen(theClazz); Method[] methods = theClazz.getMethods(); for (int i = 0; i < methods.length; i++) { if (methods[i].isAbstract()) { continue; } MethodGen mg = new MethodGen(methods[i], theClazz.getClassName(), cp); double d = getCyclomaticComplexity(mg, cg); if (d < 0.0) { return -1; } theValue += d; } return theValue; }
From source file:br.jabuti.probe.desktop.DefaultProbeInsert.java
License:Open Source License
private JavaClass doDefaultInstrument(JavaClass java_class, String className) throws InvalidInstructionException, InvalidStackArgument { ClassGen cg = new ClassGen(java_class); ConstantPoolGen cp = cg.getConstantPool(); Method[] methods = cg.getMethods(); // System.out.println( "Instrumenting class: " + className + // " cfg option: " + typeOfCFG ); for (int i = 0; i < methods.length; i++) { try {//w ww .j av a 2 s .c om MethodGen mg = new MethodGen(methods[i], cg.getClassName(), cp); // System.out.println( "\tCurrent method: " + mg.getName() ); // does not instrument static initializations or abstract methods if ((methods[i].getName().equals("<clinit>")) || (methods[i].isAbstract())) { continue; } InstructionList il = mg.getInstructionList(); InstructionHandle[] ihVec = il.getInstructionHandles(); int[] ihOffset = il.getInstructionPositions(); ASMInstrumenter gi = new ASMInstrumenter(mg, cg, cp); int nextLocal = mg.getMaxLocals() + 1; CFG gfc = new CFG(mg, cg); // gfc.releaseInstructionGraph(); // free some memory HashSet jahFoi = new HashSet(); // controla quas nos jah foram instrumentados // insert probes at the end of each node in a constructor if (methods[i].getName().equals("<init>")) { CFGNode superNode = null; // acha a chamada ao super for (int m = 0; m < gfc.size(); m++) { CFGNode ey = (CFGNode) gfc.elementAt(m); if (ey instanceof CFGSuperNode) { superNode = ey; break; } } // acha os nos que veem antes da chamada ao super // System.out.println( "Instrumentando classe: " + cg.getClassName() ); // System.out.println( gfc ); gfc.findIDFT(false, superNode); InstructionHandle ih = InstructionList.findHandle(ihVec, ihOffset, ihOffset.length, superNode.getEnd()); gi.insertAfter(ih, "aload_0 " + // empilha o objeto " ldc \"" + className + "\"" + // empilha o nome da classe " ldc " + i + // empilha o numero do metodo " lconst_0 " + // empilha aninhamento que para construtor // eh sempre 0 " ldc " + // empilha o numero do no "\"" + superNode.getNumber() + "\" " + "invokestatic " + getProbeClass() + " probe \"(Ljava/lang/Object;" + "Ljava/lang/String;IJLjava/lang/Object;)V\""); jahFoi.add(ih); // coloca a instrumentacao em cada no for (int m = 0; m < gfc.size(); m++) { CFGNode ey = (CFGNode) gfc.elementAt(m); // if marked means it is befor the super if (ey.getMark()) { continue; } ih = InstructionList.findHandle(ihVec, ihOffset, ihOffset.length, ey.getStart()); // System.out.println("No: " + ey); // System.out.println("Inicio do noh: " + ih); // System.out.println("Inicio do noh: " + ey.getStart()); if (!jahFoi.contains(ih)) { jahFoi.add(ih); gi.insertBefore(ih, "aload_0 " + // empilha o objeto " ldc \"" + className + "\"" + // empilha o nome da classe " ldc " + i + // empilha o numero do metodo " lconst_0 " + // empilha aninhamento que para construtor // eh sempre 0 " ldc " + // empilha o numero do no "\"" + ey.getNumber() + "\" " + "invokestatic " + getProbeClass() + " probe \"(Ljava/lang/Object;" + "Ljava/lang/String;IJLjava/lang/Object;)V\""); } } } else { // in this case the method is an ordinary method String probStat = null, method = null; if (mg.isStatic()) { probStat = ""; method = ""; } else { probStat = "aload_0"; method = "Ljava/lang/Object;"; } for (int m = 0; m < gfc.size(); m++) { CFGNode gn = (CFGNode) gfc.elementAt(m); InstructionHandle ih = InstructionList.findHandle(ihVec, ihOffset, ihOffset.length, gn.getStart()); if (gfc.isEntryNode(gn)) { String s = "invokestatic " + getProbeClass() + " getNest \"()J\"" + " lstore " + nextLocal; gi.addBefore(ih, s); } String s = probStat + " ldc \"" + className + "\"" + // empilha o nome da classe " ldc " + i + // empilha o numero do metodo " lload " + nextLocal + // empilha nivel de aninhamento " ldc " + // empilha o numero do no "\"" + gn.getNumber() + "\" " + "invokestatic " + getProbeClass() + " probe \"(" + method + "Ljava/lang/String;IJLjava/lang/Object;)V\""; if (!jahFoi.contains(ih)) { jahFoi.add(ih); gi.insertBefore(ih, s); } } int stackSize = mg.getMaxStack(); // Tentativa de contornar os erros do BCEL que n<E3>o altera corretamente o // tamanho da pilha if (stackSize < 6) { mg.setMaxStack(stackSize + 6); } } methods[i] = mg.getMethod(); } catch (ParseException e) { System.out.println(className); System.err.println("Parser error " + e.getMessage()); } } int newIndex = cp.addUtf8(JABUTI_DEFAULT_INSTR_ATTRIBUTE); Attribute atr = new Unknown(newIndex, JABUTI_DEFAULT_INSTR_ATTRIBUTE.length(), JABUTI_DEFAULT_INSTR_ATTRIBUTE.getBytes(), cp.getConstantPool()); cg.setConstantPool(cp); cg.addAttribute(atr); cg.setMethods(methods); return (cg.getJavaClass()); }
From source file:br.jabuti.probe.desktop.DefaultProbeInsert.java
License:Open Source License
/** * This method wraps a given method code between two pieces of code: one to be executed before * the method and other after, as a finaly clause. The instrumentation will use the next 2 free * local variable, so the code to be inserted should not use them. * /* www . j av a 2 s. c o m*/ * @param jv - The JavaClass where to find the method * @param name - the method name * @param sig - method signature * @param cfg - the control flow graph of the method * @param before - the code to be inserted before the method code * @param after - the code to be inserted after the method */ static public JavaClass wrapMethod(JavaClass jv, String name, String sig, // CFG cfg, String before, String after) { ClassGen cg = new ClassGen(jv); ConstantPoolGen cp = cg.getConstantPool(); Method[] methods = cg.getMethods(); int i; for (i = 0; i < methods.length; i++) { String n = methods[i].getName(); String s = methods[i].getSignature(); if (s.equals(sig) && n.equals(name)) break; } if (i >= methods.length) return jv; MethodGen mg = new MethodGen(methods[i], cg.getClassName(), cp); try { int nextLocal = mg.getMaxLocals(); ASMInstrumenter gi = new ASMInstrumenter(mg, cg, cp); InstructionList iList = mg.getInstructionList(); // pega instrucao inicial InstructionHandle first = iList.getStart(); // System.out.println("First: " + first); // System.out.println(iList); gi.insertBefore(first, " NOP " + (before == null ? "" : before)); // System.out.println(iList); // iList = mg.getInstructionList(); InstructionHandle preambulo = iList.getStart(); // System.out.println("Preambulo: " + preambulo); // ultima instrucao do metodo InstructionHandle last = iList.getEnd(); // System.out.println("Last: " + last); // comeca a inserir o tratador de instrucoes gi.insertAfter(last, " astore " + (nextLocal + 1)); // iList = mg.getInstructionList(); InstructionHandle catcher = iList.getEnd(); gi.insertAfter(catcher, " jsr l1 aload " + (nextLocal + 1) + " athrow " + " l1: NOP "); // System.out.println("catcher: " + catcher); // comeca a inserir o codigo do finally // iList = mg.getInstructionList(); InstructionHandle subroutine = iList.getEnd(); // System.out.println("subroutine: " + subroutine); String finali = " astore " + nextLocal; finali += after; finali += " ret " + nextLocal; gi.insertAfter(subroutine, finali); // iList = mg.getInstructionList(); InstructionHandle nx = first, curr; mg.getMethod(); // para cada return no codigo faz uma chamada aa subrotina do { curr = nx; BranchInstruction jsr = new JSR(subroutine); Instruction ins = curr.getInstruction(); if (ins instanceof ReturnInstruction) { gi.insertBefore(curr, jsr); } nx = curr.getNext(); } while (curr != last); // e finalmente, coloca o tratador de excees para todo // o cdigo orignal iList = mg.getInstructionList(); mg.addExceptionHandler(preambulo, last, catcher, (ObjectType) null); } catch (ParseException e) { System.err.println("Parser error " + e.getMessage()); } mg.setMaxStack(); mg.setMaxLocals(); methods[i] = mg.getMethod(); cg.setMethods(methods); return (cg.getJavaClass()); }
From source file:br.jabuti.probe.mobiledevice.HostProbeInsert.java
License:Open Source License
protected JavaClass doClassInstrument(JavaClass java_class) throws InvalidInstructionException, InvalidStackArgument { ClassGen cg = new ClassGen(java_class); // procura a entrada da classe mucode.abstractions.MuAgent e // substitui por mobility.abstractions.MuAgent ConstantPoolGen cp = cg.getConstantPool(); int oldIndex = cp.lookupClass(MUCODE_AGENT); if (oldIndex >= 0) { int newIndex = cp.addUtf8(MY_AGENT_UTF8); ConstantClass oldConst = (ConstantClass) cp.getConstant(oldIndex); oldConst.setNameIndex(newIndex); cp.setConstant(oldIndex, oldConst); cg.setConstantPool(cp);/*from w ww . j ava2 s.c o m*/ } int newIndex = cp.addUtf8(JABUTI_HOST_INSTR_ATTRIBUTE); Attribute atr = new Unknown(newIndex, JABUTI_HOST_INSTR_ATTRIBUTE.length(), JABUTI_HOST_INSTR_ATTRIBUTE.getBytes(), cp.getConstantPool()); cg.setConstantPool(cp); cg.addAttribute(atr); return (cg.getJavaClass()); }