Advertisement
Guest User

Untitled

a guest
Dec 10th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.84 KB | None | 0 0
  1. import java.io.BufferedReader
  2. import java.io.File
  3. import java.io.FileReader
  4. import java.io.IOException
  5. import java.nio.file.Files
  6. import java.nio.file.Paths
  7. import java.util._
  8. import java.io._
  9. import java.nio.charset._
  10.  
  11. import org.apache.commons.io._
  12. import org.eclipse.jdt.core.dom.MethodDeclaration
  13. import org.eclipse.jdt.core.JavaCore
  14. import org.eclipse.jdt.core.dom._
  15. import org.eclipse.jdt.core.dom.rewrite.ASTRewrite
  16. import org.eclipse.jdt.core.dom.rewrite.ITrackedNodePosition
  17. import org.eclipse.jdt.core.dom.rewrite.ListRewrite
  18. import org.eclipse.jface.text.BadLocationException
  19. import org.eclipse.jface.text.Document
  20.  
  21. import scala.collection.mutable.HashSet
  22. import org.eclipse.text.edits.TextEdit
  23. import org.eclipse.text.edits.UndoEdit
  24. import org.apache.commons.io.FileUtils.readFileToString
  25. import org.slf4j.{Logger, LoggerFactory}
  26.  
  27. import scala.collection.mutable
  28.  
  29.  
  30. object MainScala {
  31. @throws[IOException]
  32. @throws[BadLocationException]
  33. def main(args: Array[String]): Unit = {
  34. val config = System.getProperty("user.dir") + "/src/config.properties"
  35. val input = new FileInputStream(config)
  36. val prop = new Properties
  37. prop.load(input)
  38. val is = new FileInputStream(prop.getProperty("file"))
  39. val buf = new BufferedReader(new InputStreamReader(is))
  40. var line = buf.readLine
  41. val sb = new StringBuilder
  42. while ( {
  43. line != null
  44. }) {
  45. sb.append(line).append("\n")
  46. line = buf.readLine
  47. }
  48. val fileName = sb.toString.toCharArray
  49. val document = new Document(sb.toString)
  50. val parser = ASTParser.newParser(AST.JLS3)
  51. parser.setKind(ASTParser.K_COMPILATION_UNIT)
  52. parser.setResolveBindings(true)
  53. val options = JavaCore.getOptions
  54. val unitName = "Test.java"
  55. parser.setUnitName(unitName)
  56. parser.setCompilerOptions(options)
  57. parser.setSource(document.get.toCharArray)
  58. val sources = Array("/Users/Abdel/Documents/Fall2019/CS474/Final_Proj_474/src")
  59. val classpath = Array("")
  60. parser setEnvironment(classpath, sources, Array[String]("UTF-8"), true)
  61. parser.setBindingsRecovery(true)
  62. parser.setResolveBindings(true)
  63. parser.setCompilerOptions(options)
  64. parser.setStatementsRecovery(true)
  65. //parser.setSource(fileName);
  66. val cu = parser.createAST(null).asInstanceOf[CompilationUnit]
  67. //----------------------------------------------------------------------------------------------------------------------
  68. val root = cu.getRoot
  69.  
  70. //Creating logger to log statements
  71. def log : Logger = LoggerFactory.getLogger(MainScala.getClass)
  72.  
  73. //Creating Abstract Syntax Tree from compilation unit
  74. val ast = cu.getAST
  75.  
  76. //ASTRewriter to allow modifications in the code
  77. val rewriter = ASTRewrite.create(ast)
  78. cu.recordModifications()
  79. val typeDec:TypeDeclaration = cu.types().get(0).asInstanceOf[TypeDeclaration]//typeDec is the class
  80. var className:String = typeDec.getName.toString
  81.  
  82. //Traversing AST using AST Parser
  83. cu.accept(new ASTVisitor() {
  84. var names: HashSet[String] = HashSet(" ")
  85.  
  86. //When visiting a variable declaration fragment
  87. override def visit(node: VariableDeclarationFragment): Boolean = {
  88.  
  89. //Gathering basic information of the node
  90.  
  91. //Name of the node
  92. val name = node.getName
  93.  
  94. //Adding it to the hashset of variables
  95. this.names.add(name.getIdentifier)
  96.  
  97. val id = ast.newImportDeclaration
  98. id.setName(ast.newName(Array[String]("java", "util", "Set")))
  99. val lrw = rewriter.getListRewrite(cu, CompilationUnit.IMPORTS_PROPERTY)
  100.  
  101. //Empty list of statements
  102. val s = new ArrayList[Statement]
  103.  
  104. //Creating empty block to be inserted into the node if necessary
  105. val block = ast.newBlock
  106.  
  107. //if node is only a variable declaration fragment and NOT a variable delcaration statement withing a function
  108. if (node.getParent.getNodeType == 23) {
  109.  
  110. //Log name, type, and line number
  111. log.info("Global Declaration of : " + node.getName + " with Type: " + node.resolveBinding.getType.getQualifiedName + " at Line " + cu.getLineNumber(node.getStartPosition) )
  112.  
  113. val type1 = node.resolveBinding.getType.getQualifiedName.toString
  114. val name = node.getName.toString
  115.  
  116. //Will check the variable to see if it's Initialized or not
  117. //If it's not, it must be instrum in a different way
  118.  
  119. if(node.getInitializer!= null) {//if initialized
  120.  
  121. //Getting value of variable
  122. val value = node.getInitializer.toString
  123.  
  124. //Getting variable declaration string
  125. val declaration = (name + "=" + value).toString
  126.  
  127. //Create instrumentation statement and rewrite to document
  128. val placeHolder = rewriter.createStringPlaceholder("Template.instrum(" + "\""+ type1 + "\"" +"," + "\""+ declaration + "\"" + ");", 20).asInstanceOf[Statement]
  129.  
  130. //Adding new statment to list of statements
  131. s.add(placeHolder)
  132. }
  133. else{//if not initialized
  134.  
  135. //Creating empty value of variable
  136. val value= ""
  137.  
  138. val declaration= (name)
  139.  
  140.  
  141. //Create instrumentation statement and rewrite to document
  142. val placeHolder = rewriter.createStringPlaceholder("Template.instrum(" + "\""+ type1 + "\"" +"," + "\""+ declaration + "\"" + ");", 20).asInstanceOf[Statement]
  143.  
  144. //Adding new statment to list of statements
  145. s.add(placeHolder)
  146. }
  147. }
  148.  
  149. lrw.replace(node, id, null)
  150. val name1 = "var " + node.getName.toString
  151. val varDecFrag = ast.newVariableDeclarationFragment
  152.  
  153. true // do not continue to avoid usage info
  154. }
  155.  
  156. // override def visit(node: SimpleName): Boolean = {
  157. // if (this.names.contains(node.getIdentifier)) {
  158. // //System.out.println("Usage of '" + node + "' at line " + cu.getLineNumber(node.getStartPosition()));
  159. // }
  160. // true
  161. // }
  162.  
  163. //When visiting a method declaration
  164. override def visit(node: MethodDeclaration): Boolean = { //CREATE NEW BLOCK
  165.  
  166. //Creating empty block to be inserted into the node
  167. val block = ast.newBlock
  168.  
  169. //Old block with statements
  170. val block1 = node.getBody
  171.  
  172. //Empty list of statements
  173. val s = new ArrayList[Statement]
  174.  
  175. //Getting statements from body of function
  176. val lstStmt = node.getBody.statements()
  177.  
  178. val placeHolder: Statement = rewriter.createStringPlaceholder("//Declaration of Method: "+ node.getName()+ " with parameters: "+ node.parameters() + " returning: "+ node.getReturnType2() + " at Line: "+cu.getLineNumber(node.getStartPosition) , 20).asInstanceOf[Statement]
  179. s.add(placeHolder)
  180.  
  181. log.info("Method Declaration: "+ node.getName()+ " with parameters: "+ node.parameters() + " returning: "+ node.getReturnType2() + " at Line: "+cu.getLineNumber(node.getStartPosition) )
  182.  
  183. //Retrieveing strings method info
  184. val name = node.getName.toString
  185. val rType = node.getReturnType2.toString
  186. val param = node.parameters.toString
  187.  
  188. //creating and adding new instrumenatation statement to statement list
  189. val placeHolder3 = rewriter.createStringPlaceholder(
  190. "Template.instrum(" + "\""+ rType + "\"" +"," + "\""+ name + "\"" + "," + "\""+ param + "\"" + ");", 20).asInstanceOf[Statement]
  191. s.add(placeHolder3)
  192.  
  193.  
  194. //Traversing statements from body of method, checking each type of statement to be instrumented
  195. //This is where the bulk of the logging will take place, accessing different types of statements (ex. Methods, While loops, variable Declarations)
  196. var x = 0
  197. while ( {
  198. x < block1.statements.size
  199. }) {
  200.  
  201. //Adding statement to array of new statements to be instrumented
  202. s.add(block1.statements.get(x).asInstanceOf[Statement])
  203.  
  204. //If variable declaration statement
  205. if (block1.statements.get(x).isInstanceOf[VariableDeclarationStatement]) {
  206. val node1 = block1.statements.get(x).asInstanceOf[VariableDeclarationStatement]
  207.  
  208. //Debug logger
  209. log.info("Local Declaration of : " + node1.fragments + " with Type: " + node1.getType + " at Line " +cu.getLineNumber(node1.getStartPosition))
  210.  
  211. //Break fragements of statement
  212. val fragments= node1.fragments()
  213. //Gather name and type from fragments
  214. val name = fragments.get(0)
  215. val type1 = node1.getType.toString
  216.  
  217.  
  218. //Create and rewrite with new instrumentation statement
  219. val placeHolder3 = rewriter.createStringPlaceholder(
  220. "Template.instrum(" + "\""+ type1 + "\"" +"," + "\""+ name + "\"" + ");", 20).asInstanceOf[Statement]
  221.  
  222. //Add instrumentation statement to list of statements
  223. s.add(placeHolder3)
  224.  
  225. }
  226.  
  227. //Will check for instances of While Loop statements
  228. else if(block1.statements().get(x).isInstanceOf[WhileStatement]){
  229.  
  230. //Store the While Statement into a node
  231. val node1 = block1.statements.get(x).asInstanceOf[WhileStatement]
  232. log.info("While Statement Expression: '" + node1.getExpression +"' at Line " +cu.getLineNumber(node1.getStartPosition))
  233.  
  234. //Will store the WhileExpresssion, will identify the name of the instrum case as 'While Loop' and then add to the Template class
  235. val whileExpression= node1.getExpression.toString
  236. val name = "While Loop"
  237.  
  238. //Create and rewrite with new instrumentation statement
  239. val placeHolder4= rewriter.createStringPlaceholder(
  240. "Template.instrum(" + "\""+ name + "\"" +"," + "\""+ whileExpression + "\"" + ");", 20).asInstanceOf[Statement]
  241.  
  242. //Add instrumentation statement to list of statements
  243. s.add(placeHolder4)
  244.  
  245. }
  246.  
  247. //Will check for all instances of For Loop Statements
  248. else if(block1.statements().get(x).isInstanceOf[ForStatement]){
  249. //Stores the For Loop Statement into a node
  250. val node1 = block1.statements.get(x).asInstanceOf[ForStatement]
  251. log.info("For Statement Statement: '" + node1.getExpression+ "' at Line " +cu.getLineNumber(node1.getStartPosition))
  252.  
  253. //Will store the forExpresssion, will identify the name of the instrum case as 'For Loop' and then adds to the Template class
  254. val forExpression= node1.getExpression.toString
  255. val name = "For Loop"
  256.  
  257. //Create and rewrite with new instrumentation statement
  258. val placeHolder5= rewriter.createStringPlaceholder(
  259. "Template.instrum(" + "\""+ name + "\"" +"," + "\""+ forExpression + "\"" + ");", 20).asInstanceOf[Statement]
  260.  
  261. //Add instrumentation statement to list of statements
  262. s.add(placeHolder5)
  263.  
  264. }
  265. //If it's a do while loop
  266. else if(block1.statements().get(x).isInstanceOf[DoStatement]) {
  267.  
  268. //Get do while node
  269. val node1 = block1.statements.get(x).asInstanceOf[DoStatement]
  270.  
  271. //Debug Logger
  272. log.info("Do-While Statement: '" + node1.getExpression + "' at Line " + cu.getLineNumber(node1.getStartPosition))
  273.  
  274. //Gather info from do while
  275. val doWhileExpression = node1.getExpression.toString
  276. val name = "Do-While Loop"
  277.  
  278. //Create and rewrite with new instrumentation statement
  279. val placeHolder6 = rewriter.createStringPlaceholder(
  280. "Template.instrum(" + "\"" + name + "\"" + "," + "\"" + doWhileExpression + "\"" + ");", 20).asInstanceOf[Statement]
  281.  
  282. //Add instrumentation statement to list of statements
  283. s.add(placeHolder6)
  284. }
  285.  
  286.  
  287. //ToDo: Will not work if the If and Else is at the very end of the method (Receive an 'unused statement' error)
  288. else if(block1.statements().get(x).isInstanceOf[IfStatement]) {
  289.  
  290. //Will store the If-Else statement into a node
  291. val node1 = block1.statements.get(x).asInstanceOf[IfStatement]
  292. log.info("If-Else Statement: '" + node1.getExpression + "' at Line " + cu.getLineNumber(node1.getStartPosition))
  293.  
  294. //Will store the Expression for the If-Else statement into ifElseExpression as a string, it's instance type, and updates to the Template class
  295. val ifElseExpression = node1.getExpression.toString
  296. val name = "If-Else Statement"
  297. var elseStatement=""
  298.  
  299. //In case the use only write the 'if' statement without 'else'
  300. if(node1.getElseStatement != null) {
  301. var elseStatement = node1.getElseStatement.toString
  302. }
  303.  
  304. //Removes the semicolon that automatically creates a new line
  305. //Thus preventing an error to the NewJava File
  306. if (elseStatement.contains(";")){
  307. val parts = elseStatement.split(";")
  308. elseStatement = parts(0)
  309. }
  310.  
  311. //ToDo: It will log it but not create an instrum due to the unused statement error
  312. /*
  313. val placeHolder7 = rewriter.createStringPlaceholder(
  314. "Template.instrum(" + "\"" + name + "\"" + "," + "\"" + elseStatement + "\"" + ");", 20).asInstanceOf[Statement]
  315. s.add(placeHolder7)
  316. */
  317.  
  318.  
  319. }
  320.  
  321.  
  322. {
  323. //Increments
  324. x += 1; x - 1
  325. }
  326. }
  327.  
  328. //Will store all the block statements into list rewrite, and will Insert Last
  329. val listRewrite = rewriter.getListRewrite(block, Block.STATEMENTS_PROPERTY)
  330. var i = 0
  331. while ( {
  332. i < s.size
  333. }) {
  334. listRewrite.insertLast(s.get(i), null)
  335.  
  336. {
  337. i += 1; i - 1
  338. }
  339. }
  340.  
  341. val methodDeclaration = ast.newMethodDeclaration
  342. methodDeclaration.setBody(block)
  343. rewriter.set(node, MethodDeclaration.BODY_PROPERTY, block, null)
  344. true
  345. }
  346. })
  347.  
  348. //Writing/modifying the file
  349. val edits = rewriter.rewriteAST(document, null)
  350. //Applying the writes the document
  351. edits.apply(document)
  352.  
  353. var docString = document.get
  354.  
  355. /*
  356. -Replaces the name of the new file so that it is not the same as the input Java Program
  357. This ensures that the file can run without any issues of having multiple files with
  358. the same name
  359. */
  360. val newClass= "new_" + className
  361. docString = docString.replaceAll(className,newClass)
  362. //Variables for writing to a new file
  363. val writer = new BufferedWriter( new FileWriter( "src/main/Java/"+newClass+".java"));
  364. //Writing into the new file
  365. writer.write( docString );
  366. //Close writer
  367. writer.close();
  368. }
  369. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement