/// <summary> /// read the contents to be injected into every generated class. /// </summary> private static void readInjectContents() { string injectFileName = ConfigurationXMLParser.getProperty("injectFilename"); if (!File.Exists(injectFileName)) { Console.WriteLine("Unable to locate Inject File. Skipping content injection!"); } //Veena : Unreachable code. I tested it twice in eclipse. it never comes here. // Hence commenting the try block try { //StringBuilder buffer = new StringBuilder(); //System.IO.StreamReader reader = new System.IO.StreamReader(injectFileName); //System.IO.StreamReader buffReader = new System.IO.StreamReader(reader); //string str = ""; //while ((str = buffReader.ReadLine()) != null) //{ // buffer.Append(str); // buffer.Append("\n"); //} //injectContents = buffer.ToString(); } catch (FileNotFoundException) { Console.WriteLine("Unable to locate Inject File. Skipping content injection!"); injectContents = ""; } catch (IOException) { Console.WriteLine("Unable to read Inject File. Skipping content injection!"); injectContents = ""; } }
/// <summary> /// read the contents to be injected into every generated class. /// </summary> private static void readInjectContents() { string injectFileName = ConfigurationXMLParser.getProperty("injectFilename"); File injectFile = new File(injectFileName); if (!injectFile.exists()) { Console.WriteLine("Unable to locate Inject File. Skipping content injection!"); } try { StringBuilder buffer = new StringBuilder(); System.IO.StreamReader reader = new System.IO.StreamReader(injectFile); System.IO.StreamReader buffReader = new System.IO.StreamReader(reader); string str = ""; while ((str = buffReader.ReadLine()) != null) { buffer.Append(str); buffer.Append("\n"); } injectContents = buffer.ToString(); } catch (FileNotFoundException) { Console.WriteLine("Unable to locate Inject File. Skipping content injection!"); injectContents = ""; } catch (IOException) { Console.WriteLine("Unable to read Inject File. Skipping content injection!"); injectContents = ""; } }
//read config information needed for code generation. static ProgGenUtil() { allowedTypes = AllowedTypesAsList; primitivesMap["char"] = Type.Primitives.CHAR; primitivesMap["byte"] = Type.Primitives.BYTE; primitivesMap["short"] = Type.Primitives.SHORT; primitivesMap["int"] = Type.Primitives.INT; primitivesMap["long"] = Type.Primitives.LONG; primitivesMap["float"] = Type.Primitives.FLOAT; primitivesMap["double"] = Type.Primitives.DOUBLE; primitivesMap["String"] = Type.Primitives.STRING; primitivesMap["Object"] = Type.Primitives.OBJECT; primitivesMap["Other"] = Type.Primitives.OTHER; readInjectContents(); maximumArraySize = ConfigurationXMLParser.getPropertyAsInt("maximumArraySize"); if (ConfigurationXMLParser.getProperty("useQueries").Equals("true", StringComparison.InvariantCultureIgnoreCase)) { useQueries = true; } //if (ConfigurationXMLParser.getProperty("useQueries").equalsIgnoreCase("true")) //{ // useQueries = true; //} string callType = ConfigurationXMLParser.getProperty("callType"); if (callType.Equals("MCO2_2", StringComparison.CurrentCultureIgnoreCase)) { methodCallType = CallType.crossClassWithoutRecursionLimit; } else if (callType.Equals("MCO2_1", StringComparison.CurrentCultureIgnoreCase)) { methodCallType = CallType.crossClassWithRecursionLimit; } else if (callType.Equals("MCO1_1", StringComparison.CurrentCultureIgnoreCase)) { methodCallType = CallType.localWithRecursionLimit; } else { //Original: methodCallType = CallType.localWithoutRecursionLimit; //Veena : Changed it to methodCallType = CallType.localWithRecursionLimit; } }
private void appendClassName() { program += "public class " + ConfigurationXMLParser.getProperty("classNamePrefix") + "Start {\n"; }
private void createClass(int level, int target) { if (level == 0) { /* * create 'loop' number of classes where each class calls 150 or * less T.SingleEntry() methods in total 'target' number of * T.SingleEntry() methods name these classes TStart_Llevel_X */ int count = 0; int loop = (int)Math.Ceiling((double)target / 150); for (int i = 0; i < loop; i++) { try { File file = new File(DirPath + "TestPrograms" + File.separator + "com" + File.separator + "accenture" + File.separator + "lab" + File.separator + "carfast" + File.separator + "test" + File.separator + "TStart_L" + level + "_" + i + ".java"); System.IO.StreamWriter fileWriter = new System.IO.StreamWriter(file); System.IO.StreamWriter writer = new System.IO.StreamWriter(fileWriter); StringBuilder output = new StringBuilder(); output.Append("package com.accenture.lab.carfast.test;\n\n"); output.Append("public class TStart_L" + level + "_" + i + "{\n"); for (int k = 0; k < ProgGenUtil.maxNoOfParameters; k++) { output.Append("private static int f" + k + ";\n"); } output.Append("\n\n"); output.Append("public static void entryMethod("); //int i0, int i1, int i2, int i3, int i4, int i5, int i6){\n"); output.Append(formalParam + "){\n"); for (int k = 0; k < ProgGenUtil.maxNoOfParameters; k++) { output.Append("f" + k + " = " + "i" + k + ";\n"); } for (int j = 0; j < methCallLimit && count < target; j++, count++) { // call Tj.SingleEntry(); // output.append("FiveMLOC"+count+".singleEntry(f0,f1,f2,f3,f4,f5,f6);\n"); output.Append(ConfigurationXMLParser.getProperty("classNamePrefix") + count + ".singleEntry(" + argument + ");\n"); } output.Append("}\n}"); string @out = output.ToString(); // System.out.println("Writing L0 level entry classes."); writer.WriteByte(@out); writer.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } } createClass(level + 1, loop); } else { if (level == LEVEL) { // create FiveMLOCStart.java class that will call // FiveMLOCStart_L(prevLevel)_0.entryMethod(); try { File file = new File(DirPath + "TestPrograms" + File.separator + "com" + File.separator + "accenture" + File.separator + "lab" + File.separator + "carfast" + File.separator + "test" + File.separator + ConfigurationXMLParser.getProperty("classNamePrefix") + "Start" + ".java"); // File file = new File("./FiveMLOCStart.java"); System.IO.StreamWriter fileWriter = new System.IO.StreamWriter(file); System.IO.StreamWriter writer = new System.IO.StreamWriter(fileWriter); StringBuilder output = new StringBuilder(); output.Append("package com.accenture.lab.carfast.test;\n\n"); // output.append("public class FiveMLOCStart {\n"); output.Append("public class " + ConfigurationXMLParser.getProperty("classNamePrefix") + "Start {\n"); for (int k = 0; k < ProgGenUtil.maxNoOfParameters; k++) { output.Append("private static int f" + k + ";\n"); } output.Append("\n\n"); output.Append("public static void entryMethod("); //int i0, int i1, int i2, int i3, int i4, int i5, int i6){\n"); output.Append(formalParam + "){\n"); for (int k = 0; k < ProgGenUtil.maxNoOfParameters; k++) { output.Append("f" + k + " = " + "i" + k + ";\n"); } output.Append("TStart_L" + (level - 1) + "_0.entryMethod(" + argument + ");\n}\n\n"); output.Append("public static void main(String[] args){\n entryMethod("); StringBuilder str = new StringBuilder(); for (int i = 0; i < ProgGenUtil.maxNoOfParameters; i++) { str.Append("Integer.parseInt(args[" + i + "]),"); } string s = str.ToString(); s = s.Substring(0, str.Length - 1); s += ");\n}"; output.Append(s); output.Append("\n}"); string @out = output.ToString(); // System.out.println("Writing the 'Start' class."); writer.WriteByte(@out); writer.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } return; } else { int count = 0; int loop = (int)Math.Ceiling((double)target / 150); for (int i = 0; i < loop; i++) { /* * create 'loop' number of classes,where each calls 150 or * less TStart_L(prevlevel)_X.entryMethod() methods; in * total 'target' number of calls. * * Name each class TStart_Llevel_X */ try { File file = new File(DirPath + "TestPrograms" + File.separator + "com" + File.separator + "accenture" + File.separator + "lab" + File.separator + "carfast" + File.separator + "test" + File.separator + "TStart_L" + level + "_" + i + ".java"); // File file = new File("./TStart_L"+level+"_"+i+".java"); System.IO.StreamWriter fileWriter = new System.IO.StreamWriter(file); System.IO.StreamWriter writer = new System.IO.StreamWriter(fileWriter); StringBuilder output = new StringBuilder(); output.Append("package com.accenture.lab.carfast.test;\n\n"); output.Append("public class TStart_L" + level + "_" + i + "{\n"); for (int k = 0; k < ProgGenUtil.maxNoOfParameters; k++) { output.Append("private static int f" + k + ";\n"); } output.Append("\n\n"); output.Append("public static void entryMethod("); //int i0, int i1, int i2, int i3, int i4, int i5, int i6){\n"); output.Append(formalParam + "){\n"); for (int k = 0; k < ProgGenUtil.maxNoOfParameters; k++) { output.Append("f" + k + " = " + "i" + k + ";\n"); } for (int j = 0; j < methCallLimit && count < target; j++, count++) { // Call TStart_L(prevlevel)_X.entryMethod() output.Append("TStart_L" + (level - 1) + "_" + count + ".entryMethod(" + argument + ");\n"); } output.Append("}\n}"); string @out = output.ToString(); // System.out.println("Writing mid level classes."); writer.WriteByte(@out); writer.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } } createClass(level + 1, loop); } } }
/// <summary> /// get a random method call. /// </summary> /// <param name="method"> </param> /// <param name="classList"> /// @return </param> public static string getMethodCall(Method method, List <ClassGenerator> classList) { string stmt = ""; if (ProgGenUtil.methodCallType == CallType.localWithoutRecursionLimit || ProgGenUtil.methodCallType == CallType.localWithRecursionLimit) { //only local method calls. List <MethodSignature> methodList = method.AssociatedClass.MethodSignatures; if (methodList.Count < 1) { stmt = (new PrintStatement(method)).ToString(); return(stmt); } MethodSignature methodToBeInvoked = getMethodToBeInvoked(methodList, method.Static, method.MethodSignature); if (methodToBeInvoked == null) { stmt = (new PrintStatement(method)).ToString(); return(stmt); } // Check if indirect recursion is allowed: if (ConfigurationXMLParser.getProperty("allowIndirectRecursion").ToLower().Equals("no")) { //Methods are always named ClassNameM/methodNUMBER string[] tok = methodToBeInvoked.Name.ToLower().Split("method", true); int calleeMethodID = int.Parse(tok[1]); string[] tok2 = method.MethodSignature.Name.ToLower().Split("method", true); int callerMethodID = int.Parse(tok2[1]); // callerID should be lower than calleeID if (callerMethodID >= calleeMethodID) { stmt = (new PrintStatement(method)).ToString(); return(stmt); } } List <Variable> parameterList = methodToBeInvoked.ParameterList; string parameters = "("; parameters += getParametersForList(parameterList, method); parameters += ")"; stmt += methodToBeInvoked.Name + parameters + ";"; method.CalledMethods.Add(methodToBeInvoked); method.CalledMethodsWithClassName.Add(method.AssociatedClass.FileName + "." + methodToBeInvoked.Name); method.Loc = method.Loc + 1; return(stmt); } else { //cross-class method calls. //Veena : tested in eclipse. Never comes here Since we are not handling objects. //Random random = new Random(); //List<Field> objList = new List<Field>(); //objList.AddRange(getObjects(method.AssociatedClass.Fields)); //objList.AddRange(getObjects(method.ParameterList)); //if (objList.Count != 0) //{ // Field variable = objList[random.Next(objList.Count)]; // ClassGenerator classObj = getClassByName(classList, variable.Type.ToString()); // if (classObj != null) // { // string varString = variable.ToString(); // List<MethodSignature> signatures = classObj.MethodSignatures; // MethodSignature signature = signatures[random.Next(signatures.Count)]; // string methodCall = signature.Name + "(" + getParametersForList(signature.ParameterList, method) + ");\n"; // if (!signature.Static) // { // if (method.Static && !variable.Static) // { // if (!variable.Name.StartsWith("var", StringComparison.Ordinal)) // { // stmt += "classObj."; // } // } // stmt += varString + " = new " + variable.Type + "();\n"; // } // if (method.Static && !variable.Static && !variable.Name.StartsWith("var", StringComparison.Ordinal) && !signature.Static) // { // stmt += "classObj."; // } // if (signature.Static) // { // stmt += classObj.FileName + "." + methodCall; // } // else // { // stmt += varString + "." + methodCall; // } // method.Loc = method.Loc + 1; // method.CalledMethods.Add(signature); // method.CalledMethodsWithClassName.Add(variable.Type + "." + signature.Name); // return stmt; // } //} } return(stmt); }
/// <summary> /// Return a method call statement based on a given primitive. /// </summary> /// <param name="method"> </param> /// <param name="classList"> </param> /// <param name="returnType"> </param> /// <param name="lhs"> /// @return </param> public static string getMethodCallForReturnType(Method method, List <ClassGenerator> classList, Type returnType, Operand lhs) { string stmt = ""; if (ProgGenUtil.methodCallType == CallType.localWithoutRecursionLimit || ProgGenUtil.methodCallType == CallType.localWithRecursionLimit) { //only local method calls. List <MethodSignature> methodList = method.AssociatedClass.MethodSignatures; if (methodList.Count < 1) { return(lhs + " = " + (new Literal(returnType.getType())).ToString() + ";"); } MethodSignature methodToBeInvoked = getMethodToBeInvoked(methodList, method.Static, returnType, method.MethodSignature); if (methodToBeInvoked == null) { return(lhs + " = " + (new Literal(returnType.getType())).ToString() + ";"); } //Check if indirect recursion is allowed: if (ConfigurationXMLParser.getProperty("allowIndirectRecursion").ToLower().Equals("no")) { try { string[] tok = methodToBeInvoked.Name.ToLower().Split("method", true); int calleeMethodID = int.Parse(tok[1]); string[] tok2 = method.MethodSignature.Name.ToLower().Split("method", true); int callerMethodID = int.Parse(tok2[1]); if (callerMethodID >= calleeMethodID) { return(lhs + " = " + (new Literal(returnType.getType())).ToString() + ";"); } } catch (System.FormatException e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } } List <Variable> parameterList = methodToBeInvoked.ParameterList; string parameters = "("; parameters += getParametersForList(parameterList, method); parameters += ")"; stmt += lhs + " = " + methodToBeInvoked.Name + parameters + ";"; method.CalledMethods.Add(methodToBeInvoked); method.CalledMethodsWithClassName.Add(method.AssociatedClass.FileName + "." + methodToBeInvoked.Name); method.Loc = method.Loc + 1; return(stmt); } else { //Veena : tested in eclipse. Never comes here Since we are not handling objects. //cross-class method calls. //Random random = new Random(); //List<Field> objList = new List<Field>(); //objList.AddRange(getObjects(method.AssociatedClass.Fields)); //objList.AddRange(getObjects(method.ParameterList)); //if (objList.Count != 0) //{ // ArrayList list = getClassByMethodReturnType(objList, returnType.getType(), classList); // if (list == null) // { // return lhs + " = " + (new Literal(returnType.getType())).ToString() + ";"; // } // Field variable = (Field)list[0]; // ClassGenerator classObj = (ClassGenerator)list[1]; // if (classObj != null) // { // List<MethodSignature> signatures = classObj.getMethodSignatures(returnType); // if (signatures.Count == 0) // { // return lhs + " = " + (new Literal(returnType.getType())).ToString() + ";"; // } // MethodSignature signature = signatures[random.Next(signatures.Count)]; // string varString = variable.ToString(); // string methodCall = signature.Name + "(" + getParametersForList(signature.ParameterList, method) + ");\n"; // if (!signature.Static) // { // if (method.Static && !variable.Static) // { // if (!variable.Name.StartsWith("var", StringComparison.Ordinal)) // { // stmt += "classObj."; // } // } // stmt += varString + " = new " + variable.Type + "();\n"; // } // stmt += lhs + " = "; // if (method.Static && !variable.Static && !variable.Name.StartsWith("var", StringComparison.Ordinal) && !signature.Static) // { // stmt += "classObj."; // } // if (signature.Static) // { // stmt += classObj.FileName + "." + methodCall; // } // else // { // stmt += varString + "." + methodCall; // } // method.Loc = method.Loc + 1; // method.CalledMethods.Add(signature); // method.CalledMethodsWithClassName.Add(variable.Type + "." + method.Name); // return stmt; // } //} } return(lhs + " = " + (new Literal(returnType.getType())).ToString() + ";"); }
public static void Main(string[] args) { /* For ant script: specify 'config.xml' file and output directory */ if (args.Length == 1) { pathToDir = args[0] + System.IO.Path.PathSeparator; } /* List of generated class objects: ClassGenerators */ List <ClassGenerator> list = new List <ClassGenerator>(); // List<InterfaceGenerator> interfaceList = new List<InterfaceGenerator>(); int numberOfClasses = 0; int maxInheritanceDepth = 0; int noOfInheritanceChains = 0; int noOfInterfaces = 0; int maxInterfacesToImplement = 0; /* Set of generated classes, it's updated in ClassGenerator.generate() */ HashSet <string> generatedClasses = new HashSet <string>(); HashSet <string> preGeneratedClasses = new HashSet <string>(); try { string className = ConfigurationXMLParser.getProperty("classNamePrefix"); int totalLoc = ConfigurationXMLParser.getPropertyAsInt("totalLOC"); numberOfClasses = ConfigurationXMLParser.getPropertyAsInt("noOfClasses"); maxInheritanceDepth = ConfigurationXMLParser.getPropertyAsInt("maxInheritanceDepth"); // e.g. 3 noOfInheritanceChains = ConfigurationXMLParser.getPropertyAsInt("noOfInheritanceChains"); // 2 => "A-B-C" ; "E-F-G" noOfInterfaces = ConfigurationXMLParser.getPropertyAsInt("noOfInterfaces"); maxInterfacesToImplement = ConfigurationXMLParser.getPropertyAsInt("maxInterfacesToImplement"); if (numberOfClasses < (maxInheritanceDepth * noOfInheritanceChains)) { Console.WriteLine("Insufficent number of classes. Should be atleast: " + maxInheritanceDepth * noOfInheritanceChains); Environment.Exit(1); } HashSet <string> classList = new HashSet <string>(); for (int i = 0; i < numberOfClasses; i++) { classList.Add(className + i); } //E.g., {[2,5,6], [0,1,4]} List <List <int> > inheritanceHierarchies = new List <List <int> >(); //inheritanceHierarchies = ProgGenUtil.getInheritanceList(noOfInheritanceChains, maxInheritanceDepth, numberOfClasses); for (int i = 0; i < numberOfClasses; i++) { //Ishtiaque: All classes have equal number of variables, methods, etc. Should we change it? // classes are like A1, A2, etc where A=<UserDefinedName> //Bala: All such cases are handled in the ClassGenerator. It generates arbitrary number of // fields, methods. Only constraint is it should override all the methods of the interfaces // it implements. list.Add(new ClassGenerator(className + i, totalLoc / numberOfClasses, null) ); } string path = @"C:\Users\VeenaBalasubramanya\Desktop\Adv_Se\rugrat\TestPrograms\com\accenture\lab\carfast\test"; //Directory directory = Directory.CreateDirectory(path); DirectoryInfo directory = Directory.CreateDirectory(path); //System.IO.FileStream fs = System.IO.File.Create(pathString); if (!directory.Exists) { //Console.WriteLine(directory.mkdirs()); directory = System.IO.Directory.CreateDirectory(path); Console.WriteLine(directory); } /* * for (int i = 0; i < noOfInterfaces; i++) * { * InterfaceGenerator generator = new InterfaceGenerator(className + "Interface" + i, list); * interfaceList.Add(generator); * writeToFile(generator); * } * * //establishClassRelationships(inheritanceHierarchies, list); * * //establishClassInterfaceRelationships(interfaceList, list); */ } catch (System.FormatException e) { Console.WriteLine("Please enter integer values for arguments that expect integers!!!"); Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); Environment.Exit(1); } //do pre-generation for classes //pre-generation determines the class members variables and method signatures foreach (ClassGenerator generator in list) { generator.preGenerateForMethodSignature(list, preGeneratedClasses); } foreach (ClassGenerator generator in list) { //Ishtiaque: How can 'generatedClasses' contain any of the ClassGenerator objects from the list? //Bala: classes are generated semi-recursively. The classes will invoke class generation on the //super class. The current class will be generated only after all its ancestor classes are generated. //We do not want to regenerate the ancestor classses and make stale the information used by its sub-classes //based on the earlier version. if (!generatedClasses.Contains(generator.FileName)) { //call generate to construct the class contents generator.generate(list, generatedClasses, preGeneratedClasses); } writeToFile(generator); } //generate DBUtil only if useQueries is TRUE //if (ProgGenUtil.useQueries) //{ // DBUtilGenerator dbUtilGenerator = new DBUtilGenerator(); // writeToFile(dbUtilGenerator); //} /* writing SingleEntry class */ //SingleEntryGenerator singleEntryGen = new SingleEntryGenerator(list); //String className = ConfigurationXMLParser.getProperty("classNamePrefix")+"Start"; //write(className, singleEntryGen.toString()); TreeOfSingleEntryGenerator treeSingleEntryGen = new TreeOfSingleEntryGenerator(list, pathToDir); treeSingleEntryGen.generateTreeOfSingleEntryClass(); //write the reachability matrix if (ConfigurationXMLParser.getProperty("doReachabilityMatrix").Equals("no")) { return; } List <Method> methodListAll = new List <Method>(); foreach (ClassGenerator generator in list) { methodListAll.AddRange(generator.MethodList); } StringBuilder builder = new StringBuilder(); builder.Append("Name, "); foreach (Method method in methodListAll) { builder.Append(method.AssociatedClass.FileName + "." + method.Name); builder.Append(", "); } builder.Append("\n"); foreach (Method method in methodListAll) { builder.Append(method.AssociatedClass.FileName + "." + method.Name); builder.Append(", "); foreach (Method calledMethod in methodListAll) { if (method.CalledMethodsWithClassName.Contains(calledMethod.AssociatedClass.FileName + "." + calledMethod.Name)) { builder.Append("1, "); } else { builder.Append("0, "); } } builder.Append("\n"); } writeReachabilityMatrix(builder.ToString()); }