diff --git a/.gitignore b/.gitignore index 55cd965..9faf990 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ # Database /DB/ +/Databases/ # Database logs *.log @@ -14,4 +15,7 @@ target/ *.png # intelliJ files -*.iml \ No newline at end of file +*.iml + +# screenshots folder +/Screenshots/ diff --git a/CSV_Before_Run_call_trace.txt b/CSV_Before_Run_call_trace.txt deleted file mode 100644 index 1d6443b..0000000 --- a/CSV_Before_Run_call_trace.txt +++ /dev/null @@ -1,58 +0,0 @@ -1500994917851|13532|1|Enter|1|[[Ljava.lang.String;@5fcfe4b2] -1500994917940|13532|12|Enter|2|[javafx.stage.Stage@1dd8ca16] -1500994917944|13532|12|Enter|3|[com.application.Main@275a96b5] -1500994917944|13532|12|Exit -1500994917945|13532|12|Enter|4|[] -1500994918049|13532|12|Enter|5|[MenuItem@12b748e0[styleClass=[menu-item]]] -1500994918049|13532|12|Exit -1500994918049|13532|12|Enter|5|[MenuItem@7334ee37[styleClass=[menu-item]]] -1500994918049|13532|12|Exit -1500994918049|13532|12|Enter|5|[MenuItem@7d1e983a[styleClass=[menu-item]]] -1500994918049|13532|12|Exit -1500994918049|13532|12|Enter|5|[MenuItem@2c5ebf5f[styleClass=[menu-item]]] -1500994918049|13532|12|Exit -1500994918050|13532|12|Enter|5|[MenuItem@406127c[styleClass=[menu-item]]] -1500994918050|13532|12|Exit -1500994918050|13532|12|Enter|5|[MenuItem@5017019d[styleClass=[menu-item]]] -1500994918050|13532|12|Exit -1500994918050|13532|12|Enter|5|[MenuItem@59419ced[styleClass=[menu-item]]] -1500994918050|13532|12|Exit -1500994918051|13532|12|Enter|6|[Glyph@341d1344[styleClass=label glyph-font]''] -1500994918051|13532|12|Exit -1500994918051|13532|12|Enter|6|[Glyph@5ceef7b3[styleClass=label glyph-font]''] -1500994918051|13532|12|Exit -1500994918051|13532|12|Enter|6|[Glyph@99dae37[styleClass=label glyph-font]''] -1500994918051|13532|12|Exit -1500994918051|13532|12|Enter|6|[Glyph@6a64a955[styleClass=label glyph-font]''] -1500994918051|13532|12|Exit -1500994918051|13532|12|Enter|6|[Glyph@36bf006e[styleClass=label glyph-font]''] -1500994918051|13532|12|Exit -1500994918051|13532|12|Enter|6|[Glyph@1dc72a65[styleClass=label glyph-font]''] -1500994918052|13532|12|Exit -1500994918052|13532|12|Enter|6|[Glyph@794fc3fc[styleClass=label glyph-font]''] -1500994918052|13532|12|Exit -1500994918052|13532|12|Enter|6|[Glyph@36aef381[styleClass=label glyph-font]''] -1500994918052|13532|12|Exit -1500994918052|13532|12|Enter|7|[] -1500994918060|13532|12|Exit -1500994918060|13532|12|Enter|8|[] -1500994918064|13532|12|Exit -1500994918064|13532|12|Exit -1500994918334|13532|12|Exit -1500994920827|13532|12|Enter|9|[javafx.event.ActionEvent[source=MenuItem@12b748e0[styleClass=[menu-item]]]] -1500994920827|13532|12|Enter|10|[MethodDefinition] -1500994932180|13532|12|Exit -1500994932182|13532|12|Enter|11|[/home/omer/ThreadExampleThree_method_definitions.txt] -1500994932182|13532|12|Exit -1500994932184|13532|12|Enter|12|[methodDefnFileSet,true] -1500994932184|13532|12|Exit -1500994932184|13532|12|Exit -1500994934923|13532|12|Enter|13|[javafx.event.ActionEvent[source=MenuItem@7334ee37[styleClass=[menu-item]]]] -1500994934923|13532|12|Enter|10|[CallTrace] -1500994942691|13532|12|Exit -1500994942692|13532|12|Enter|14|[/home/omer/ThreadExampleThree_call_trace.txt] -1500994942692|13532|12|Exit -1500994942692|13532|12|Enter|12|[callTraceFileSet,true] -1500994942692|13532|12|Exit -1500994942692|13532|12|Exit -1500994953782|13532|1|Exit diff --git a/CSV_Before_Run_method_definitions.txt b/CSV_Before_Run_method_definitions.txt deleted file mode 100644 index a2ee4d5..0000000 --- a/CSV_Before_Run_method_definitions.txt +++ /dev/null @@ -1,14 +0,0 @@ -1|com.application.Main|main|([Ljava/lang/String;)V -2|com.application.Main|start|(Ljavafx/stage/Stage;)V -3|com.application.fxgraph.graph.EventHandlers|saveRef|(Lcom/application/Main;)V -4|com.application.Main|setUpMenu|()V -5|com.application.Main|lambda$setUpMenu$0|(Ljavafx/scene/control/MenuItem;)V -6|com.application.Main|lambda$setUpMenu$1|(Lorg/controlsfx/glyphfont/Glyph;)V -7|com.application.Main|populateInstructions|()V -8|com.application.Main|setMenuActions|()V -9|com.application.Main|lambda$setMenuActions$2|(Ljavafx/event/ActionEvent;)V -10|com.application.Main|chooseLogFile|(Ljava/lang/String;)Ljava/io/File; -11|com.application.logs.fileHandler.MethodDefinitionLogFile|setFile|(Ljava/io/File;)V -12|com.application.Main|changeBool|(Ljava/lang/String;Z)V -13|com.application.Main|lambda$setMenuActions$3|(Ljavafx/event/ActionEvent;)V -14|com.application.logs.fileHandler.CallTraceLogFile|setFile|(Ljava/io/File;)V diff --git a/README.md b/README.md index 030675b..1a695ff 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,37 @@ -# CSVFull +# Java Call Stack Graph Tool +#### A tool to generate a graphical representation of the Java call stack. +This tool generate a tree graph for the call stack using the information in log files for you code. A specific format of log files are required for the tool to parse and process the logs. Please see _**How to generate Log files for you code**_ section below to generate log files for your own code.
+ +### Instruction to run tool using Maven. +1. Download or clone the repository.
+`git clone https://github.com/OmerKhureshi/JavaCallStackGraphTool.git` + +2. Since this is a Maven project, use the command below to run the tool from root folder of the repo.
+`mvn exec:java -Dexec.mainClass=com.csgt.Main` ### Instruction to run tool using intelliJ. 1. Download or clone the repository. -2. In IntelliJ, create a new project and choose `Create Project from Existing Sources...`. Choose the cloned repository to improt all the file. -3. Ensure that this project is recognized as a Maven project inside IntelliJ. -6. Run the Main java class in `/src/main/java/com/application/Main.java`. +2. In IntelliJ, create a new project and choose `Create Project from Existing Sources...`. Choose the cloned repository to import all the files. + Or. + + Right click `pom.xml` file and click open with then choose IntelliJ. +3. Ensure that this project is recognized as a Maven project inside IntelliJ and all the dependencies are downloaded. +6. Run the Main java class at `/src/main/java/com/csgt/Main.java`. ### How to use the tool? -1. Click File -> Select Method Definition log file. -2. Click File -> Select Call Trace file. -3. Click Run -> Run. -4. If you want to start over, click Run -> Reset and redo steps 1 through 3 above. +#### For first time use: +For the first time, the tool requires the log files that should be used to generate the graph. +1. Click `File -> Select Method Definition log file` (⎇ + m). +2. Click `File -> Select Call Trace file` (⎇ + c). +3. Click `Render -> Run` (⎇ + r). +4. To start over, click `Render -> Reset` (⎇ + ⇧ + r) and redo steps 1 to 3 above. + +#### For consecutive uses: +The tool uses an embedded database to store the parsed information from the log files. Therefore for consecutive uses of the same log files, you can point to the previously generated database to generate the graph without processing the log files. The database file can be found at `/Databases`. The file is suffixed with the time stamp. +1. Click `File -> Load existing database` (⎇ + d). +2. Click `Render -> Run` (⎇ + r) +3. To start over, click `Render -> Reset` (⎇ + ⇧ + r). -### Generate Log files. -Call Trace and Method Definition log files can be generated by using the shell script [here](https://github.com/omersalar/LogWeaver) +### How to generate Log files for your code? +Call Trace and Method Definition log files can be generated by following the instructions [here](https://github.com/omerkhureshi/LogWeaver). diff --git a/pom.xml b/pom.xml index bfece00..00fbe35 100644 --- a/pom.xml +++ b/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.omer.csc895 - CallStackVisualization + com.csgt + CallStackGraphTool 1.0-SNAPSHOT @@ -34,7 +34,13 @@ derby 10.13.1.1 + + + commons-lang + commons-lang + 2.6 + - \ No newline at end of file + diff --git a/src/main/java/com/application/Controller.java b/src/main/java/com/application/Controller.java deleted file mode 100644 index 362c156..0000000 --- a/src/main/java/com/application/Controller.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.application; - -public class Controller { -} diff --git a/src/main/java/com/application/Main.java b/src/main/java/com/application/Main.java deleted file mode 100644 index c8e1e78..0000000 --- a/src/main/java/com/application/Main.java +++ /dev/null @@ -1,1648 +0,0 @@ -package com.application; - -import com.application.db.DAOImplementation.*; -import com.application.db.DatabaseUtil; -import com.application.db.TableNames; -import com.application.fxgraph.ElementHelpers.ConvertDBtoElementTree; -import com.application.fxgraph.ElementHelpers.Element; -import com.application.fxgraph.cells.CircleCell; -import com.application.fxgraph.graph.*; -import com.application.logs.fileHandler.CallTraceLogFile; -import com.application.logs.fileHandler.MethodDefinitionLogFile; -import com.application.logs.fileIntegrity.CheckFileIntegrity; -import com.application.logs.parsers.ParseCallTrace; -import javafx.animation.KeyFrame; -import javafx.animation.Timeline; -import javafx.application.Application; -import javafx.application.Platform; -import javafx.collections.FXCollections; -import javafx.collections.ObservableList; -import javafx.concurrent.Task; -import javafx.embed.swing.SwingFXUtils; -import javafx.event.ActionEvent; -import javafx.event.EventHandler; -import javafx.geometry.*; -import javafx.scene.Group; -import javafx.scene.Node; -import javafx.scene.Scene; -import javafx.scene.SnapshotParameters; -import javafx.scene.control.*; -import javafx.scene.image.WritableImage; -import javafx.scene.layout.*; -import javafx.scene.paint.Color; -import javafx.scene.text.Font; -import javafx.scene.text.FontWeight; -import javafx.stage.FileChooser; -import javafx.stage.Modality; -import javafx.stage.Stage; -import javafx.util.Duration; -import org.controlsfx.glyphfont.FontAwesome; -import org.controlsfx.glyphfont.Glyph; - -import javax.imageio.ImageIO; -import java.io.File; -import java.io.IOException; -import java.sql.DatabaseMetaData; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.*; -import java.util.concurrent.atomic.AtomicInteger; - -public class Main extends Application { - - - // Main UI screen - private Graph graph; - Model model; - private BorderPane root; - private ConvertDBtoElementTree convertDBtoElementTree; - private Stage primaryStage; - - // Information panel. - private boolean methodDefnFileSet; - private boolean callTraceFileSet; - - private Glyph methodDefnInfoGlyph; - private String methodDefnInfoString = "Select Method Definition log file."; - private Label methodDefnInfoLabel; - - private Glyph callTraceInfoGlyph; - private String callTraceInfoString = "Select Call Trace log file."; - private Label callTraceInfoLabel; - - private Glyph runInfoGlyph; - - private FlowPane instructionsNode; - - // Menu bar - private MenuBar menuBar; - - private Menu fileMenu; // File menu button - private MenuItem chooseMethodDefnMenuItem; - private MenuItem chooseCallTraceMenuItem; - private Glyph methodDefnGlyph; - private Glyph callTraceGlyph; - - private Menu runMenu; // Run menu button - private MenuItem runAnalysisMenuItem; - private Glyph runAnalysisGlyph; - private MenuItem resetMenuItem; - private Glyph resetGlyph; - private MenuItem runAnalysisHistoryMenuItem; - - private Menu saveImgMenu; // Save Image menu button - private MenuItem saveImgMenuItem; - private Glyph saveImgGlyph; - - private Menu goToMenu; - private Menu recentMenu; - private Glyph recentsGlyph; - private MenuItem clearHistoryMenuItem; - private Glyph clearHistoryGlyph; - - private Menu highlight; - private MenuItem highlightMenuItem; - private Glyph highlightItemsGlyph; - - private Menu debugMenu; // Debug menu button - private MenuItem printCellsMenuItem; - private MenuItem printEdgesMenuItem; - private MenuItem printHighlightsMenuItem; - - // Status bar - private Group statusBar; - private Label statusBarLabel = new Label(); - - // Thread list panel on left. - static ListView threadListView; - ObservableList threadsObsList; - - // Progress bar - Stage pStage; - Scene pScene; - ProgressBar progressBar; - VBox pVBox; - Label title; - Label progressText; - private static final int PROGRESS_BAR_WIDTH = 676; - - // Background tasks - Task task; - - private boolean firstTimeLoad = true; - - - @Override - public void start(Stage primaryStage) { - this.primaryStage = primaryStage; - root = new BorderPane(); - EventHandlers.saveRef(this); - - Scene scene = new Scene(root, 1000, 300); - - // URL url = getClass().getClassLoader().getResource("css/application.css"); - // String css = url.toExternalForm(); - // scene.getStylesheets().add(css); - // scene.getStylesheets().add(getClass().getResource("css/application.css").toExternalForm()); - - primaryStage.setScene(scene); - primaryStage.setTitle("Call Stack Visualization"); - primaryStage.show(); - - - // ***************** - // Display user confirmation window to reset or reload the application. - // ***************** - Task userConfirmation = new Task() { - @Override - protected Void call() throws Exception { - firstTimeLoad = isFirstLoad(); - System.out.println("Is first time load? : " + firstTimeLoad); - return null; - } - - @Override - protected void succeeded() { - super.succeeded(); - chooseReloadOrReset(firstTimeLoad); - } - - @Override - protected void failed() { - super.failed(); - - System.out.println("*******************************"); - System.out.println("FAILED BACKGROUND DB CHECK."); - System.out.println("*******************************"); - } - }; - - new Thread(userConfirmation).start(); - - - } - - private boolean isFirstLoad() { - try { - DatabaseMetaData dbm = DatabaseUtil.getConnection().getMetaData(); - ResultSet tables = dbm.getTables(null, null, TableNames.ELEMENT_TABLE, null); - if (tables.next()) { - methodDefnFileSet = callTraceFileSet = true; - return false; - } - } catch (SQLException e) { - e.printStackTrace(); - } - - return true; - } - - private void chooseReloadOrReset(boolean firstTimeLoad) { - if (firstTimeLoad) { - setUpInfoPanel(); - setUpMenu(); - setUpMenuActions(); - return; - } - - Alert userChoiceAlert = new Alert(Alert.AlertType.CONFIRMATION); - userChoiceAlert.setTitle("Start up options"); - userChoiceAlert.setHeaderText("Start new or reload previous log files?"); - userChoiceAlert.setContentText("You can either start fresh and load new log files or you may choose to reload previously loaded log files. If the log files are large, you can avoid long load times after the first load by clicking Reload previous in the successive use of this application."); - - ButtonType startFreshButtonType = new ButtonType("Start new"); - ButtonType reloadButtonType = new ButtonType("Reload previous"); - userChoiceAlert.getButtonTypes().setAll(startFreshButtonType, reloadButtonType); - userChoiceAlert.getDialogPane().setMinWidth(Region.USE_PREF_SIZE); - userChoiceAlert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); - - Optional res = userChoiceAlert.showAndWait(); - - if (res.isPresent() && res.get() == startFreshButtonType) { - // Start fresh. Load new configuration. - this.firstTimeLoad = true; - setUpInfoPanel(); - setUpMenu(); - setUpMenuActions(); - } else if (res.isPresent() && res.get() == reloadButtonType) { - // Reload previous configuration. - setUpMenuForReloads(); - setUpMenuActions(); - reload(); - } - } - - private void setUpMenu() { - List glyphs = new ArrayList<>(); - List menuItems = new ArrayList<>(); - - menuBar = new MenuBar(); - menuBar.setStyle(SizeProp.PADDING_MENU); - - // ***************** - // File Menu - // ***************** - - fileMenu = new Menu("File"); - methodDefnGlyph = new Glyph("FontAwesome", FontAwesome.Glyph.PLUS); - methodDefnGlyph.setColor(ColorProp.ENABLED); - // methodDefnGlyph.setPadding(SizeProp.INSETS_ICONS); - chooseMethodDefnMenuItem = new MenuItem("Select Method Definition log file", methodDefnGlyph); - // chooseMethodDefnMenuItem.setStyle(SizeProp.PADDING_SUBMENU); - - String font = "FontAwesome"; - callTraceGlyph = new Glyph(font, FontAwesome.Glyph.PLUS); - callTraceGlyph.setColor(Color.DIMGRAY); - // callTraceGlyph.setPadding(new Insets(2, 2, 2, 2)); - chooseCallTraceMenuItem = new MenuItem("Select Call Trace log file", callTraceGlyph); - // chooseCallTraceMenuItem.setStyle(SizeProp.PADDING_SUBMENU); - - fileMenu.getItems().addAll(chooseMethodDefnMenuItem, chooseCallTraceMenuItem); - menuItems.add(chooseMethodDefnMenuItem); - menuItems.add(chooseCallTraceMenuItem); - - // ***************** - // Run Menu - // ***************** - runMenu = new Menu("Run"); - - resetGlyph = new Glyph(font, FontAwesome.Glyph.RETWEET); - resetGlyph.setColor(ColorProp.ENABLED); - resetMenuItem = new MenuItem("Reset", resetGlyph); - // resetMenuItem.setStyle(SizeProp.PADDING_SUBMENU); - - runAnalysisGlyph = new Glyph(font, FontAwesome.Glyph.PLAY); - runAnalysisGlyph.setColor(ColorProp.DISABLED); - runAnalysisMenuItem = new MenuItem("Run", runAnalysisGlyph); - // runAnalysisMenuItem.setStyle(SizeProp.PADDING_SUBMENU); - runAnalysisMenuItem.setDisable(true); - - runAnalysisHistoryMenuItem = new MenuItem("Rerun latest files"); - runAnalysisHistoryMenuItem.setDisable(firstTimeLoad); - - runMenu.getItems().addAll(runAnalysisMenuItem, resetMenuItem, runAnalysisHistoryMenuItem); - menuItems.add(runAnalysisMenuItem); - menuItems.add(resetMenuItem); - - - // ***************** - // Save Image Menu - // ***************** - saveImgMenu = new Menu("Save Image"); - saveImgGlyph = new Glyph(font, FontAwesome.Glyph.PICTURE_ALT); - saveImgGlyph.setColor(ColorProp.ENABLED); - saveImgMenuItem = new MenuItem("Save Image", saveImgGlyph); - - saveImgMenu.getItems().add(saveImgMenuItem); - saveImgMenu.setDisable(true); - menuItems.add(saveImgMenuItem); - - - // ***************** - // Go To Menu - // ***************** - goToMenu = new Menu("Go To"); - recentsGlyph = new Glyph(font, FontAwesome.Glyph.HISTORY); - recentsGlyph.setColor(ColorProp.ENABLED); - recentMenu = new Menu("Recent nodes", recentsGlyph); - recentMenu.setStyle(SizeProp.PADDING_SUBMENU); - - clearHistoryGlyph = new Glyph(font, FontAwesome.Glyph.TRASH); - clearHistoryGlyph.setColor(ColorProp.ENABLED); - clearHistoryMenuItem = new MenuItem("Clear history", clearHistoryGlyph); - - goToMenu.getItems().addAll(recentMenu, clearHistoryMenuItem); - goToMenu.setDisable(true); - menuItems.add(clearHistoryMenuItem); - - // ***************** - // Highlights Menu - // ***************** - highlight = new Menu("Highlights"); - highlightItemsGlyph = new Glyph(font, FontAwesome.Glyph.FLAG); - highlightItemsGlyph.setColor(ColorProp.ENABLED); - highlightMenuItem = new MenuItem("Highlight method invocations", highlightItemsGlyph); - - highlight.getItems().add(highlightMenuItem); - highlight.setDisable(true); - menuItems.add(highlightMenuItem); - - // ***************** - // Debug Menu - // ***************** - debugMenu = new Menu("Debug"); - printCellsMenuItem = new MenuItem("Print circles on canvas to console"); - printEdgesMenuItem = new MenuItem("Print edges on canvas to console"); - printHighlightsMenuItem = new MenuItem("Print highlights on canvas to console"); - debugMenu.getItems().addAll(printCellsMenuItem, printEdgesMenuItem, printHighlightsMenuItem); - - // ***************** - // Main Menu - // ***************** - menuBar.getMenus().addAll(fileMenu, runMenu, saveImgMenu, goToMenu, highlight, debugMenu); - glyphs.addAll(Arrays.asList(methodDefnGlyph, callTraceGlyph, resetGlyph, runAnalysisGlyph, - saveImgGlyph, recentsGlyph, clearHistoryGlyph, highlightItemsGlyph)); - - menuItems.forEach(menuItem -> menuItem.setStyle(SizeProp.PADDING_SUBMENU)); - glyphs.forEach(glyph -> glyph.setStyle(SizeProp.PADDING_ICONS)); - root.setTop(menuBar); - } - - private void setUpMenuForReloads() { - List glyphs = new ArrayList<>(); - List menuItems = new ArrayList<>(); - String font = "FontAwesome"; - - menuBar = new MenuBar(); - menuBar.setStyle(SizeProp.PADDING_MENU); - - // ***************** - // File Menu - // ***************** - - fileMenu = new Menu("File"); - methodDefnGlyph = new Glyph(font, FontAwesome.Glyph.CHECK); - methodDefnGlyph.setColor(ColorProp.ENABLED_COLORFUL); - chooseMethodDefnMenuItem = new MenuItem("Select Method Definition log file", methodDefnGlyph); - - callTraceGlyph = new Glyph(font, FontAwesome.Glyph.CHECK); - callTraceGlyph.setColor(ColorProp.ENABLED_COLORFUL); - chooseCallTraceMenuItem = new MenuItem("Select Call Trace log file", callTraceGlyph); - - fileMenu.getItems().addAll(chooseMethodDefnMenuItem, chooseCallTraceMenuItem); - menuItems.add(chooseMethodDefnMenuItem); - menuItems.add(chooseCallTraceMenuItem); - - - // ***************** - // Run Menu - // ***************** - runMenu = new Menu("Run"); - - runAnalysisGlyph = new Glyph(font, FontAwesome.Glyph.PLAY); - runAnalysisGlyph.setColor(ColorProp.ENABLED_COLORFUL); - runAnalysisMenuItem = new MenuItem("Run", runAnalysisGlyph); - - resetGlyph = new Glyph(font, FontAwesome.Glyph.RETWEET); - resetGlyph.setColor(ColorProp.ENABLED); - resetMenuItem = new MenuItem("Reset", resetGlyph); - - runAnalysisHistoryMenuItem = new MenuItem("Rerun latest files"); - runAnalysisHistoryMenuItem.setDisable(firstTimeLoad); - - runMenu.getItems().addAll(runAnalysisMenuItem, resetMenuItem, runAnalysisHistoryMenuItem); - - // runMenu.getItems().addAll(runAnalysisMenuItem, resetMenuItem); - menuItems.add(runAnalysisMenuItem); - menuItems.add(resetMenuItem); - - - // ***************** - // Save Image Menu - // ***************** - saveImgMenu = new Menu("Save Image"); - saveImgGlyph = new Glyph(font, FontAwesome.Glyph.PICTURE_ALT); - saveImgGlyph.setColor(ColorProp.ENABLED_COLORFUL); - saveImgMenuItem = new MenuItem("Save Image", saveImgGlyph); - - saveImgMenu.getItems().add(saveImgMenuItem); - menuItems.add(saveImgMenuItem); - - - // ***************** - // Go To Menu - // ***************** - goToMenu = new Menu("Go To"); - recentsGlyph = new Glyph(font, FontAwesome.Glyph.HISTORY); - recentsGlyph.setColor(ColorProp.ENABLED_COLORFUL); - recentMenu = new Menu("Recent nodes", recentsGlyph); - recentMenu.setStyle(SizeProp.PADDING_SUBMENU); - - clearHistoryGlyph = new Glyph(font, FontAwesome.Glyph.TRASH); - clearHistoryGlyph.setColor(ColorProp.ENABLED_COLORFUL); - clearHistoryMenuItem = new MenuItem("Clear history", clearHistoryGlyph); - - goToMenu.getItems().addAll(recentMenu, clearHistoryMenuItem); - menuItems.add(clearHistoryMenuItem); - - // Highlight method invocations menu. - highlight = new Menu("Highlights"); - highlightItemsGlyph = new Glyph(font, FontAwesome.Glyph.FLAG); - highlightItemsGlyph.setColor(ColorProp.ENABLED_COLORFUL); - highlightMenuItem = new MenuItem("Highlight method invocations", highlightItemsGlyph); - - highlight.getItems().add(highlightMenuItem); - menuItems.add(highlightMenuItem); - - // ***************** - // Debug Menu - // ***************** - debugMenu = new Menu("Debug"); - printCellsMenuItem = new MenuItem("Print circles on canvas to console"); - printEdgesMenuItem = new MenuItem("Print edges on canvas to console"); - printHighlightsMenuItem = new MenuItem("Print highlights on canvas to console"); - debugMenu.getItems().addAll(printCellsMenuItem, printEdgesMenuItem, printHighlightsMenuItem); - - // Main menu - menuBar.getMenus().addAll(fileMenu, runMenu, saveImgMenu, goToMenu, highlight, debugMenu); - glyphs.addAll(Arrays.asList(methodDefnGlyph, callTraceGlyph, resetGlyph, runAnalysisGlyph, - saveImgGlyph, recentsGlyph, clearHistoryGlyph, highlightItemsGlyph)); - - menuItems.forEach(menuItem -> menuItem.setStyle(SizeProp.PADDING_SUBMENU)); - glyphs.forEach(glyph -> glyph.setStyle(SizeProp.PADDING_ICONS)); - root.setTop(menuBar); - } - - private void setUpMenuActions() { - System.out.println("Main::setUpMenuActions: method started"); - - chooseMethodDefnMenuItem.setOnAction(event -> { - File methodDefnFile = chooseLogFile("MethodDefinition"); - if (methodDefnFile != null) { - - // Menu buttons related - MethodDefinitionLogFile.setFile(methodDefnFile); - methodDefnGlyph.setIcon(FontAwesome.Glyph.CHECK); - - if (firstTimeLoad) { - // Change icons and colors in instructions panel - methodDefnInfoLabel.setText(methodDefnInfoString + " File selected : " + methodDefnFile.getName()); - - methodDefnInfoGlyph.setIcon(FontAwesome.Glyph.CHECK); - methodDefnInfoGlyph.setColor(ColorProp.ENABLED_COLORFUL); - callTraceInfoGlyph.setColor(ColorProp.ENABLED_COLORFUL); - } - - changeBool("methodDefnFileSet", true); - } - }); - - chooseCallTraceMenuItem.setOnAction(event -> { - File callTraceFile = chooseLogFile("CallTrace"); - if (callTraceFile != null) { - // Menu buttons related - CallTraceLogFile.setFile(callTraceFile); - callTraceGlyph.setIcon(FontAwesome.Glyph.CHECK); - - if (firstTimeLoad) { - // Change icons and colors in instructions panel - methodDefnInfoGlyph.setColor(ColorProp.ENABLED_COLORFUL); - - callTraceInfoLabel.setText(callTraceInfoString + " File selected : " + callTraceFile.getName()); - callTraceInfoGlyph.setIcon(FontAwesome.Glyph.CHECK); - callTraceInfoGlyph.setColor(ColorProp.ENABLED_COLORFUL); - } - - changeBool("callTraceFileSet", true); - } - }); - - runAnalysisMenuItem.setOnAction(event -> { - setUpProgressBar(); - reload(); - - if (firstTimeLoad) { - // Change icons and colors in instructions panel - runInfoGlyph.setIcon(FontAwesome.Glyph.CHECK); - runInfoGlyph.setColor(ColorProp.ENABLED_COLORFUL); - - saveImgMenu.setDisable(false); - goToMenu.setDisable(false); - highlight.setDisable(false); - } - - }); - - resetMenuItem.setOnAction(event -> { - reset(); - methodDefnGlyph.setIcon(FontAwesome.Glyph.PLUS); - callTraceGlyph.setIcon(FontAwesome.Glyph.PLUS); - }); - - runAnalysisHistoryMenuItem.setOnAction(event -> { - methodDefnFileSet = callTraceFileSet = true; - reload(); - }); - - // Capture and save the currently loaded UI tree. - saveImgMenuItem.setOnAction(event -> saveUIImage()); - - - // Populate recentMenu. - goToMenu.setOnShowing(event -> { - recentMenu.getItems().clear(); - graph.getRecentLocationsMap().entrySet().forEach(entry -> { - MenuItem nodeLocation = new MenuItem(); - nodeLocation.setText(entry.getKey()); - nodeLocation.setOnAction(event1 -> { - String targetThreadId = String.valueOf(entry.getValue().threadId); - if (!targetThreadId.equals(currentSelectedThread)) - showThread(targetThreadId); - - ConvertDBtoElementTree.resetRegions(); - - Timeline idleWait = new Timeline(new KeyFrame(Duration.millis(100), new EventHandler() { - @Override - public void handle(ActionEvent event) { - graph.moveScrollPane( - graph.getHValue(entry.getValue().x), - graph.getVValue(entry.getValue().y) - ); - } - })); - - idleWait.setCycleCount(1); - - makeSelection(targetThreadId); - idleWait.play(); - - }); - - recentMenu.getItems().add(nodeLocation); - }); - }); - - clearHistoryMenuItem.setOnAction(event -> graph.clearRecents()); - - // highlightMenuItem.setOnAction(event -> setUpMethodsWindow()); - highlightMenuItem.setOnAction(event -> setUpHighlightsWindow()); - - printCellsMenuItem.setOnAction(event -> { - System.out.println("-----------Cells on canvas ------------------------"); - graph.getModel().getCircleCellsOnUI().keySet().stream().sorted(Comparator.comparingInt(Integer::valueOf)).forEach(id -> { - System.out.print(id + ", "); - }); - System.out.println(); - System.out.println("---------------------------------------------------"); - }); - - printEdgesMenuItem.setOnAction(event -> { - System.out.println("-----------Edges on canvas ------------------------"); - graph.getModel().getEdgesOnUI().keySet().stream().sorted(Comparator.comparingInt(Integer::valueOf)).forEach(id -> { - System.out.print(id + ", "); - }); - System.out.println(); - System.out.println("---------------------------------------------------"); - }); - - printHighlightsMenuItem.setOnAction(event -> { - System.out.println("-----------Highlights on canvas --------------------"); - graph.getModel().getHighlightsOnUI().keySet().stream().sorted().forEach(id -> { - System.out.print(id + ", "); - }); - System.out.println(); - System.out.println("---------------------------------------------------"); - }); - - // System.out.println("Main::setUpMenuActions: method ended"); - } - - public String getCurrentSelectedThread() { - return currentSelectedThread; - } - - private String currentSelectedThread; - - public void resetFromOutside() { - System.out.println("Main::resetFromOutside: method start"); - reset(); - methodDefnGlyph.setIcon(FontAwesome.Glyph.PLUS); - callTraceGlyph.setIcon(FontAwesome.Glyph.PLUS); - System.out.println("Main::resetFromOutside: method end"); - - } - - public void setUpStatusBar() { - statusBar = new Group(); - statusBarLabel.setText("Application ready."); - statusBar.getChildren().add(statusBarLabel); - root.setBottom(statusBar); - } - - public void setStatus(String str) { - statusBarLabel.setText(str); - } - - private void reset() { - System.out.println("Main::reset: method start"); - root.setCenter(null); - root.setLeft(null); - runAnalysisMenuItem.setDisable(true); - goToMenu.setDisable(true); - saveImgMenu.setDisable(true); - - resetInstructionsPanel(); - resetHighlights(); - EventHandlers.resetEventHandlers(); - - ConvertDBtoElementTree.resetRegions(); - System.out.println("Main::reset: method end"); - } - - private void reload() { - if (!methodDefnFileSet || !callTraceFileSet) { - System.out.println("Returning without effect"); - return; - } - addGraphCellComponents(); - } - - private void dbOnReload() { - String resetCollapsedValOnCells = "UPDATE " + TableNames.ELEMENT_TABLE + " SET COLLAPSED = 0"; - String resetCollapsedValOnEdges = "UPDATE " + TableNames.EDGE_TABLE+ " SET COLLAPSED = 0"; - - Platform.runLater(() -> { - DatabaseUtil.executeUpdate(resetCollapsedValOnCells); - DatabaseUtil.executeUpdate(resetCollapsedValOnEdges); - }); - - } - - private void resetCenterLayout() { - // Layout Center - graph = null; - root.setCenter(null); - - graph = new Graph(); - setUpStatusBar(); - convertDBtoElementTree.setGraph(graph); - root.setCenter(graph.getScrollPane()); - ((ZoomableScrollPane) graph.getScrollPane()).saveRef(this); - } - - public void setUpNavigationBar() { - HBox hBox = new HBox(); - Button goToParent = new Button("Parent"); - Button goToChildren = new Button("Children"); - Button goUpSigbling = new Button("Up Sibling"); - Button goDownSigbling = new Button("Down Sibling"); - - hBox.getChildren().addAll(goToParent, goUpSigbling, goDownSigbling, goToChildren); - root.setBottom(hBox); - - goToParent.setOnAction(event -> { - Node node = (Node) event.getSource(); - CircleCell cell = (CircleCell) node; - getNextElementToGO("up", cell); - - // Go To Parent - // When an element is clicked. Highlight it. - // when go to parent is clicked. - // unhighlight element. - // From element table - // Get its element id. Get its parent id. - // Get clicked cell's parent cell coordinates. - // scroll to parent. - // highlight parent. - - // Go To First child. - // When an element is clicked. Highlight it. - // when go to child is clicked. - // unhighlight element. - // From element table - // Get its element id. Get its child's id. - // Get clicked cell's child cell coordinates. - // scroll to child - // highlight parent. - - - }); - } - - private void getNextElementToGO(String direction, CircleCell cell) { - switch (direction) { - case "up": - // Get parent element record. - ResultSet rs = ElementDAOImpl.selectWhere("id = (Select PARENT_ID FROM " + TableNames.ELEMENT_TABLE + " WHERE ID = " + cell.getCellId()); - - try { - if (rs.next()) { - double xCord = rs.getDouble("BOUND_BOX_X_COORDINATE"); - double yCord = rs.getDouble("BOUND_BOX_Y_COORDINATE"); - - double hValue = graph.getHValue(xCord); - double vValue = graph.getVValue(yCord); - graph.moveScrollPane(hValue, vValue); - - } - - break; - } catch (SQLException e) { - e.printStackTrace(); - } - } - } - - private void setUpThreadsView() { - /* - Setup the threads list view on the left. - */ - - // List to back the UI List view - threadsObsList = FXCollections.observableArrayList(); - - // UI List View to display all threads - threadListView = new ListView<>(); - threadListView.setItems(threadsObsList); - - threadListView.setOnMouseClicked(event -> { - String selectedItem = threadListView.getSelectionModel().getSelectedItem(); - String threadId = selectedItem.split(" ")[1]; - ConvertDBtoElementTree.resetRegions(); - if (!currentSelectedThread.equalsIgnoreCase(threadId)) { - showThread(threadId); - } - }); - - // Get thread list and populate - threadsObsList.clear(); - - if (!firstTimeLoad) { - try (ResultSet threadsRS = DatabaseUtil.select("SELECT DISTINCT(THREAD_ID) FROM CALL_TRACE")) { - while (threadsRS.next()) { - int threadId = threadsRS.getInt("thread_id"); - threadsObsList.add("Thread: " + threadId); - } - } catch (SQLException e) { - e.printStackTrace(); - } - - } else { - - ConvertDBtoElementTree.greatGrandParent.getChildren().forEach(element -> { - Element child = element.getChildren().get(0); - int callTraceId = -1; - if (child != null) callTraceId = child.getFkEnterCallTrace(); - try (ResultSet rs = CallTraceDAOImpl.selectWhere("id = " + callTraceId)) { - if (rs.next()) { - int threadId = rs.getInt("thread_id"); - threadsObsList.add("Thread: " + threadId); - } - } catch (SQLException e) { - e.printStackTrace(); - } - }); - } - - root.setLeft(threadListView); - - } - - - private int imgId = 0; - - private void saveUIImage() { - System.out.println("In saveUIImage."); - ScrollPane scrollPane = graph.getScrollPane(); - WritableImage image = scrollPane.snapshot(new SnapshotParameters(), null); - - File file = new File("screenshot-" + imgId + ".png"); - imgId++; - try { - ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file); - } catch (IOException e) { - System.out.println("saveUIImage exception"); - } - } - - private void addGraphCellComponents() { - convertDBtoElementTree = new ConvertDBtoElementTree(); - CheckFileIntegrity.saveRef(this); - EventHandlers.saveRef(convertDBtoElementTree); - - task = new Task() { - @Override - protected Void call() throws Exception { - // Reset Database - updateTitle("Resetting the Database."); - DatabaseUtil.resetDB(); - - // Check fileMenu integrity. - BytesRead bytesRead = new BytesRead( - 0, - MethodDefinitionLogFile.getFile().length() + 2 * CallTraceLogFile.getFile().length() - ); - updateTitle("Checking call trace fileMenu for errors."); - updateMessage("Please wait... total Bytes: " + bytesRead.total + " bytes processed: " + bytesRead.readSoFar); - updateProgress(bytesRead.readSoFar, bytesRead.total); - CheckFileIntegrity.checkFile(CallTraceLogFile.getFile(), bytesRead); - - // Parse Log files. - new ParseCallTrace().readFile(MethodDefinitionLogFile.getFile(), bytesRead, MethodDefnDAOImpl::insert); - updateTitle("Parsing log files."); - new ParseCallTrace().readFile(CallTraceLogFile.getFile(), bytesRead, - parsedLineList -> { - try { - int autoIncrementedId = CallTraceDAOImpl.insert(parsedLineList); - convertDBtoElementTree.StringToElementList(parsedLineList, autoIncrementedId); - updateMessage("Please wait... total Bytes: " + bytesRead.total + " bytes processed: " + bytesRead.readSoFar); - updateProgress(bytesRead.readSoFar, bytesRead.total); - Main.this.updateProgress(bytesRead); - } catch (SQLException | ClassNotFoundException | IllegalAccessException | InstantiationException e) { // Todo Create a custom exception class and clean this. - e.printStackTrace(); - } - }); - - - // Inserting log files into Database. - LinesInserted linesInserted = new LinesInserted( - 0, - 2 * ParseCallTrace.countNumberOfLines(CallTraceLogFile.getFile()) - ); - - updateTitle("Writing to DB."); - updateMessage("Please wait... total records: " + linesInserted.total + " records processed: " + linesInserted.insertedSoFar); - updateProgress(linesInserted.insertedSoFar, linesInserted.total); - convertDBtoElementTree.calculateElementProperties(); - - // Insert elements and properties into database - // convertDBtoElementTree.recursivelyInsertElementsIntoDB(convertDBtoElementTree.greatGrandParent); - - Element root = ConvertDBtoElementTree.greatGrandParent; - if (root == null) - return null; - - Queue queue = new LinkedList<>(); - queue.add(root); - - Element element; - while ((element = queue.poll()) != null) { - ElementDAOImpl.insert(element); - ElementToChildDAOImpl.insert( - element.getParent() == null ? -1 : element.getParent().getElementId(), - element.getElementId()); - - if (element.getChildren() != null) { - element.getChildren().forEach(queue::add); - } - - linesInserted.insertedSoFar++; - updateMessage("Please wait... total records: " + linesInserted.total + " records processed: " + linesInserted.insertedSoFar); - updateProgress(linesInserted.insertedSoFar, linesInserted.total); - } - - // Insert lines and properties into database. - convertDBtoElementTree.recursivelyInsertEdgeElementsIntoDB(ConvertDBtoElementTree.greatGrandParent); - return null; - } - - @Override - protected void succeeded() { - super.succeeded(); - // close the progress bar screen. - pStage.close(); - - // Load UI. - postDatabaseLoad(); - } - }; - - if (firstTimeLoad) { - progressBar.progressProperty().bind(task.progressProperty()); - title.textProperty().bind(task.titleProperty()); - progressText.textProperty().bind(task.messageProperty()); - - new Thread(task).start(); - } else { - postDatabaseLoad(); - } - } - - private void setUpProgressBar() { - progressBar = new ProgressBar(); - progressBar.setPrefWidth(PROGRESS_BAR_WIDTH); - - pStage = new Stage(); - pStage.initModality(Modality.APPLICATION_MODAL); - pStage.initOwner(null); - - title = new Label(""); - progressText = new Label(""); - - pVBox = new VBox(); - pVBox.getChildren().addAll(title, progressText, progressBar); - pVBox.setSpacing(SizeProp.SPACING); - pVBox.setPadding(new Insets(10, 5, 5, 5)); - pVBox.setAlignment(Pos.CENTER); - pScene = new Scene(pVBox); - pStage.setScene(pScene); - pStage.setTitle("Please wait while we crunch the logs"); - pStage.show(); - } - - private void updateProgress(BytesRead bytesRead) { - } - - private void postDatabaseLoad() { - resetCenterLayout(); - setUpThreadsView(); - - // Graph.drawPlaceHolderLines(); - - updateUi(); - - String firstThreadID = currentSelectedThread = threadsObsList.get(0).split(" ")[1]; - showThread(firstThreadID); - threadListView.getSelectionModel().select(0); - } - - // private void createCircleCellsRecursively(Element root, Model model) { - // if (root == null) { - // return; - // } - // createCircleCell(root, model); - // - // if (root.getChildren() != null) { - // root.getChildren() - // .forEach(ele -> createCircleCellsRecursively(ele, model)); - // } - // } - - // public void createCircleCell(Element root, Model model) { - // CircleCell targetCell = model.addCircleCell(String.valueOf(root.getElementId()), root); - // if (root.getParent() != null) { - // CircleCell sourceCell = root.getParent().getCircleCell(); - // model.addEdge(sourceCell, targetCell); - // } - // } - - // public Map fromDBToUI() { - // Map resMap = new HashMap(); - // // Do fast - // // monitor scroll hvalue changes and load more circles. - // try { - // ResultSet rs = ElementDAOImpl.selectWhere("parent_id = -1"); - // rs.next(); - // int grandParentId = rs.getInt("id"); - // float grandParentXCoordinate = rs.getFloat("bound_box_x_coordinate"); - // float grandParentYCoordinate = rs.getFloat("bound_box_y_coordinate"); - // CircleCell grandParentCell = new CircleCell(String.valueOf(grandParentId), grandParentXCoordinate, grandParentYCoordinate); - // model.addCell(grandParentCell); - // - // rs = ElementDAOImpl.selectWhere("parent_id = " + grandParentId); - // while (rs.next()) { - // int cellId = rs.getInt("id"); - // float cellXCoordinate = rs.getFloat("bound_box_x_coordinate"); - // float cellYCoordinate = rs.getFloat("bound_box_y_coordinate"); - // // For each level 1 element, draw on UI. - // CircleCell targetCell = new CircleCell(String.valueOf(cellId), cellXCoordinate, cellYCoordinate); - // model.addCell(targetCell); - // model.addEdge(grandParentCell, targetCell); - // resMap.put(cellId, targetCell); - // } - // } catch (SQLException e) { - // e.printStackTrace(); - // } - // return resMap; - // } - - public void showThread(String threadId) { - System.out.println("Main::showThread: clicked thread: " + threadId); - currentSelectedThread = threadId; - - // Prevent triggering listeners from modifying circleCellsOnUI, edgesOnUI and highlightsOnUI HashMaps - ZoomableScrollPane.turnOffListeners(); - - // graph.getModel().uiUpdateRequired = true; - convertDBtoElementTree.setCurrentThreadId(threadId); - convertDBtoElementTree.clearUI(); - updateUi(); - - // Prevent triggering listeners from modifying circleCellsOnUI, edgesOnUI and highlightsOnUI HashMaps - ZoomableScrollPane.turnOnListeners(); - graph.getModel().stackRectangles(); - System.out.println("Main::showThread: END"); - } - - public void updateUi() { - - if (convertDBtoElementTree != null && graph != null) { - // System.out.println("Main::updateUi: called by " + caller + " thread " + Thread.currentThread().getName()); - BoundingBox viewPortDims = graph.getViewPortDims(); - if (!convertDBtoElementTree.isUIDrawingRequired(viewPortDims)) { - // System.out.println("ConvertDBtoElementTree:loadUIComponentsInsideVisibleViewPort: UI redrawing not required."); - return; - } - convertDBtoElementTree.loadUIComponentsInsideVisibleViewPort(graph); - convertDBtoElementTree.removeUIComponentsFromInvisibleViewPort(graph); - // graph.myEndUpdate(); - } - // System.out.println("Main::updateUi: END called by " + caller); - } - - // private void addGraphComponents() { - // - // Model model = graph.getModel(); - // - // graph.beginUpdate(); - // - // // model.addCell("Cell A", CellType.RECTANGLE); - // // model.addCell("Cell B", CellType.RECTANGLE); - // // model.addCell("Cell C", CellType.RECTANGLE); - // // model.addCell("Cell D", CellType.TRIANGLE); - // // model.addCell("Cell E", CellType.TRIANGLE); - // // model.addCell("Cell F", CellType.RECTANGLE); - // // model.addCell("Cell G", CellType.RECTANGLE); - // model.addCell("Cell A", CellType.RECTANGLE); - // model.addCell("Cell B", CellType.RECTANGLE); - // model.addCell("Cell C", CellType.RECTANGLE); - // model.addCell("Cell D", CellType.RECTANGLE); - // model.addCell("Cell E", CellType.RECTANGLE); - // model.addCell("Cell F", CellType.RECTANGLE); - // model.addCell("Cell G", CellType.RECTANGLE); - // model.addCell("Cell H", CellType.RECTANGLE); - // model.addCell("Cell I", CellType.RECTANGLE); - // model.addCell("Cell J", CellType.RECTANGLE); - // model.addCell("Cell K", CellType.RECTANGLE); - // - // model.addEdge("Cell A", "Cell B"); - // model.addEdge("Cell A", "Cell C"); - // // model.addEdge("Cell B", "Cell C"); - // model.addEdge("Cell C", "Cell D"); - // model.addEdge("Cell B", "Cell E"); - // model.addEdge("Cell D", "Cell F"); - // model.addEdge("Cell D", "Cell G"); - // model.addEdge("Cell G", "Cell H"); - // model.addEdge("Cell G", "Cell I"); - // model.addEdge("Cell G", "Cell J"); - // model.addEdge("Cell G", "Cell K"); - // - // graph.endUpdate(); - // } - - public static void main(String[] args) { - launch(args); - } - - public static void makeSelection(String threadId) { - // Platform.runLater(() -> threadListView.getSelectionModel().select("Thread: " + threadId)); - threadListView.getSelectionModel().select("Thread: " + threadId); - } - - private File chooseLogFile(String logType) { - FileChooser fileChooser = new FileChooser(); - fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Text Files", "*.txt")); - - if (logType.equalsIgnoreCase("CallTrace")) { - fileChooser.setTitle("Choose call trace log fileMenu."); - } else { - fileChooser.setTitle("Choose method definition log fileMenu."); - } - - File logFile = fileChooser.showOpenDialog(primaryStage); - if (logFile != null) { - return logFile; - } - - return null; - } - - private void changeBool(String type, boolean val) { - if (type.equalsIgnoreCase("methodDefnFileSet")) { - methodDefnFileSet = val; - } else { - if (type.equalsIgnoreCase("callTraceFileSet")) - callTraceFileSet = val; - } - - if (methodDefnFileSet && callTraceFileSet) { - runAnalysisMenuItem.setDisable(false); - - // Menu buttons related. - runAnalysisGlyph.setColor(ColorProp.ENABLED); - - // Change icons and colors in instructions panel - runInfoGlyph.setIcon(FontAwesome.Glyph.ARROW_RIGHT); - runInfoGlyph.setColor(ColorProp.ENABLED_COLORFUL); - } - } - - private void resetInstructionsPanel() { - changeBool("methodDefnFileSet", false); - changeBool("callTraceFileSet", false); - setUpInfoPanel(); - } - - private void setUpInfoPanel() { - instructionsNode = new FlowPane(); - - /* - * root.setCenter() has to be invoked before root.setTop(). Otherwise, methodDefnInfoLabel will go blank. - * I do not know the reason why this is happening. - * */ - root.setCenter(instructionsNode); - - methodDefnInfoGlyph = new Glyph("FontAwesome", FontAwesome.Glyph.ARROW_RIGHT); - methodDefnInfoGlyph.setColor(ColorProp.ENABLED_COLORFUL); - methodDefnInfoLabel = new Label(methodDefnInfoString, methodDefnInfoGlyph); - - callTraceInfoGlyph = new Glyph("FontAwesome", FontAwesome.Glyph.ARROW_RIGHT); - callTraceInfoGlyph.setColor(ColorProp.ENABLED); - callTraceInfoLabel = new Label(callTraceInfoString, callTraceInfoGlyph); - - - runInfoGlyph = new Glyph("FontAwesome", FontAwesome.Glyph.ARROW_RIGHT); - runInfoGlyph.setColor(ColorProp.DISABLED); - String runInfoString = "Click run."; - Label runInfoLabel = new Label(runInfoString, runInfoGlyph); - - instructionsNode.getChildren().addAll(methodDefnInfoLabel, callTraceInfoLabel, runInfoLabel); - instructionsNode.setAlignment(Pos.CENTER); - instructionsNode.setOrientation(Orientation.VERTICAL); - instructionsNode.setPadding(new Insets(5, 5, 5, 5)); - instructionsNode.setVgap(10); - } - - public class BytesRead { - public long readSoFar = 0; - long total = 0; - - BytesRead(long readSoFar, long totalBytes) { - this.readSoFar = readSoFar; - this.total = totalBytes; - } - } - - public class LinesInserted { - long insertedSoFar = 0; - long total = 0; - - LinesInserted(long insertedSoFar, long totalBytes) { - this.insertedSoFar = insertedSoFar; - this.total = totalBytes; - } - } - - - private Stage mStage; - private Button applyButton; - private Button cancelButton; - private VBox vBox; - - private boolean firstTimeSetUpHighlightsWindowCall = true; - - public Map firstCBMap; - public Map secondCBMap; - private Map colorsMap; - private boolean anyColorChange = false; - - private void firstTimeSetUpHighlightsWindow() { - if (!firstTimeSetUpHighlightsWindowCall) - return; - - firstTimeSetUpHighlightsWindowCall = false; - - firstCBMap = new HashMap<>(); - secondCBMap = new HashMap<>(); - colorsMap = new HashMap<>(); - anyColorChange = false; - - GridPane gridPane = new GridPane(); - gridPane.setPadding(SizeProp.INSETS); - gridPane.setHgap(10); - gridPane.setVgap(10); - gridPane.setMinHeight(GridPane.USE_PREF_SIZE); - gridPane.setAlignment(Pos.TOP_CENTER); - - Label headingCol1 = new Label("Package and method name"); - headingCol1.setWrapText(true); - headingCol1.setFont(Font.font("Verdana", FontWeight.BOLD, headingCol1.getFont().getSize() * 1.1)); - GridPane.setConstraints(headingCol1, 0, 0); - GridPane.setHalignment(headingCol1, HPos.CENTER); - - Label headingCol2 = new Label("Highlight method only"); - headingCol2.setWrapText(true); - headingCol2.setFont(Font.font("Verdana", FontWeight.BOLD, headingCol2.getFont().getSize() * 1.1)); - GridPane.setConstraints(headingCol2, 1, 0); - GridPane.setHalignment(headingCol2, HPos.CENTER); - - Label headingCol3 = new Label("Highlight subtree"); - headingCol3.setWrapText(true); - headingCol3.setFont(Font.font("Verdana", FontWeight.BOLD, headingCol3.getFont().getSize() * 1.1)); - GridPane.setConstraints(headingCol3, 2, 0); - GridPane.setHalignment(headingCol3, HPos.CENTER); - - - Label headingCol4 = new Label("Choose color"); - headingCol4.setWrapText(true); - headingCol4.setFont(Font.font("Verdana", FontWeight.BOLD, headingCol4.getFont().getSize() * 1.1)); - GridPane.setConstraints(headingCol4, 3, 0); - GridPane.setHalignment(headingCol4, HPos.CENTER); - - - gridPane.getChildren().addAll( - headingCol1, headingCol2, headingCol3, headingCol4 - ); - - applyButton = new Button("Apply"); - applyButton.setAlignment(Pos.CENTER_RIGHT); - - cancelButton = new Button("Cancel"); - cancelButton.setAlignment(Pos.CENTER_RIGHT); - - Pane hSpacer = new Pane(); - hSpacer.setMinSize(10, 1); - HBox.setHgrow(hSpacer, Priority.ALWAYS); - - - ScrollPane scrollPane = new ScrollPane(); - scrollPane.setContent(gridPane); - scrollPane.setFitToHeight(true); - scrollPane.setFitToWidth(true); - - Pane vSpacer = new Pane(); - vSpacer.setMinSize(10, 1); - VBox.setVgrow(vSpacer, Priority.ALWAYS); - - HBox hBox = new HBox(hSpacer, cancelButton, applyButton); - hBox.setPadding(SizeProp.INSETS); - hBox.setSpacing(20); - hBox.setAlignment(Pos.BOTTOM_CENTER); - - vBox = new VBox(SizeProp.SPACING); - vBox.setPrefHeight(VBox.USE_PREF_SIZE); - vBox.setPadding(SizeProp.INSETS); - - vBox.getChildren().addAll(scrollPane, vSpacer, hBox); - - // For debugging purposes. Shows backgrounds in colors. - // hBox.setStyle("-fx-background-color: #ffb85f"); - // vBox.setStyle("-fx-background-color: yellow"); - // gridPane.setStyle("-fx-background-color: #4dfff3"); - // scrollPane.setStyle("-fx-background-color: #ffb2b3"); - - - // mRootGroup.getChildren().add(); - Scene mScene = new Scene(vBox, 1000, 500); - mStage = new Stage(); - mStage.setTitle("Choose highlighting options"); - mStage.setScene(mScene); - - LinkedList methodNamesList = new LinkedList<>(); - - // Fetch all methods from method definition fileMenu and display on UI. - Task onStageLoad = new Task() { - @Override - protected Void call() throws Exception { - // Fetch all methods from method definition fileMenu. - ResultSet rs = DatabaseUtil.select("SELECT * FROM " + TableNames.METHOD_DEFINITION_TABLE); - while (rs.next()) { - String methodName = rs.getString("METHOD_NAME"); - String packageName = rs.getString("PACKAGE_NAME"); - methodNamesList.add(packageName + "." + methodName); - } - - return null; - } - - @Override - protected void succeeded() { - super.succeeded(); - final AtomicInteger rowInd = new AtomicInteger(1); - - // Display the methods on UI - methodNamesList.forEach(fullName -> { - - // Label - Label name = new Label(fullName); - name.setWrapText(true); - // name.setMaxWidth(250); - GridPane.setConstraints(name, 0, rowInd.get()); - GridPane.setHalignment(name, HPos.CENTER); - GridPane.setHgrow(name, Priority.ALWAYS); - - - // First checkbox - CheckBox firstCB = new CheckBox(); - GridPane.setConstraints(firstCB, 1, rowInd.get()); - GridPane.setHalignment(firstCB, HPos.CENTER); - GridPane.setValignment(firstCB, VPos.CENTER); - GridPane.setHgrow(firstCB, Priority.ALWAYS); - firstCB.selectedProperty().addListener((observable, oldValue, newValue) -> { - if (newValue) { - firstCBMap.put(fullName, firstCB); - } else { - firstCBMap.remove(fullName); - } - }); - - - // Second checkbox - CheckBox secondCB = new CheckBox(); - // secondCB.setAlignment(Pos.CENTER); - GridPane.setConstraints(secondCB, 2, rowInd.get()); - GridPane.setHalignment(secondCB, HPos.CENTER); - GridPane.setValignment(secondCB, VPos.CENTER); - GridPane.setHgrow(secondCB, Priority.ALWAYS); - secondCB.selectedProperty().addListener((observable, oldValue, newValue) -> { - if (newValue) secondCBMap.put(fullName, secondCB); - else secondCBMap.remove(fullName); - }); - - - // Color picker - ColorPicker colorPicker = new ColorPicker(Color.AQUAMARINE); - colorPicker.setOnAction(event -> { - anyColorChange = true; - colorsMap.put(fullName, colorPicker.getValue()); - // System.out.println(colorPicker.getValue()); - }); - colorPicker.getStyleClass().add("button"); - colorPicker.setStyle( - "-fx-color-label-visible: false; " + - "-fx-background-radius: 15 15 15 15;"); - GridPane.setConstraints(colorPicker, 3, rowInd.get()); - GridPane.setHalignment(colorPicker, HPos.CENTER); - GridPane.setValignment(colorPicker, VPos.CENTER); - GridPane.setHgrow(colorPicker, Priority.ALWAYS); - - // For debugging. - // Pane colorPane = new Pane(); - // colorPane.setStyle("-fx-background-color: #99ff85"); - // GridPane.setConstraints(colorPane, 2, rowInd.get()); - // Pane colorPane2 = new Pane(); - // colorPane2.setStyle("-fx-background-color: #e383ff"); - // GridPane.setConstraints(colorPane2, 1, rowInd.get()); - // gridPane.getChildren().addAll(name, colorPane2, firstCB, colorPane, secondCB, colorPicker); - - rowInd.incrementAndGet(); - - // Put every thing together - gridPane.getChildren().addAll(name, firstCB, secondCB, colorPicker); - - }); - } - }; - - new Thread(onStageLoad).start(); - - } - - private void setUpHighlightsWindow() { - - if (firstTimeSetUpHighlightsWindowCall) - firstTimeSetUpHighlightsWindow(); - - mStage.show(); - - /* - On Apply button click behaviour. - For each of the selected methods, insert the bound box properties into Highlights table if not already present. - */ - Task taskOnApply = new Task() { - @Override - protected Void call() throws Exception { - if (!HighlightDAOImpl.isTableCreated()) { - HighlightDAOImpl.createTable(); - } - - // For each of the selected methods, insert the bound box properties into Highlights table if not already present. - Statement statement = DatabaseUtil.getConnection().createStatement(); - firstCBMap.forEach((fullName, checkBox) -> addInsertQueryToStatement(fullName, statement, "SINGLE")); - - secondCBMap.forEach((fullName, checkBox) -> addInsertQueryToStatement(fullName, statement, "FULL")); - - // Delete records from HIGHLIGHT_ELEMENT if that method is not checked in the stage. - StringJoiner firstSJ = new StringJoiner("','", "'", "'"); - firstCBMap.forEach((fullName, checkBox) -> firstSJ.add(fullName)); - addDeleteQueryToStatement(firstSJ.toString(), statement, "SINGLE"); - - StringJoiner secondSJ = new StringJoiner("','", "'", "'"); - secondCBMap.forEach((fullName, checkBox) -> secondSJ.add(fullName)); - addDeleteQueryToStatement(secondSJ.toString(), statement, "FULL"); - - updateColors(statement); - - statement.executeBatch(); - - return null; - } - - @Override - protected void succeeded() { - super.succeeded(); - // System.out.println("Main::setUpHighlightsWindow::succeeded"); - graph.getModel().uiUpdateRequired = true; - updateUi(); - - // Stack highlights so that the larger ones are behind smaller ones. - graph.getModel().stackRectangles(); - } - }; - - applyButton.setOnAction(event -> { - new Thread(taskOnApply).start(); - mStage.close(); - }); - - cancelButton.setOnAction(event -> mStage.close()); - } - - private void addInsertQueryToStatement(String fullName, Statement statement, String highlightType) { - // System.out.println("Main.addInsertQueryToStatement: crafting query for " + fullName); - double startXOffset = 30; - double widthOffset = 0; - double startYOffset = -10; - double heightOffset = -20; - - String[] arr = fullName.split("\\."); - String methodName = arr[arr.length - 1]; - String packageName = fullName.substring(0, fullName.length() - methodName.length() - 1); - - String sqlSingle = "INSERT INTO " + TableNames.HIGHLIGHT_ELEMENT + " " + - "(ELEMENT_ID, METHOD_ID, THREAD_ID, HIGHLIGHT_TYPE, START_X, START_Y, WIDTH, HEIGHT, COLOR, COLLAPSED) " + - - "SELECT " + - - // ELEMENT_ID - TableNames.ELEMENT_TABLE + ".ID, " + - - // METHOD_ID - TableNames.METHOD_DEFINITION_TABLE + ".ID, " + - - // THREAD_ID - TableNames.CALL_TRACE_TABLE + ".THREAD_ID, " + - - // HIGHLIGHT_TYPE - "'" + highlightType + "', " + - - // START_X - TableNames.ELEMENT_TABLE + ".BOUND_BOX_X_TOP_LEFT + " + startXOffset + ", " + - - // START_Y - TableNames.ELEMENT_TABLE + ".BOUND_BOX_Y_TOP_LEFT + " + startYOffset + ", " + - - // WIDTH - (BoundBox.unitWidthFactor + widthOffset) + ", " + - - // HEIGHT - (BoundBox.unitHeightFactor + heightOffset) + ", " + - // "(" + TableNames.ELEMENT_TABLE + ".BOUND_BOX_X_TOP_RIGHT - " + TableNames.ELEMENT_TABLE + ".BOUND_BOX_X_TOP_LEFT), " + - // "(" + TableNames.ELEMENT_TABLE + ".BOUND_BOX_Y_BOTTOM_LEFT - " + TableNames.ELEMENT_TABLE + ".BOUND_BOX_Y_TOP_LEFT), " + - - // HIGHLIGHT COLOR - "'" + colorsMap.getOrDefault(fullName, Color.AQUAMARINE) + "'," + - - // COLLAPSED - "0 " + - - "FROM " + TableNames.ELEMENT_TABLE + " " + - "JOIN " + TableNames.CALL_TRACE_TABLE + " ON " + TableNames.ELEMENT_TABLE + ".ID_ENTER_CALL_TRACE = " + TableNames.CALL_TRACE_TABLE + ".ID " + - "JOIN " + TableNames.METHOD_DEFINITION_TABLE + " ON " + TableNames.CALL_TRACE_TABLE + ".METHOD_ID = " + TableNames.METHOD_DEFINITION_TABLE + ".ID " + - "WHERE " + TableNames.METHOD_DEFINITION_TABLE + ".METHOD_NAME = '" + methodName + "' " + - "AND " + TableNames.METHOD_DEFINITION_TABLE + ".PACKAGE_NAME = '" + packageName + "' " + - "AND NOT EXISTS " + - "(SELECT * FROM " + TableNames.HIGHLIGHT_ELEMENT + " " + - "WHERE " + TableNames.HIGHLIGHT_ELEMENT + ".METHOD_ID = " + TableNames.METHOD_DEFINITION_TABLE + ".ID " + - "AND " + TableNames.HIGHLIGHT_ELEMENT + ".HIGHLIGHT_TYPE = '" + highlightType + "')"; - - - // Get thread id for the method. There can only be a single thread. - // If method with same name was invoked by another thread, then its package name would different. - String getThreadSQL = "SELECT thread_id " + - "FROM " + TableNames.CALL_TRACE_TABLE + " " + - "JOIN method_defn ON " + TableNames.CALL_TRACE_TABLE + ".method_id " + - "= " + - TableNames.METHOD_DEFINITION_TABLE + ".id " + - "AND " + TableNames.METHOD_DEFINITION_TABLE + ".METHOD_NAME = '" + methodName + "' " + - "AND " + TableNames.METHOD_DEFINITION_TABLE + ".PACKAGE_NAME = '" + packageName + "'"; - - ResultSet getThreadInfoRS = DatabaseUtil.select(getThreadSQL); - - // System.out.println("get thread query:"); - // System.out.println(getThreadSQL); - - int threadId = 0; - try { - while (getThreadInfoRS.next()) { - threadId = getThreadInfoRS.getInt("THREAD_ID"); - } - } catch (SQLException e) { - e.printStackTrace(); - } - - // System.out.println("Result threadId " + threadId); - - String sqlFull = "INSERT INTO " + TableNames.HIGHLIGHT_ELEMENT + " " + - "(ELEMENT_ID, METHOD_ID, THREAD_ID, HIGHLIGHT_TYPE, START_X, START_Y, WIDTH, HEIGHT, COLOR, COLLAPSED) " + - "SELECT " + - - // ELEMENT_ID - TableNames.ELEMENT_TABLE + ".ID, " + - - // METHOD_ID - TableNames.METHOD_DEFINITION_TABLE + ".ID, " + - - // THREAD_ID - TableNames.CALL_TRACE_TABLE + ".THREAD_ID, " + - - // HIGHLIGHT_TYPE - "'" + highlightType + "', " + - - // START_X - TableNames.ELEMENT_TABLE + ".BOUND_BOX_X_TOP_LEFT + " + startXOffset + ", " + - - // START_Y - TableNames.ELEMENT_TABLE + ".BOUND_BOX_Y_TOP_LEFT + " + startYOffset + ", " + - - // WIDTH - "CASE " + - "WHEN " + TableNames.ELEMENT_TABLE + ".COLLAPSED IN (0, 2) THEN " + - "((SELECT MAX(E1.BOUND_BOX_X_TOP_RIGHT) FROM " + TableNames.ELEMENT_TABLE + " AS E1 " + - "JOIN " + TableNames.CALL_TRACE_TABLE + " AS CT ON E1.ID_ENTER_CALL_TRACE = CT.ID " + - "WHERE E1.BOUND_BOX_Y_COORDINATE >= " + TableNames.ELEMENT_TABLE + ".BOUND_BOX_Y_TOP_LEFT " + - "AND E1.BOUND_BOX_Y_COORDINATE < " + TableNames.ELEMENT_TABLE + ".BOUND_BOX_Y_BOTTOM_LEFT " + - "AND CT.THREAD_ID = " + threadId + " " + - "AND (E1.COLLAPSED IN (0, 2) OR E1.ID = ELEMENT.ID)" + - // ") - " + TableNames.ELEMENT_TABLE + ".BOUND_BOX_X_TOP_LEFT + " + widthOffset + ") " + - ") - " + TableNames.ELEMENT_TABLE + ".BOUND_BOX_X_TOP_LEFT) " + - "ELSE " + (BoundBox.unitWidthFactor + widthOffset) + " " + - "END " + - ", " + - // TableNames.ELEMENT_TABLE + ".BOUND_BOX_X_BOTTOM_RIGHT - " + TableNames.ELEMENT_TABLE + ".BOUND_BOX_X_BOTTOM_LEFT + " + endOffset + "," + - - // HEIGHT - // "(SELECT MAX(E1.BOUND_BOX_Y_BOTTOM_RIGHT) FROM " + TableNames.ELEMENT_TABLE + " AS E1 " + - // "JOIN " + TableNames.CALL_TRACE_TABLE + " AS CT ON E1.ID_ENTER_CALL_TRACE = CT.ID " + - // "WHERE E1.BOUND_BOX_Y_COORDINATE >= " + TableNames.ELEMENT_TABLE + ".BOUND_BOX_Y_TOP_LEFT " + - // "AND E1.BOUND_BOX_Y_COORDINATE <= " + TableNames.ELEMENT_TABLE + ".BOUND_BOX_Y_BOTTOM_LEFT " + - // "AND E1.BOUND_BOX_X_COORDINATE >= " + TableNames.ELEMENT_TABLE + ".BOUND_BOX_X_TOP_LEFT " + - // "AND CT.THREAD_ID = " + threadId + ") - " + TableNames.ELEMENT_TABLE + ".BOUND_BOX_Y_TOP_LEFT + " + endOffset + ", " + - TableNames.ELEMENT_TABLE + ".BOUND_BOX_Y_BOTTOM_LEFT - " + TableNames.ELEMENT_TABLE + ".BOUND_BOX_Y_TOP_LEFT + " + heightOffset + "," + - - // COLOR - "'" + colorsMap.getOrDefault(fullName, Color.AQUAMARINE) + "', " + - - // COLLAPSED - "(SELECT " + - "CASE " + - "WHEN E1.COLLAPSED = 0 THEN 0 " + - "WHEN E1.COLLAPSED = 2 THEN 0 " + - "ELSE 1 " + - "END " + - "FROM " + TableNames.ELEMENT_TABLE + " AS E1 WHERE E1.ID = " + TableNames.ELEMENT_TABLE + ".ID) " + - - - "FROM " + TableNames.ELEMENT_TABLE + " " + - "JOIN " + TableNames.CALL_TRACE_TABLE + " ON " + TableNames.ELEMENT_TABLE + ".ID_ENTER_CALL_TRACE = " + TableNames.CALL_TRACE_TABLE + ".ID " + - "JOIN " + TableNames.METHOD_DEFINITION_TABLE + " ON " + TableNames.CALL_TRACE_TABLE + ".METHOD_ID = " + TableNames.METHOD_DEFINITION_TABLE + ".ID " + - "WHERE " + TableNames.METHOD_DEFINITION_TABLE + ".METHOD_NAME = '" + methodName + "' " + - "AND " + TableNames.METHOD_DEFINITION_TABLE + ".PACKAGE_NAME = '" + packageName + "' " + - "AND NOT EXISTS " + - "(SELECT * FROM " + TableNames.HIGHLIGHT_ELEMENT + " " + - "WHERE " + TableNames.HIGHLIGHT_ELEMENT + ".METHOD_ID = " + TableNames.METHOD_DEFINITION_TABLE + ".ID " + - "AND " + TableNames.HIGHLIGHT_ELEMENT + ".HIGHLIGHT_TYPE = '" + highlightType + "')"; - - String sql = highlightType.equalsIgnoreCase("SINGLE") ? sqlSingle : sqlFull; - - // System.out.println("Main::addInsertQueryToStatement: sql : " + sql); - try { - statement.addBatch(sql); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - private void addDeleteQueryToStatement(String fullNames, Statement statement, String highlightType) { - String sql = "DELETE FROM " + TableNames.HIGHLIGHT_ELEMENT + " " + - "WHERE HIGHLIGHT_TYPE = '" + highlightType + "' AND METHOD_ID NOT IN " + - "(SELECT ID FROM " + TableNames.METHOD_DEFINITION_TABLE + " " + - "WHERE (" + TableNames.METHOD_DEFINITION_TABLE + ".PACKAGE_NAME || '.' || " + TableNames.METHOD_DEFINITION_TABLE + ".METHOD_NAME) " + - "IN (" + fullNames + "))"; - - // System.out.println( "Main::addDeleteQueryToStatement: sql: " + sql); - - - try { - statement.addBatch(sql); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - private void updateColors(Statement statement) { - if (!anyColorChange) - return; - - anyColorChange = false; - - colorsMap.forEach((fullName, color) -> { - String sql = "UPDATE " + TableNames.HIGHLIGHT_ELEMENT + " SET COLOR = '" + color + "' " + - "WHERE METHOD_ID = (SELECT ID FROM " + TableNames.METHOD_DEFINITION_TABLE + " " + - "WHERE PACKAGE_NAME || '.' || METHOD_NAME = '" + fullName + "')"; - try { - statement.addBatch(sql); - } catch (SQLException e) { - e.printStackTrace(); - } - }); - } - - private void resetHighlights() { - // firstTimeSetUpMethodsWindowCall = true; - firstTimeSetUpHighlightsWindowCall = true; - highlight.setDisable(true); - } - -} \ No newline at end of file diff --git a/src/main/java/com/application/db/DAOImplementation/CallTraceDAOImpl.java b/src/main/java/com/application/db/DAOImplementation/CallTraceDAOImpl.java deleted file mode 100644 index 08b3177..0000000 --- a/src/main/java/com/application/db/DAOImplementation/CallTraceDAOImpl.java +++ /dev/null @@ -1,177 +0,0 @@ -package com.application.db.DAOImplementation; - -import com.application.db.DatabaseUtil; -import com.application.db.TableNames; - -import java.sql.*; -import java.util.List; - -import static com.application.db.TableNames.CALL_TRACE_TABLE; - -public class CallTraceDAOImpl { - // TODO: Create abstract classes for all these Impl classes. All common funtionality is implement by the default class. Rest of the methods are abstract. - // public static boolean isTableCreated = false; - - public static boolean isTableCreated() { - // System.out.println("starting isTableCreated"); - // if (!isTableCreated) {// No need to call DatabaseUtil method every time. Save time this way. - // System.out.println("CallTraceDAOImpl:isTableCreated: " + isTableCreated); - // isTableCreated = DatabaseUtil.isTableCreated(CALL_TRACE_TABLE); - // System.out.println("CallTraceDAOImpl:isTableCreated: " + isTableCreated); - // } - // System.out.println("ending isTableCreated"); - // return isTableCreated; - return DatabaseUtil.isTableCreated(TableNames.CALL_TRACE_TABLE); - } - - public static void createTable() { - // System.out.println("starting createTable"); - // System.out.println("CallTraceDAOImpl:createTable: " + isTableCreated()); - if (!isTableCreated()) { - try (Connection c = DatabaseUtil.getConnection(); Statement ps = c.createStatement()) { - sql = "CREATE TABLE " + CALL_TRACE_TABLE + " (" + - "id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), " + - "process_id INTEGER not null, " + - "thread_id INTEGER, " + - "method_id INTEGER, " + - "message VARCHAR(20), " + - "parameters VARCHAR(800), " + - "lockObjId VARCHAR(50), " + - // "time_instant VARCHAR(24)" + - "time_instant TIMESTAMP" + - ")"; - ps.execute(sql); - System.out.println("** Creating table " + TableNames.CALL_TRACE_TABLE); - } catch (SQLException e) { - e.printStackTrace(); - } - } - // System.out.println("ending createTable"); - } - - public static int insert(List val) - throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException{ - - int autoIncrementedId = -1; - // int processID = Integer.parseInt(readSoFar.get(0)); - // int threadID = Integer.parseInt(readSoFar.get(1)); - // int methodID = Integer.parseInt(readSoFar.get(2)); - // String eventType = readSoFar.get(3); - // String parameters = readSoFar.get(4); - // String time_instant = readSoFar.get(5); - - // TimeStamp | ProcessID | ThreadID | EventType |LockObjectID - // utc time format | 40948 | 9 | Wait-Enter |3986916 - - // TimeStamp | ProcessID | ThreadID | EventType | MethodID | Arguments - // 2017-03-31T17:00:19.305Z | 40948 | 9 | Enter | 1 | [] - // TimeStamp | ProcessID | ThreadID | EventType | MethodID - // 2017-03-31T17:00:19.305Z | 40948 | 9 | Enter | 1 - String time_instant = val.get(0); - // Instant instant = Instant.parse(time_instant); - // Timestamp timestamp = Timestamp.from(instant); - // java.sql.Timestamp sqlTimeStamp = new Timestamp(instant.toEpochMilli()); - - Timestamp timestamp = new Timestamp(Long.valueOf(time_instant)); - int processID = Integer.parseInt(val.get(1)); - int threadID = Integer.parseInt(val.get(2)); - String eventType = val.get(3); - int methodID = 0; - String parameters = ""; - String lockObjectId = ""; - - if (eventType.equalsIgnoreCase("ENTER")) { - methodID = Integer.parseInt(val.get(4)); - parameters = val.get(5); - // } else if (eventType.equalsIgnoreCase("EXIT")) { - // methodID = Integer.parseInt(readSoFar.get(4)); - } else if (eventType.equalsIgnoreCase("WAIT-ENTER") || eventType.equalsIgnoreCase("WAIT-EXIT") || - eventType.equalsIgnoreCase("NOTIFY-ENTER") || eventType.equalsIgnoreCase("NOTIFY-EXIT") || - eventType.equalsIgnoreCase("NOTIFYALL-ENTER") || eventType.equalsIgnoreCase("NOTIFYALL-EXIT")) { - lockObjectId = val.get(4); - } - // System.out.println("starting insert"); - // System.out.println("CallTraceDAOImpl:insert: " + isTableCreated()); - - if (!isTableCreated()) - createTable(); - String sql = null; - try (Connection c = DatabaseUtil.getConnection(); Statement ps = c.createStatement()) { - - // System.out.println("value of callTraceTableCreated: " + callTraceTableCreated); - sql = "INSERT INTO " + CALL_TRACE_TABLE + - "(" + - "process_id, " + - "thread_id, " + - "method_id, " + - "message, " + - "parameters, " + - "lockObjId, " + - "time_instant" + - ")" + - " VALUES("+ - processID + ", " + - threadID + ", " + - methodID + ", " + - "'" + eventType + "', " + - "'" + parameters + "', " + - "'" + lockObjectId + "', " + - // "'" + time_instant + "'" + - "{ts '" + timestamp + "'}" + - ")"; - - // System.out.println("Inserting into call trace the statement: " + sql); - ps.execute(sql, Statement.RETURN_GENERATED_KEYS); - ResultSet rs = ps.getGeneratedKeys(); - if (rs.next()) { - autoIncrementedId = rs.getInt(1); - } - - // autoIncrementedId = rs.getInt("ID"); - // System.out.println(TableNames.ELEMENT_TABLE + ": Inserted: " + sql); - } catch (SQLException e) { - System.out.println(" Exception caused by: " + sql); - e.printStackTrace(); - } - // System.out.println("ending insert"); - return autoIncrementedId; - } - - - public static void dropTable() { - // System.out.println("starting dropTable"); - if (isTableCreated()) { - try (Connection c = DatabaseUtil.getConnection(); Statement ps = c.createStatement()) { - String sql= "Drop table " + TableNames.CALL_TRACE_TABLE; - ps.executeUpdate(sql); - ps.close(); - System.out.println(">> Dropping table " + TableNames.CALL_TRACE_TABLE); - } catch (SQLException e) { - e.printStackTrace(); - } - } - // System.out.println("ending dropTable"); - } - - static Connection conn; - static Statement ps; - static String sql; - public static ResultSet selectWhere(String where) { - if (isTableCreated()) try { - conn = DatabaseUtil.getConnection(); - ps = conn.createStatement(); - sql = "SELECT * FROM " + CALL_TRACE_TABLE + " WHERE " + where; - // System.out.println(">>> we got " + sql); - ResultSet resultSet = ps.executeQuery(sql); - // resultSet.next(); - // System.out.println(resultSet.getInt("id")); - return resultSet; - } catch (SQLException e) { - System.out.println("Line that threw error: " + sql); - e.printStackTrace(); - } - throw new IllegalStateException("Table does not exist. Hence cannot fetch any rows from it."); - } - - -} diff --git a/src/main/java/com/application/db/DAOImplementation/EdgeDAOImpl.java b/src/main/java/com/application/db/DAOImplementation/EdgeDAOImpl.java deleted file mode 100644 index 5d8e20b..0000000 --- a/src/main/java/com/application/db/DAOImplementation/EdgeDAOImpl.java +++ /dev/null @@ -1,142 +0,0 @@ -package com.application.db.DAOImplementation; - -import com.application.db.DatabaseUtil; -import com.application.db.TableNames; -import com.application.fxgraph.ElementHelpers.EdgeElement; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; - -import static com.application.db.TableNames.EDGE_TABLE; - -public class EdgeDAOImpl { - // public static boolean isTableCreated = false; - - public static boolean isTableCreated() { - // System.out.println("starting isTableCreated"); - // if (!isTableCreated) {// No need to call DatabaseUtil method every time. Save time this way. - // System.out.println("ElementDAOImpl:isTableCreated: " + isTableCreated); - // isTableCreated = DatabaseUtil.isTableCreated(EDGE_TABLE); - // System.out.println("ElementDAOImpl:isTableCreated: " + isTableCreated); - // } - // System.out.println("ending isTableCreated"); - // return isTableCreated; - return DatabaseUtil.isTableCreated(TableNames.EDGE_TABLE); - } - - public static void createTable() { - // System.out.println("starting createTable"); - // System.out.println("ElementDAOImpl:createTable: " + isTableCreated()); - if (!isTableCreated()) { - try (Connection c = DatabaseUtil.getConnection(); Statement ps = c.createStatement()) { - String sql = "CREATE TABLE " + EDGE_TABLE + " (" + - "id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), " + - "fk_source_element_id INTEGER, " + - "fk_target_element_id INTEGER, " + - "start_x FLOAT, " + - "start_y FLOAT, " + - "end_x FLOAT, " + - "end_y FLOAT, " + - "collapsed INTEGER" + - ")"; - ps.execute(sql); - System.out.println("** Creating table " + TableNames.EDGE_TABLE); - } catch (SQLException e) { - e.printStackTrace(); - } - } - } - - public static void insert(EdgeElement edge) { - if (!isTableCreated()) - createTable(); - - String sql = null; - try (Connection c = DatabaseUtil.getConnection(); Statement ps = c.createStatement()) { - sql = "INSERT INTO " + EDGE_TABLE + " (" + - "fk_source_element_id, " + - "fk_target_element_id, " + - "start_x, " + - "start_y, " + - "end_x, " + - "end_y, " + - "collapsed) " + - " VALUES (" + - edge.getSourceElement().getElementId() + ", " + - edge.getTargetElement().getElementId() + ", " + - edge.getStartX() + ", " + - edge.getStartY() + ", " + - edge.getEndX() + ", " + - edge.getEndY() + ", " + - edge.getCollpased() + "" + - ")"; - - ps.execute(sql); - } catch (SQLException e) { - System.out.println(" Exception caused by: " + sql); - e.printStackTrace(); - } - } - - public static void dropTable() { - // System.out.println("starting dropTable"); - if (isTableCreated()) { - try (Connection c = DatabaseUtil.getConnection(); Statement ps = c.createStatement()) { - String sql= "Drop table " + EDGE_TABLE; - System.out.println(">> Dropping table " + TableNames.EDGE_TABLE); - - ps.execute(sql); - } catch (SQLException e) { - e.printStackTrace(); - } - } - // System.out.println("ending dropTable"); - } - - static Connection conn; - static Statement ps; - static String sql; - public static ResultSet selectWhere(String where) { - if (isTableCreated()) { - try { - conn = DatabaseUtil.getConnection(); - ps = conn.createStatement(); - sql = "SELECT * FROM " + EDGE_TABLE + " WHERE " + where; - // System.out.println(">>> we got " + sql); - ResultSet resultSet = ps.executeQuery(sql); - // System.out.println("Where: " + sql); - // resultSet.next(); - // System.out.println(resultSet.getInt("id")); - return resultSet; - } catch (SQLException e) { - System.out.println("Line that threw error: " + sql); - e.printStackTrace(); - } - } - throw new IllegalStateException("No results for the select query. " + sql); - } - - public static void updateWhere(String columnName, String columnValue, String where) { - if (isTableCreated()) { - try { - conn = DatabaseUtil.getConnection(); - ps = conn.createStatement(); - sql = "UPDATE " + TableNames.EDGE_TABLE + - " SET " + columnName + " = " + columnValue + - " WHERE " + where; - // System.out.println(">>> we got " + sql); - ps.executeUpdate(sql); - return; - // resultSet.next(); - // System.out.println(resultSet.getInt("id")); - } catch (SQLException e) { - System.out.println("Line that threw error: " + sql); - e.printStackTrace(); - } - } - throw new IllegalStateException("Table does not exist. Hence cannot fetch any rows from it."); - - } -} diff --git a/src/main/java/com/application/db/DAOImplementation/ElementDAOImpl.java b/src/main/java/com/application/db/DAOImplementation/ElementDAOImpl.java deleted file mode 100644 index 5a67a2d..0000000 --- a/src/main/java/com/application/db/DAOImplementation/ElementDAOImpl.java +++ /dev/null @@ -1,160 +0,0 @@ -package com.application.db.DAOImplementation; - -import com.application.db.DatabaseUtil; -import com.application.db.TableNames; -import com.application.fxgraph.ElementHelpers.Element; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; - -import static com.application.db.TableNames.ELEMENT_TABLE; - -public class ElementDAOImpl { - // public static boolean isTableCreated = false; - - public static boolean isTableCreated() { - // System.out.println("starting isTableCreated"); - // if (!isTableCreated) {// No need to call DatabaseUtil method every time. Save time this way. - // System.out.println("ElementDAOImpl:isTableCreated: " + isTableCreated); - // isTableCreated = DatabaseUtil.isTableCreated(ELEMENT_TABLE); - // System.out.println("ElementDAOImpl:isTableCreated: " + isTableCreated); - // } - // System.out.println("ending isTableCreated"); - // return isTableCreated; - return DatabaseUtil.isTableCreated(ELEMENT_TABLE); - } - - public static void createTable() { - // System.out.println("starting createTable"); - // System.out.println("ElementDAOImpl:createTable: " + isTableCreated()); - if (!isTableCreated()) { - try (Connection c = DatabaseUtil.getConnection(); Statement ps = c.createStatement()) { - String sql = "CREATE TABLE " + ELEMENT_TABLE + " (" + - "id INTEGER NOT NULL, " + - "parent_id INTEGER, " + // todo define foreign key - "id_enter_call_trace INTEGER, " + // not a foreign key. - "id_exit_call_trace INTEGER, " + // not a foreign key. - "bound_box_x_top_left FLOAT, " + - "bound_box_y_top_left FLOAT, " + - "bound_box_x_top_right FLOAT, " + - "bound_box_y_top_right FLOAT, " + - "bound_box_x_bottom_right FLOAT, " + - "bound_box_y_bottom_right FLOAT, " + - "bound_box_x_bottom_left FLOAT, " + - "bound_box_y_bottom_left FLOAT, " + - "bound_box_x_coordinate FLOAT, " + - "bound_box_y_coordinate FLOAT, " + - "index_in_parent INTEGER, " + - "leaf_count INTEGER, " + - "level_count INTEGER, " + - "collapsed INTEGER, " + - "delta FLOAT, " + - "delta_x FLOAT" + - ")"; - ps.execute(sql); - System.out.println("** Creating table " + TableNames.ELEMENT_TABLE); - } catch (SQLException e) { - e.printStackTrace(); - } - } - // System.out.println("ending createTable"); - } - - public static void insert(Element element) { - if (!isTableCreated()) - createTable(); - String sql = null; - try (Connection c = DatabaseUtil.getConnection(); Statement ps = c.createStatement()) { - sql = "INSERT INTO " + TableNames.ELEMENT_TABLE + " VALUES (" + - element.getElementId() + ", " + - (element.getParent() == null? -1 : element.getParent().getElementId()) + ", " + - element.getFkEnterCallTrace() + ", " + - element.getFkExitCallTrace() + ", " + - element.getBoundBox().xTopLeft + ", " + - element.getBoundBox().yTopLeft + ", " + - element.getBoundBox().xTopRight + ", " + - element.getBoundBox().yTopRight + ", " + - element.getBoundBox().xBottomRight + ", " + - element.getBoundBox().yBottomRight + ", " + - element.getBoundBox().xBottomLeft + ", " + - element.getBoundBox().yBottomLeft + ", " + - element.getBoundBox().xCoordinate + ", " + - element.getBoundBox().yCoordinate + ", " + - element.getIndexInParent() + ", " + - element.getLeafCount() + ", " + - element.getLevelCount() + ", " + - element.getIsCollapsed() + ", " + - element.getDelta() + ", " + - element.getDeltaX() + - ")"; - - ps.execute(sql); - // System.out.println(TableNames.ELEMENT_TABLE + ": Inserted: " + sql); - } catch (SQLException e) { - System.out.println(" Exception caused by: " + sql); - e.printStackTrace(); - } - // System.out.println("ending insert"); - } - - public static void dropTable() { - // System.out.println("starting dropTable"); - if (isTableCreated()) { - try (Connection c = DatabaseUtil.getConnection(); Statement ps = c.createStatement()) { - String sql= "Drop table " + TableNames.ELEMENT_TABLE; - System.out.println(">> Dropping table " + TableNames.ELEMENT_TABLE); - - ps.execute(sql); - } catch (SQLException e) { - e.printStackTrace(); - } - } - // System.out.println("ending dropTable"); - } - - static Connection conn; - static Statement ps; - static String sql; - public static ResultSet selectWhere(String where) { - if (isTableCreated()) { - try { - conn = DatabaseUtil.getConnection(); - ps = conn.createStatement(); - sql = "SELECT * FROM " + ELEMENT_TABLE + " WHERE " + where; - // System.out.println(">>> we got " + sql); - ResultSet resultSet = ps.executeQuery(sql); - // resultSet.next(); - // System.out.println(resultSet.getInt("id")); - return resultSet; - } catch (SQLException e) { - System.out.println("Line that threw error: " + sql); - e.printStackTrace(); - } - } - throw new IllegalStateException("Table does not exist. Hence cannot fetch any rows from it."); - } - - public static void updateWhere(String columnName, String columnValue, String where) { - if (isTableCreated()) { - try { - conn = DatabaseUtil.getConnection(); - ps = conn.createStatement(); - sql = "UPDATE " + ELEMENT_TABLE + - " SET " + columnName + " = " + columnValue + - " WHERE " + where; - // System.out.println(">>> we got " + sql); - ps.executeUpdate(sql); - return; - // resultSet.next(); - // System.out.println(resultSet.getInt("id")); - } catch (SQLException e) { - System.out.println("Line that threw error: " + sql); - e.printStackTrace(); - } - } - throw new IllegalStateException("Table does not exist. Hence cannot fetch any rows from it."); - - } -} diff --git a/src/main/java/com/application/db/DAOImplementation/HighlightDAOImpl.java b/src/main/java/com/application/db/DAOImplementation/HighlightDAOImpl.java deleted file mode 100644 index 2262697..0000000 --- a/src/main/java/com/application/db/DAOImplementation/HighlightDAOImpl.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.application.db.DAOImplementation; - -import com.application.db.DatabaseUtil; -import com.application.db.TableNames; -import javafx.geometry.BoundingBox; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; - -public class HighlightDAOImpl { - - public static boolean isTableCreated() { - return DatabaseUtil.isTableCreated(TableNames.HIGHLIGHT_ELEMENT); - } - - public static void createTable() { - if (!isTableCreated()) { - try (Connection c = DatabaseUtil.getConnection(); Statement ps = c.createStatement()) { - String sql = "CREATE TABLE " + TableNames.HIGHLIGHT_ELEMENT + " (" + - "id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), " + - "element_id INT, " + - "method_id INT, " + - "thread_id INT, " + - "highlight_type VARCHAR(6), " + // valid values may be "SINGLE" or "FuLL". - "start_x FLOAT, " + - "start_y FLOAT, " + - "width FLOAT, " + - "height FLOAT, " + - "color VARCHAR(10), " + - "collapsed INT" + - ")"; - ps.execute(sql); - System.out.println("** Creating table " + TableNames.HIGHLIGHT_ELEMENT); - } catch (SQLException e) { - e.printStackTrace(); - } - } - } - - public static void dropTable() { - if (isTableCreated()) { - try (Connection c = DatabaseUtil.getConnection(); Statement ps = c.createStatement()) { - String sql= "Drop table " + TableNames.HIGHLIGHT_ELEMENT; - System.out.println(">> Dropping table " + TableNames.HIGHLIGHT_ELEMENT); - - ps.execute(sql); - } catch (SQLException e) { - e.printStackTrace(); - } - } - } - - static Connection conn; - static Statement ps; - static String sql; - public static ResultSet selectWhere(String where) { - if (!isTableCreated()) - createTable(); - - try { - conn = DatabaseUtil.getConnection(); - ps = conn.createStatement(); - sql = "SELECT * FROM " + TableNames.HIGHLIGHT_ELEMENT + " WHERE " + where; - ResultSet resultSet = ps.executeQuery(sql); - return resultSet; - } catch (SQLException e) { - System.out.println("Line that threw error: " + sql); - e.printStackTrace(); - } - throw new IllegalStateException("No results for the select query. " + sql); - } - - public static void updateWhere(String columnName, String columnValue, String where) { - if (isTableCreated()) { - try { - conn = DatabaseUtil.getConnection(); - ps = conn.createStatement(); - sql = "UPDATE " + TableNames.HIGHLIGHT_ELEMENT + - " SET " + columnName + " = " + columnValue + - " WHERE " + where; - ps.executeUpdate(sql); - return; - } catch (SQLException e) { - System.out.println("Line that threw error: " + sql); - e.printStackTrace(); - } - } - throw new IllegalStateException("Table does not exist. Hence cannot fetch any rows from it."); - - } -} diff --git a/src/main/java/com/application/db/DAOImplementation/MethodDefnDAOImpl.java b/src/main/java/com/application/db/DAOImplementation/MethodDefnDAOImpl.java deleted file mode 100644 index 8b14c68..0000000 --- a/src/main/java/com/application/db/DAOImplementation/MethodDefnDAOImpl.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.application.db.DAOImplementation; - -import com.application.db.DatabaseUtil; -import com.application.db.TableNames; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.List; - -import static com.application.db.TableNames.METHOD_DEFINITION_TABLE; - -public class MethodDefnDAOImpl { - // TODO: Create abstract classes for all these Impl classes. All common funtionality is implement by the default class. Rest of the methods are abstract. - // public static boolean isTableCreated = false; - - public static boolean isTableCreated() { - // System.out.println("starting isTableCreated"); - // if (!isTableCreated) {// No need to call DatabaseUtil method every time. Save time this way. - // System.out.println("MethodDefnDAOImpl:isTableCreated: " + isTableCreated); - // isTableCreated = DatabaseUtil.isTableCreated(METHOD_DEFINITION_TABLE); - return DatabaseUtil.isTableCreated(METHOD_DEFINITION_TABLE); - // System.out.println("MethodDefnDAOImpl:isTableCreated: " + isTableCreated); - // } - // System.out.println("ending isTableCreated"); - // return isTableCreated; - } - - public static void createTable() { - // System.out.println("starting createTable"); - if (!isTableCreated()) { - try (Connection c = DatabaseUtil.getConnection(); Statement ps = c.createStatement()) { - sql = "CREATE TABLE " + METHOD_DEFINITION_TABLE + " (" + - "id INTEGER NOT NULL PRIMARY KEY , " + - "package_name VARCHAR(200), " + - "method_name VARCHAR(50), " + - "parameter_types VARCHAR(200)" + - ")"; - ps.execute(sql); - System.out.println("** Creating table " + TableNames.METHOD_DEFINITION_TABLE); - } catch (SQLException e) { - System.err.println("MethodDefnDAOImpl::createTable: SQL Exception on create table"); - e.printStackTrace(); - } - } - // System.out.println("ending createTable"); - } - - public static void insert(List vals) { - if (!isTableCreated()) - createTable(); - - int methodID = Integer.parseInt(vals.get(0)); - String packageName = vals.get(1); - String methodName = vals.get(2); - String arguments = vals.get(3); - String sql = null; - try (Connection c = DatabaseUtil.getConnection(); Statement ps = c.createStatement()) { - sql = "INSERT INTO " + METHOD_DEFINITION_TABLE + " VALUES(\n"+ - methodID + ", '" + - packageName + "', '" + - methodName + "', '" + - arguments + "'" + - ")"; - ps.execute(sql); - } catch (SQLException e) { - System.out.println(" Exception caused by: " + sql); - e.printStackTrace(); - } - } - - public static void dropTable() { - // System.out.println("starting dropTable"); - if (isTableCreated()) { - try (Connection c = DatabaseUtil.getConnection(); Statement ps = c.createStatement()) { - String sql= "Drop table " + METHOD_DEFINITION_TABLE; - System.out.println(">> Dropping table " + TableNames.METHOD_DEFINITION_TABLE); - - ps.execute(sql); - ps.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - // System.out.println("ending dropTable"); - } - - static Connection conn; - static Statement ps; - static String sql; - public static ResultSet selectWhere(String where) { - if (isTableCreated()) try { - conn = DatabaseUtil.getConnection(); - ps = conn.createStatement(); - sql = "SELECT * FROM " + METHOD_DEFINITION_TABLE + " WHERE " + where; - ResultSet resultSet = ps.executeQuery(sql); - // resultSet.next(); - // System.out.println(resultSet.getInt("id")); - return resultSet; - } catch (SQLException e) { - System.out.println("Line that threw error: " + sql); - e.printStackTrace(); - } - throw new IllegalStateException("Table does not exist. Hence cannot fetch any rows from it."); - } -} diff --git a/src/main/java/com/application/db/DAOImplementation/TraceDAOImpl.java b/src/main/java/com/application/db/DAOImplementation/TraceDAOImpl.java deleted file mode 100644 index 56ad2bf..0000000 --- a/src/main/java/com/application/db/DAOImplementation/TraceDAOImpl.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.application.db.DAOImplementation; - -import com.application.db.DAOInterfaces.TraceDAOInterface; -import com.application.db.DatabaseUtil; -import com.application.db.TableNames; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; - -/** - * Implementation of the TraceDAOInterface. - */ -public class TraceDAOImpl implements TraceDAOInterface{ - - public boolean isTableCreated = false; - Connection conn = null; - - @Override - public boolean insert(List vals) { - Connection conn = DatabaseUtil.getConnection(); - Statement ps = null; - String sql; - - int processID = Integer.parseInt(vals.get(0)); - int threadID = Integer.parseInt(vals.get(1)); - int methodID = Integer.parseInt(vals.get(2)); - String eventType = vals.get(0); - String parameters = vals.get(0); - - if (!isTableCreated) { - createTable(); - } - - try { - ps = conn.createStatement(); - - sql = "INSERT INTO " + TableNames.CALL_TRACE_TABLE + " VALUES(\n"+ - processID +","+ - threadID +","+ - methodID +",'"+ - eventType +"','"+ - parameters + - "')"; - - ps.executeUpdate(sql); - ps.close(); - ps = null; - conn.close(); - conn = null; - - } catch (SQLException e) { - e.printStackTrace(); - return false; - } - finally{ - if (ps != null){ - try { ps.close();} catch (SQLException e){;} - ps = null; - } - if (conn != null){ - try {conn.close();} catch(SQLException e) {;} - conn = null; - } - } - - return true; - } - - @Override - public boolean createTable() { - Statement ps = null; - Connection cn = null; - cn = DatabaseUtil.getConnection(); - String sql; - ResultSet rs; - - if (isTableCreated) return true; - - try { - ps = cn.createStatement(); - - sql = "CREATE TABLE " + TableNames.CALL_TRACE_TABLE + " (\n" + - " \"processID\" INTEGER not null primary key,\n" + - " \"threadID\" INTEGER,\n" + - " \"methodID\" INTEGER,\n" + - " \"message\" VARCHAR(50),\n" + - " \"parameter\" VARCHAR(20)\n" + - /*" FOREIGN KEY(\"methodID\") REFERENCES METHOD(\"methdID\")"+ */ - ")"; - - ps.executeUpdate(sql); - ps.close(); - ps = null; - cn.close(); - cn = null; - isTableCreated = true; - } catch (SQLException e) { - String sqlError = e.getSQLState(); - if (sqlError.equals("X0Y32")) { - System.out.println("TableNames already exists."); - isTableCreated = true; - return true; - } else { - e.printStackTrace(); - System.out.println("Other error."); - return false; - } - } finally { - if (ps != null) { - try { - ps.close(); - } catch (SQLException e) { - ; - } - ps = null; - } - if (cn != null) { - try { - cn.close(); - } catch (SQLException e) { - ; - } - cn = null; - } - } - return true; - } - - @Override - public ResultSet select(int numOfRows) { - Connection c = DatabaseUtil.getConnection(); - Statement ps = null; - ResultSet rs = null; - ArrayList process = new ArrayList<>(); - String query; - - try{ - ps = c.createStatement(); - ps.setMaxRows(numOfRows); - query = "SELECT * FROM " + TableNames.CALL_TRACE_TABLE; - rs = ps.executeQuery(query); - } catch (SQLException e) { - e.printStackTrace(); - } -// finally{ -// if (ps != null){ -// try { ps.close();} catch (SQLException e){;} -// ps = null; -// } -// if (c != null){ -// try {c.close();} catch(SQLException e) {;} -// c = null; -// } -// } - - return rs; - } -} diff --git a/src/main/java/com/application/db/DAOInterfaces/DefnDAOInterface.java b/src/main/java/com/application/db/DAOInterfaces/DefnDAOInterface.java deleted file mode 100644 index b31a242..0000000 --- a/src/main/java/com/application/db/DAOInterfaces/DefnDAOInterface.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.application.db.DAOInterfaces; - -import com.application.logs.fileHandler.MethodDefinitionLogFile; - -import java.sql.ResultSet; - -/** - * Data Access Object Interface for each log statement in the Call Trace Log file - */ -public interface DefnDAOInterface { - String DEFINITION_TABLE_NAME = MethodDefinitionLogFile.getFileName(); - - boolean insert(); - boolean createTable(); - ResultSet select(int numOfRows); - -} diff --git a/src/main/java/com/application/db/DAOInterfaces/ElementDAOInterface.java b/src/main/java/com/application/db/DAOInterfaces/ElementDAOInterface.java deleted file mode 100644 index edbf1ba..0000000 --- a/src/main/java/com/application/db/DAOInterfaces/ElementDAOInterface.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.application.db.DAOInterfaces; - -import com.application.fxgraph.ElementHelpers.Element; - -public interface ElementDAOInterface extends TableDAOInterface{ - void insert(Element element); -} diff --git a/src/main/java/com/application/db/DAOInterfaces/ElementToChildDAOInterface.java b/src/main/java/com/application/db/DAOInterfaces/ElementToChildDAOInterface.java deleted file mode 100644 index 0133235..0000000 --- a/src/main/java/com/application/db/DAOInterfaces/ElementToChildDAOInterface.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.application.db.DAOInterfaces; - -public interface ElementToChildDAOInterface extends TableDAOInterface{ - void insert(int elementId, int childId); -} - diff --git a/src/main/java/com/application/db/DAOInterfaces/TableDAOInterface.java b/src/main/java/com/application/db/DAOInterfaces/TableDAOInterface.java deleted file mode 100644 index 2c13d3d..0000000 --- a/src/main/java/com/application/db/DAOInterfaces/TableDAOInterface.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.application.db.DAOInterfaces; - -public interface TableDAOInterface { - void createTable(); - boolean isTableCreated(); -} diff --git a/src/main/java/com/application/db/DAOInterfaces/TraceDAOInterface.java b/src/main/java/com/application/db/DAOInterfaces/TraceDAOInterface.java deleted file mode 100644 index 9d06629..0000000 --- a/src/main/java/com/application/db/DAOInterfaces/TraceDAOInterface.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.application.db.DAOInterfaces; - -import java.sql.ResultSet; -import java.util.List; - -/** - * Data Access Object Interface for each log statement in the Call Trace Log file - */ -public interface TraceDAOInterface { - public static final String TRACE_TABLE_NAME = "CALL_TRACE"; - - public boolean insert(List values); - public boolean createTable(); - public ResultSet select(int numOfRows); - -} diff --git a/src/main/java/com/application/db/model/DefnStatement.java b/src/main/java/com/application/db/model/DefnStatement.java deleted file mode 100644 index ebbaaa0..0000000 --- a/src/main/java/com/application/db/model/DefnStatement.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.application.db.model; - -/** - * Model for a log statement in the Method Definition File. - */ -public class DefnStatement { - int methodId; - String packageName; - String methodName; - String arguments; - - public DefnStatement(int methodId, String packageName, String methodName, String arguments) { - this.methodId = methodId; - this.packageName = packageName; - this.methodName = methodName; - this.arguments = arguments; - } - - public int getMethodId() { - return methodId; - } - - public void setMethodId(int methodId) { - this.methodId = methodId; - } - - public String getPackageName() { - return packageName; - } - - public void setPackageName(String packageName) { - this.packageName = packageName; - } - - public String getMethodName() { - return methodName; - } - - public void setMethodName(String methodName) { - this.methodName = methodName; - } - - public String getArguments() { - return arguments; - } - - public void setArguments(String arguments) { - this.arguments = arguments; - } -} diff --git a/src/main/java/com/application/db/model/TraceStatement.java b/src/main/java/com/application/db/model/TraceStatement.java deleted file mode 100644 index 71fbf43..0000000 --- a/src/main/java/com/application/db/model/TraceStatement.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.application.db.model; - -/** - * Model for a log statement in the Call Trace File. - */ -public class TraceStatement { - int processId; - int threadId; - int methodId; - String eventType; - String parameters; - - public TraceStatement(int processId, int threadId, int methodId, String eventType, String parameters) { - this.processId = processId; - this.threadId = threadId; - this.methodId = methodId; - this.eventType = eventType; - this.parameters = parameters; - } - - public int getProcessId() { - return processId; - } - - public void setProcessId(int processId) { - this.processId = processId; - } - - public int getThreadId() { - return threadId; - } - - public void setThreadId(int threadId) { - this.threadId = threadId; - } - - public int getMethodId() { - return methodId; - } - - public void setMethodId(int methodId) { - this.methodId = methodId; - } - - public String getEventType() { - return eventType; - } - - public void setEventType(String eventType) { - this.eventType = eventType; - } - - public String getParameters() { - return parameters; - } - - public void setParameters(String parameters) { - this.parameters = parameters; - } -} diff --git a/src/main/java/com/application/fxgraph/ElementHelpers/ConvertDBtoElementTree.java b/src/main/java/com/application/fxgraph/ElementHelpers/ConvertDBtoElementTree.java deleted file mode 100644 index 0077634..0000000 --- a/src/main/java/com/application/fxgraph/ElementHelpers/ConvertDBtoElementTree.java +++ /dev/null @@ -1,804 +0,0 @@ -package com.application.fxgraph.ElementHelpers; - -import com.application.db.DAOImplementation.*; -import com.application.db.DatabaseUtil; -import com.application.db.TableNames; -import com.application.fxgraph.cells.CircleCell; -import com.application.fxgraph.graph.*; -import javafx.application.Platform; -import javafx.geometry.BoundingBox; -import javafx.scene.shape.Line; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.*; - -public class ConvertDBtoElementTree { - public static Element greatGrandParent; - private Map threadMapToRoot; - public ArrayList rootsList; - Element grandParent, parent, cur; - Map currentMap; - Graph graph; - Model model; - private String currentThreadId = "0"; - - private boolean showAllThreads = true; - - public int multiplierForVisibleViewPort = 3; - public int multiplierForPreLoadedViewPort = 2; - - public ConvertDBtoElementTree() { - Element.clearAutoIncrementId(); - greatGrandParent = new Element(null, -2); - rootsList = new ArrayList<>(); - currentMap = new HashMap<>(); - threadMapToRoot = new LinkedHashMap<>(); - } - - /** - * This method converts the string to an element tree. - * - */ - public void StringToElementList(List line, int fkCallTrace) { - String msg = line.get(3); // ToDo replace hardcoded indices with universal indices. - Integer threadId = Integer.valueOf(line.get(2)); - - switch (msg.toUpperCase()) { - case "WAIT-ENTER": - case "NOTIFY-ENTER": - case "NOTIFYALL-ENTER": - case "ENTER": // Todo Performance: Use int codes instead of String like "ENTER": - if (!threadMapToRoot.containsKey(threadId)) { - // new thread - parent = null; - } else if (currentMap.containsKey(threadId)) { - parent = currentMap.get(threadId); - // parent = cur; - } - cur = new Element(parent, fkCallTrace); - currentMap.put(threadId, cur); - break; - - case "WAIT-EXIT": - case "NOTIFY-EXIT": - case "NOTIFYALL-EXIT": - case "EXIT": - cur = currentMap.get(threadId); - cur.setFkExitCallTrace(fkCallTrace); - cur = cur.getParent(); - currentMap.put(threadId, cur); - // cur = cur.getParent(); - break; - - default: - IllegalStateException up = new IllegalStateException("EventType should be either ENTER OR EXIT. This line caused exception: " + line); - throw up; // Yuck! Not having any of that :( - } - - if (parent == null && - (!msg.equalsIgnoreCase("EXIT") && - !msg.equalsIgnoreCase("WAIT-EXIT") && - !msg.equalsIgnoreCase("NOTIFY-EXIT") && - !msg.equalsIgnoreCase("NOTIFYALL-EXIT"))) { - if (!threadMapToRoot.containsKey(threadId)) { - grandParent = new Element(greatGrandParent, -1); - grandParent.setChildren(new ArrayList<>(Arrays.asList(cur))); - cur.setParent(grandParent); - threadMapToRoot.put(threadId, grandParent); - /*defaultInitialize(grandParent); - ElementDAOImpl.insert(grandParent);*/ - } else { - Element grandparent = threadMapToRoot.get(threadId); // Get grandParent root for the current threadId - grandparent.setChildren(new ArrayList<>(Collections.singletonList(cur))); // set the current element as the child of the grandParent element. - cur.setParent(grandparent); - } - } - - /*if ( msg.equalsIgnoreCase("ENTER")) { - defaultInitialize(cur); - ElementDAOImpl.insert(cur); - }*/ - } - - private void defaultInitialize(Element element) { - cur.setLeafCount(-1); - cur.setLevelCount(-1); - cur.getBoundBox().xTopLeft = -1; - cur.getBoundBox().yTopLeft = -1; - cur.getBoundBox().xTopRight = -1; - cur.getBoundBox().yTopRight = -1; - cur.getBoundBox().xBottomRight = -1; - cur.getBoundBox().yBottomRight = -1; - cur.getBoundBox().xBottomLeft = -1; - cur.getBoundBox().yBottomLeft = -1; - } - - public Map getThreadMapToRoot() { - return threadMapToRoot; - } - - - /** - * Calculates the Element properties on all direct and indirect children of current element. - * Ensure that the sub tree is fully constructed before invoking this method. - */ - public void calculateElementProperties() { - greatGrandParent.calculateLeafCount(); - greatGrandParent.calculateLevelCount(0); - - greatGrandParent.getChildren().stream().forEach(element -> { - element.setBoundBoxOnAll(element); - }); - // greatGrandParent.setBoundBoxOnAll(greatGrandParent); - - } - - public void recursivelyInsertElementsIntoDB(Element root) { - if (root == null) - return; - ElementDAOImpl.insert(root); - ElementToChildDAOImpl.insert( - root.getParent() == null? -1 : root.getParent().getElementId(), - root.getElementId()); - // // Create and insert Edges. - // Edge edge = new Edge(root.getParent(), root); - // edge.setStartX(); - - if (root.getChildren() != null) - root.getChildren().stream().forEachOrdered(this::recursivelyInsertElementsIntoDB); - } - - public void recursivelyInsertEdgeElementsIntoDB(Element root) { - if (root == null) - return; - - if (root.getChildren() != null) - root.getChildren().stream().forEachOrdered(targetElement -> { - EdgeElement edgeElement = new EdgeElement(root, targetElement); - edgeElement.calculateEndPoints(); - EdgeDAOImpl.insert(edgeElement); - - recursivelyInsertEdgeElementsIntoDB(targetElement); - }); - } - - - /** - * Loads circle on UI if they are not present when they should be. - * - */ - public void loadUIComponentsInsideVisibleViewPort(Graph graph) { - // System.out.println("ConvertDBtoElementTree:loadUIComponentsInsideVisibleViewPort: Method started"); - this.graph = graph; - this.model = graph.getModel(); - - - // BoundingBox viewPortDims = graph.getViewPortDims(); - // if (!isUIDrawingRequired(viewPortDims)) { - // // System.out.println("ConvertDBtoElementTree:loadUIComponentsInsideVisibleViewPort: UI redrawing not required."); - // return; - // } - - - // System.out.println("ConvertDBtoElementTree::loadUIComponentsInsideVisibleViewPort: before drawing, existing contents of cellLayer: "); - // System.out.println("mapCircleCellsOnUI: size: " + graph.getModel().getCircleCellsOnUI().size()); - // graph.getModel().getCircleCellsOnUI().keySet().stream().sorted().forEach(id -> { - // System.out.print(id + ", "); - // }); - - // System.out.println("mapEdgesOnUI: "); - // graph.getModel().getEdgesOnUI().keySet().stream().sorted().forEach(id -> { - // System.out.print(id + ", "); - // }); - - // System.out.println("highlightsOnUI: elementId : "); - // graph.getModel().getHighlightsOnUI().values().stream().sorted().forEach(rect -> { - // System.out.print(rect.getElementId()+ ", "); - // }); - - // Add circle cells - addCircleCells(); - - // Add edges - addEdges(); - - // Add highlights - addHighlights(); - - graph.updateCellLayer(); - - - // System.out.println("ConvertDBtoElementTree::loadUIComponentsInsideVisibleViewPort: after drawing, contents of cellLayer: "); - // System.out.println("mapCircleCellsOnUI: size: " + graph.getModel().getCircleCellsOnUI().size()); - // graph.getModel().getCircleCellsOnUI().keySet().stream().sorted().forEach(id -> { - // System.out.print(id + ", "); - // }); - } - - public void forceUiRendering(Graph graph) { - // System.out.println("ConvertDBtoElementTree:forceUiRendering: method started"); - - // Add circle cells - addCircleCells(); - // Add edges - addEdges(); - // Add highlights - addHighlights(); - graph.updateCellLayer(); - - // System.out.println("ConvertDBtoElementTree:forceUiRendering: method ended"); - } - - public void ClearAndUpdateCellLayer() { - // remove all circles cells from UI - graph.getCellLayer().getChildren().removeAll(model.getCircleCellsOnUI().values()); - model.getCircleCellsOnUI().clear(); - - // remove all Edges from UI - graph.getCellLayer().getChildren().removeAll(model.getEdgesOnUI().values()); - model.getEdgesOnUI().clear(); - - // remove all Highlights from UI - graph.getCellLayer().getChildren().removeAll(model.getHighlightsOnUI().values()); - model.getHighlightsOnUI().clear(); - - forceUiRendering(graph); - } - - private void addHighlights() { - // System.out.println("ConvertDBtoElementTree::addHighlights: method started"); - - Map highlightsOnUI = model.getHighlightsOnUI(); - - BoundingBox viewPortDims = graph.getViewPortDims(); - - double viewPortMinX = viewPortDims.getMinX(); - double viewPortMaxX = viewPortDims.getMaxX(); - double viewPortMinY = viewPortDims.getMinY(); - double viewPortMaxY = viewPortDims.getMaxY(); - double widthOffset = viewPortDims.getWidth() * multiplierForVisibleViewPort; - double heightOffset = viewPortDims.getHeight() * multiplierForVisibleViewPort ; - - // Query to fetches highlight boxes that are contained within the bounds of outermost preload box. - - String sql = (viewPortMinX - widthOffset) + " <= (start_x + width) " + " " + - "AND " + (viewPortMaxX + widthOffset) + " >= start_x " + - "AND " +(viewPortMinY - heightOffset) + " <= (start_y + height) " + " " + - "AND " + (viewPortMaxY + heightOffset) + " >= start_Y " + - "AND thread_id = " + currentThreadId + " " + - "AND COLLAPSED = 0"; - - ResultSet rs = HighlightDAOImpl.selectWhere(sql); - - try { - while (rs.next()) { - int id = rs.getInt("ID"); - int elementId = rs.getInt("ELEMENT_ID"); - float startX = rs.getFloat("START_X"); - float startY = rs.getFloat("START_Y"); - float width = rs.getFloat("WIDTH"); - float height = rs.getFloat("HEIGHT"); - String color = rs.getString("COLOR"); - - // If the rectangle highlight is not on UI then create a new rectangle and show on UI. - if (!highlightsOnUI.containsKey(id)) { - // System.out.println("Drawing rectangle: " + id + " elementId: " + elementId); - // Rectangle rectangle = new Rectangle(startX, startY, width, height); - // rectangle.setFill(Color.web(color)); - // rectangle.setArcHeight(20); - // rectangle.setArcWidth(20); - - RectangleCell rect = new RectangleCell(id, elementId, startX, startY, width, height); - rect.setColor(color); - rect.setArcHeight(20); - rect.setArcWidth(20); - - // model.addHighlight(id, rectangle); - model.addHighlight(id, rect); - } - } - } catch (SQLException e) { - e.printStackTrace(); - } - - // System.out.println("ConvertDBtoElementTree::addHighlights: method ended"); - - } - - private void addCircleCells() { - Map mapCircleCellsOnUI = model.getCircleCellsOnUI(); - - // Calculate the expanded region around viewport that needs to be loaded. - BoundingBox viewPortDims = graph.getViewPortDims(); - - double viewPortMinX = viewPortDims.getMinX(); - double viewPortMaxX = viewPortDims.getMaxX(); - double viewPortMinY = viewPortDims.getMinY(); - double viewPortMaxY = viewPortDims.getMaxY(); - double widthOffset = viewPortDims.getWidth() * multiplierForVisibleViewPort; - double heightOffset = viewPortDims.getHeight() * multiplierForVisibleViewPort ; - - - // Get element properties for those elements that are inside the expanded region calculated above. - String sql = "SELECT E.ID AS EID, parent_id, collapsed, bound_box_x_coordinate, bound_box_y_coordinate, message, id_enter_call_trace, method_id " + - "FROM " + TableNames.CALL_TRACE_TABLE + " AS CT JOIN " + TableNames.ELEMENT_TABLE + " AS E ON CT.ID = E.ID_ENTER_CALL_TRACE " + - "WHERE CT.THREAD_ID = " + currentThreadId + - " AND E.bound_box_x_coordinate > " + (viewPortMinX - widthOffset) + - " AND E.bound_box_x_coordinate < " + (viewPortMaxX + widthOffset) + - " AND E.bound_box_y_coordinate > " + (viewPortMinY - heightOffset) + - " AND E.bound_box_y_coordinate < " + (viewPortMaxY + heightOffset) + - " AND E.LEVEL_COUNT > 1" + - " AND (E.COLLAPSED = 0" + - " OR E.COLLAPSED = 2)"; - - // System.out.println("ConvertDBtoElementTree::addCircleCells: sql: " + sql); - CircleCell curCircleCell; - CircleCell parentCircleCell; - - - try (ResultSet rs = DatabaseUtil.select(sql)) { - while (rs.next()) { - - String id = String.valueOf(rs.getInt("EID")); - String parentId = String.valueOf(rs.getInt("parent_id")); - int collapsed = rs.getInt("collapsed"); - float xCoordinate = rs.getFloat("bound_box_x_coordinate"); - float yCoordinate = rs.getFloat("bound_box_y_coordinate"); - int idEnterCallTrace = rs.getInt("id_enter_call_trace"); - int methodId = rs.getInt("method_id"); - String methodName = ""; - - if (methodId == 0) { - methodName = rs.getString("message"); - } else { - try (ResultSet rsMethod = MethodDefnDAOImpl.selectWhere("id = " + methodId)) { - while (rsMethod.next()) { - methodName = rsMethod.getString("method_name"); - } - }catch (Exception e) { - e.printStackTrace(); - } - } - String eventType = ""; - eventType = rs.getString("message"); - - /* - * collapsed - actions - * 0 - Show cell on UI - * 1 - parent of this cell was minimized. Don't show on UI - * 2 - this cell was minimized. Show on UI. - * 3 - parent of this cell was minimized. this cell was minimized. Don't expand this cell's children. Don't show on UI. - */ - - // Add circle cell to model and UI only if they are not already present on UI and if collapsed value is 0 or 2 - if (!mapCircleCellsOnUI.containsKey(id) && (collapsed == 0 || collapsed == 2)) { - // System.out.println("ConvertDBtoElementTree::addCircleCells: adding new cells to UI: cell id: " + id); - curCircleCell = new CircleCell(id, xCoordinate, yCoordinate); - curCircleCell.setMethodName(methodName); - model.addCell(curCircleCell); - String label = ""; - switch (eventType.toUpperCase()) { - case "WAIT-ENTER": - label = "WAIT"; - break; - case "NOTIFY-ENTER": - label = "NOTIFY"; - break; - case "NOTIFYALL-ENTER": - label = "NOTIFY\nALL"; - break; - } - - curCircleCell.setLabel(label); - - // Add parent circle cell if not already added earlier. - parentCircleCell = mapCircleCellsOnUI.get(parentId); - if (!mapCircleCellsOnUI.containsKey(parentId)) { - try (ResultSet rsTemp = ElementDAOImpl.selectWhere("id = " + parentId)) { - if (rsTemp.next() && rsTemp.getInt("LEVEL_COUNT") > 1) { - float xCoordinateTemp = rsTemp.getFloat("bound_box_x_coordinate"); - float yCoordinateTemp = rsTemp.getFloat("bound_box_y_coordinate"); - parentCircleCell = new CircleCell(parentId, xCoordinateTemp, yCoordinateTemp); - // System.out.println("ConvertDBtoElementTree::addCircleCells: adding new parent cells to UI: cell id: " + parentId); - model.addCell(parentCircleCell); - } - } - } - } - // else { - // curCircleCell = mapCircleCellsOnUI.get(id); - // parentCircleCell = mapCircleCellsOnUI.get(parentId); - // } - // if (curCircleCell != null && !model.getEdgesOnUI().containsKey(curCircleCell.getCellId()) && parentCircleCell != null) { - // Edge curEdge = new Edge(parentCircleCell, curCircleCell); - // model.addEdge(curEdge); - // } - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - private void addEdges() { - BoundingBox viewPortDims = graph.getViewPortDims(); - double viewPortMinX = viewPortDims.getMinX(); - double viewPortMaxX = viewPortDims.getMaxX(); - double viewPortMinY = viewPortDims.getMinY(); - double viewPortMaxY = viewPortDims.getMaxY(); - double widthOffset = viewPortDims.getWidth() * multiplierForVisibleViewPort; - double heightOffset = viewPortDims.getHeight() * multiplierForVisibleViewPort ; - - String sql = "SELECT * FROM EDGE_ELEMENT " + - "INNER JOIN ELEMENT ON FK_SOURCE_ELEMENT_ID = ELEMENT.ID " + - "INNER JOIN CALL_TRACE ON ELEMENT.ID_ENTER_CALL_TRACE = CALL_TRACE.ID " + - "WHERE CALL_TRACE.THREAD_ID = " + currentThreadId + " "; - - String commonWhereClausForEdges = "AND EDGE_ELEMENT.collapsed = " + CollapseType.EDGE_VISIBLE + " AND " + "end_x >= " + (viewPortMinX - widthOffset) + " AND start_x <= " + (viewPortMaxX + widthOffset); - String whereClauseForUpwardEdges = " AND end_Y >= " + (viewPortMinY - heightOffset )+ " AND start_y <= " + (viewPortMaxY + heightOffset); - String whereClauseForDownwardEdges = " AND start_y >= " + (viewPortMinY - heightOffset)+ " AND end_Y <= " + (viewPortMaxY + heightOffset); - - // System.out.println("ConvertDBtoElementTree::loadUIComponentsInsideVisibleViewPort: sql: " + sql + commonWhereClausForEdges + whereClauseForUpwardEdges); - try (ResultSet rsUpEdges = DatabaseUtil.select(sql + commonWhereClausForEdges + whereClauseForUpwardEdges)) { - getEdgesFromResultSet(rsUpEdges); - } catch (SQLException e) { - e.printStackTrace(); - } - - // System.out.println("ConvertDBtoElementTree::loadUIComponentsInsideVisibleViewPort: sql: " + sql + commonWhereClausForEdges + whereClauseForDownwardEdges); - try (ResultSet rsDownEdges = DatabaseUtil.select(sql + commonWhereClausForEdges + whereClauseForDownwardEdges)) { - getEdgesFromResultSet(rsDownEdges); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - - private void getEdgesFromResultSet(ResultSet rs) { - Edge curEdge; - try { - while (rs.next()) { - String targetEdgeId = String.valueOf(rs.getInt("fk_target_element_id")); - double startX = rs.getFloat("start_x"); - double endX = rs.getFloat("end_x"); - double startY = rs.getFloat("start_y"); - double endY = rs.getFloat("end_y"); - // System.out.println("ConvertDBtoElementTree::getEdgesFromResultSet: adding edge with target id: " + targetEdgeId); - curEdge = new Edge(targetEdgeId, startX, endX, startY, endY); - model.addEdge(curEdge); - - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - private void removeCircleCells(BoundingBox preloadBox) { - CellLayer cellLayer = (CellLayer) graph.getCellLayer(); - - Map mapCircleCellsOnUI = model.getCircleCellsOnUI(); - List removeCircleCells = new ArrayList<>(); - List listCircleCellsOnUI = model.getListCircleCellsOnUI(); - - - - Iterator i = mapCircleCellsOnUI.entrySet().iterator(); - while (i.hasNext()) { - Map.Entry entry = (Map.Entry) i.next(); - CircleCell cell = entry.getValue(); - if (!preloadBox.contains(cell.getLayoutX(), cell.getLayoutY())) { - removeCircleCells.add(cell.getCellId()); - } - } - - removeCircleCells.forEach(cellId -> { - CircleCell circleCell = mapCircleCellsOnUI.get(cellId); - Platform.runLater(() -> cellLayer.getChildren().remove(circleCell)); - mapCircleCellsOnUI.remove(cellId); - listCircleCellsOnUI.remove(circleCell); - }); - } - - private void removeEdges(BoundingBox preloadBox) { - CellLayer cellLayer = (CellLayer) graph.getCellLayer(); - - Map mapEdgesOnUI = model.getEdgesOnUI(); - - List removeEdges = new ArrayList<>(); - List listEdgesOnUI = model.getListEdgesOnUI(); - - Iterator j = mapEdgesOnUI.entrySet().iterator(); - - while (j.hasNext()) { - Map.Entry entry = (Map.Entry) j.next(); - Edge edge = entry.getValue(); - Line line = (Line) edge.getChildren().get(0); - BoundingBox lineBB = new BoundingBox( - line.getStartX(), - Math.min(line.getStartY(), line.getEndY()), - Math.abs(line.getEndX() - line.getStartX()), - Math.abs(line.getEndY() - line.getStartY())); - // if (!preloadBox.contains(line.getEndX(), line.getEndY())) { - // removeEdges.add(edge.getEdgeId()); - // } - if (!preloadBox.intersects(lineBB)) { - removeEdges.add(edge.getEdgeId()); - } - } - - removeEdges.forEach(edgeId -> { - Edge edge = mapEdgesOnUI.get(edgeId); - Platform.runLater(() -> cellLayer.getChildren().remove(edge)); - mapEdgesOnUI.remove(edgeId); - listEdgesOnUI.remove(edge); - }); - - // clearUI(); - } - - private void removeHighlights(BoundingBox preloadBox) { - // System.out.println("ConvertDBtoElementTree::removeHighlights: method started"); - CellLayer cellLayer = (CellLayer) graph.getCellLayer(); - - // This is the global HashMap that stores rectangle highlights currently on the UI. - Map highlightsOnUI = model.getHighlightsOnUI(); - - // Temporary list to aid in removal of HashMap elements. - List removeHighlights = new ArrayList<>(); - - Iterator j = highlightsOnUI.entrySet().iterator(); - - while (j.hasNext()) { - Map.Entry entry = (Map.Entry) j.next(); - RectangleCell rectangle = entry.getValue(); - int rectId = entry.getKey(); - - // if (!preloadBox.intersects(rectangle.getBoundsInLocal())) { - if (!preloadBox.intersects(rectangle.getBoundsInParent())) { - // ------------------ FOR DEBUGGING ------------------ - // System.out.println("ConvertDBtoElementTree::removeHighlights: adding to removeHighlights because of 1: " + rectId + " elementid: " + rectangle.getElementId()); - // System.out.println(" minY: " + rectangle.getBoundsInLocal().getMinY() + " " + rectangle.getBoundsInLocal().getMinY() + " " + rectangle.getLayoutY()); - // System.out.println(" maxY: " + rectangle.getBoundsInLocal().getMaxY() + " " + rectangle.getBoundsInLocal().getMaxY()); - // System.out.println(" height: " + rectangle.getBoundsInLocal().getHeight() + " " + rectangle.getBoundsInLocal().getHeight()); - // System.out.println("---------------------------------------------------"); - // System.out.println(" minY: " + rectangle.getRectangle().getBoundsInLocal().getMinY() + " " + rectangle.getRectangle().getBoundsInLocal().getMinY() + " " + rectangle.getRectangle().getLayoutY()); - // System.out.println(" maxY: " + rectangle.getRectangle().getBoundsInLocal().getMaxY() + " " + rectangle.getRectangle().getBoundsInLocal().getMaxY()); - // System.out.println(" height: " + rectangle.getRectangle().getBoundsInLocal().getHeight() + " " + rectangle.getRectangle().getBoundsInLocal().getHeight()); - // System.out.println("---------------------------------------------------"); - // System.out.println("preloadbox bounds: " + preloadBox); - // System.out.println("rectangleCell: boundsinlocal: " + rectangle.getBoundsInLocal()); - // System.out.println("rectangleCell: boundsInParent: " + rectangle.getBoundsInParent()); - // System.out.println("rectangleCell: layoutBounds: " + rectangle.getLayoutBounds()); - // System.out.println("rectangleCell.getRectangle: boundsinlocal: " + rectangle.getRectangle().getBoundsInLocal()); - // System.out.println("rectangleCell.getRectangle: boundsinparent: " + rectangle.getRectangle().getBoundsInParent()); - // System.out.println("rectangleCell.getRectangle: layoutBounds: " + rectangle.getRectangle().getLayoutBounds()); - // System.out.println("---------------------------------------------------"); - - // Removes those highlights that are not visible. - removeHighlights.add(rectId); - - } else { - // Removes those highlights that are not in HIGHLIGHT_ELEMENT Table. - String deleteQuery = "SELECT COUNT(*) AS COUNT FROM HIGHLIGHT_ELEMENT WHERE ID = " + rectId; - ResultSet rs = DatabaseUtil.select(deleteQuery); - try { - while (rs.next()) { - if (rs.getInt("COUNT") == 0) { - if (!removeHighlights.contains(rectId)) { - removeHighlights.add(rectId); - // System.out.println("ConvertDBtoElementTree::removeHighlights: adding to removeHighlights because of 2: " + rectId + " elementId: " + rs.getInt("element_id")); - } - } - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - } - - - // Removing elements from HashMap is a two step process, this is to avoid concurrent modification exception - // Remove rectangle highlights from UI and HashMap. - removeHighlights.forEach(rectId -> { - RectangleCell rectangle = highlightsOnUI.get(rectId); - int elementId = rectangle.getElementId(); - // System.out.println("ConvertDBtoElementTree::removeHighlights: removing rectangle: " + rectId + " elementId: " + elementId); - Platform.runLater(() -> cellLayer.getChildren().remove(rectangle)); - highlightsOnUI.remove(rectId); - }); - // System.out.println("ConvertDBtoElementTree::removeHighlights: method ended"); - } - - public void removeUIComponentsFromInvisibleViewPort(Graph graph) { - // System.out.println("ConvertDBtoElementTree::removeUIComponentsFromInvisibleViewPort: method started"); - this.graph = graph; - this.model = graph.getModel(); - - BoundingBox viewPortDims = graph.getViewPortDims(); - - // if (!isUIDrawingRequired(viewPortDims)) { - // return; - // } - - double minX = viewPortDims.getMinX(); - double minY = viewPortDims.getMinY(); - double width = viewPortDims.getWidth(); - double height = viewPortDims.getHeight(); - double widthOffset = viewPortDims.getWidth() * 3; - double heightOffset = viewPortDims.getHeight() * 3; - - BoundingBox preloadBox = new BoundingBox( - minX - widthOffset, - minY - heightOffset, - width + widthOffset*6, - height + heightOffset*6); -// BoundingBox preloadBox = new BoundingBox(minX , minY, width, height); - - removeCircleCells(preloadBox); - removeEdges(preloadBox); - removeHighlights(preloadBox); - - graph.updateCellLayer(); - - } - - public void clearUI() { - - // CellLayer cellLayer = (CellLayer) graph.getCellLayer(); - // cellLayer.getChildren().clear(); - // synchronized (Main.getLock()) { - - if (graph == null){ - System.out.println("------> graph is null."); - - } - // System.out.println("ConvertDBtoElementTree::clearUI"); - graph.clearCellLayer(); - // System.out.println("ConvertDBtoElementTree::clearUI: getHighlightsOnUI.size() " + graph.getModel().getHighlightsOnUI().size()); - - if (graph.getModel() != null) { - graph.getModel().clearMaps(); - - // System.out.println("ConvertDBtoElementTree::clearUI: getHighlightsOnUI.size() " + graph.getModel().getHighlightsOnUI().size()); - } - - // } - - // if (model != null && model.getCircleCellsOnUI() != null) - // model.getCircleCellsOnUI().clear(); - // - // if (model != null && model.getEdgesOnUI() != null) - // model.getEdgesOnUI().clear(); - - // Get the width for placeholder line. - String SQLMaxLevelCount = "select max(LEVEL_COUNT) from ELEMENT " + - "where ID_ENTER_CALL_TRACE in " + - "(SELECT CALL_TRACE.ID from CALL_TRACE where THREAD_ID = " + currentThreadId + ")"; - - int width = 0; - ResultSet rs = DatabaseUtil.select(SQLMaxLevelCount); - try { - if (rs.next()) { - width = rs.getInt(1); - } - } catch (SQLException e) { - e.printStackTrace(); - } - - - // Get the height for placeholder line. - String SQLMaxLeafCount = "select LEAF_COUNT from ELEMENT " + - "where LEVEL_COUNT = 1 AND ID = " + - "(SELECT PARENT_ID from ELEMENT_TO_CHILD " + - "where CHILD_ID = " + - "(SELECT id from ELEMENT " + - "where ID_ENTER_CALL_TRACE = " + - "(SELECT min(CALL_TRACE.ID) from CALL_TRACE " + - "where THREAD_ID = " + currentThreadId + ")))"; - - int height = 0; - rs = DatabaseUtil.select(SQLMaxLeafCount); - try { - if (rs.next()) { - height = rs.getInt(1); - } - } catch (SQLException e) { - e.printStackTrace(); - } - - Graph.drawPlaceHolderLines(height, width); - - // System.out.println("ConvertDBtoElementTree::clearUI: END"); - } - - public void setCurrentThreadId(String currentThreadId) { - this.currentThreadId = currentThreadId; - } - - public boolean isShowAllThreads() { - return showAllThreads; - } - - public void setShowAllThreads(boolean showAllThreads) { - this.showAllThreads = showAllThreads; - } - - // Region where UI components are loaded. - private static BoundingBox activeRegion; - - // Trigger UI components to be reloaded when visible viewport is outside this region. triggerRegion < activeRegion - private static BoundingBox triggerRegion; - - static boolean firstLoad = true; - - public boolean isUIDrawingRequired(BoundingBox viewPort) { - // System.out.println("ConvertDBtoElementTree::UiUpdateRequired:"); - - if (firstLoad) { - firstLoad = false; - return true; - } - - if (activeRegion == null) - setActiveRegion(viewPort); - - if (triggerRegion == null) - setTriggerRegion(viewPort); - - if (!triggerRegion.contains(viewPort)) { - setActiveRegion(viewPort); - setTriggerRegion(viewPort); - return true; - } - - if (graph.getModel().uiUpdateRequired) { - // System.out.println("ConvertDBtoElementTree::UiUpdateRequired: passed true"); - return true; - } - - return false; - } - - private void setActiveRegion(BoundingBox viewPort) { - this.activeRegion = new BoundingBox( - viewPort.getMinX() - viewPort.getWidth() * 3, - viewPort.getMinY() - viewPort.getHeight() * 3, - viewPort.getWidth() * 7, - viewPort.getHeight() * 7 - ); - - // System.out.println(); - // System.out.println("------------- New active region -------------"); - // System.out.println("Viewport: " + viewPort); - // System.out.println("activeRegion: " + activeRegion); - // System.out.println("triggerRegion: " + triggerRegion); - // System.out.println("------------------"); - } - - private void setTriggerRegion(BoundingBox viewPort) { - triggerRegion = new BoundingBox( - activeRegion.getMinX() + viewPort.getWidth(), - activeRegion.getMinY() + viewPort.getHeight(), - viewPort.getWidth() * 5, - viewPort.getHeight() * 5 - ); - - // System.out.println(); - // System.out.println("------------- New Triggering region -------------"); - // System.out.println("Viewport: " + viewPort); - // System.out.println("activeRegion: " + activeRegion); - // System.out.println("triggerRegion: " + triggerRegion); - // System.out.println("------------------"); - } - - public static void resetRegions() { - activeRegion = null; - triggerRegion = null; - firstLoad = true; - } - - public void setGraph(Graph graph) { - this.graph = graph; - } -} - diff --git a/src/main/java/com/application/fxgraph/ElementHelpers/GenerateUINodesFromElementTree.java b/src/main/java/com/application/fxgraph/ElementHelpers/GenerateUINodesFromElementTree.java deleted file mode 100644 index 7631e87..0000000 --- a/src/main/java/com/application/fxgraph/ElementHelpers/GenerateUINodesFromElementTree.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.application.fxgraph.ElementHelpers; - -public class GenerateUINodesFromElementTree { - -} diff --git a/src/main/java/com/application/fxgraph/cells/CircleCell.java b/src/main/java/com/application/fxgraph/cells/CircleCell.java deleted file mode 100644 index c82f5fb..0000000 --- a/src/main/java/com/application/fxgraph/cells/CircleCell.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.application.fxgraph.cells; - -import com.application.fxgraph.ElementHelpers.Element; -import com.application.fxgraph.graph.Cell; -import javafx.geometry.Pos; -import javafx.scene.control.Label; -import javafx.scene.paint.Color; -import javafx.scene.shape.Circle; -import javafx.scene.text.TextAlignment; - -public class CircleCell extends Cell { - - private Label label; - private Label idLabel; - private Label methodName; - private Circle circle; - - public CircleCell(String id) { - super(id); - - // Uncomment to see yellow background on the whole circle cell stack pane. - // setStyle("-fx-background-color: mediumslateblue"); - - circle = new Circle(20); - label = new Label("This is a long string"); - idLabel = new Label("-" + id + "-"); - - methodName = new Label(""); - methodName.setPrefWidth(85); - methodName.setWrapText(true); - methodName.setStyle("-fx-background-color: papayawhip; -fx-background-radius: 7; -fx-border-color: burlywood; -fx-border-radius: 7; -fx-border-width: 2"); - methodName.setAlignment(Pos.CENTER); - methodName.setTextAlignment(TextAlignment.CENTER); - circle.setStroke(Color.web("#003366")); - circle.setFill(Color.web("#6699CC")); - circle.relocate(0,0); - - // getChildren().setAll(circle, label); - getChildren().add(circle); - getChildren().add(methodName); - getChildren().add(idLabel); - // setView(group); - this.toFront(); - } - - public CircleCell (String id, Element element) { - this(id); - this.relocate( - element.getBoundBox().xCoordinate, - element.getBoundBox().yCoordinate - ); - this.toFront(); - } - - public CircleCell (String id, float xCoordinate, float yCoordinate) { - this(id); - this.relocate(xCoordinate , yCoordinate); - this.toFront(); - } - - public String getLabel() { - return label.getText(); - } - - public void setLabel(String text) { - this.label.setText(text); - } - - public String getMethodName() { - return methodName.getText(); - } - - public void setMethodName(String methodName) { - this.methodName.setText(methodName); - - // Center the method name label below the circle. - // this.methodName.setMinWidth(this.methodName.getText().length()*2); - this.methodName.relocate(-this.methodName.getPrefWidth() * .25, 45);//-this.methodName.getMinHeight()/2); - - } - - public void setColor(Color color) { - circle.setFill(color); - } - - - @Override - public String toString() { - return "CircleCell: id: " + getCellId() + "; x: " + getLayoutX() + "; y: " + getLayoutY(); - } -} \ No newline at end of file diff --git a/src/main/java/com/application/fxgraph/cells/RectangleCell.java b/src/main/java/com/application/fxgraph/cells/RectangleCell.java deleted file mode 100644 index 4a52633..0000000 --- a/src/main/java/com/application/fxgraph/cells/RectangleCell.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.application.fxgraph.cells; - -import com.application.fxgraph.graph.Cell; -import javafx.scene.paint.Color; -import javafx.scene.shape.Rectangle; - -public class RectangleCell extends Cell { - - public RectangleCell( String id) { - super( id); - - Rectangle view = new Rectangle( 50,50); - - view.setStroke(Color.DODGERBLUE); - view.setFill(Color.DODGERBLUE); - - setView( view); - - } - -} \ No newline at end of file diff --git a/src/main/java/com/application/fxgraph/cells/TriangleCell.java b/src/main/java/com/application/fxgraph/cells/TriangleCell.java deleted file mode 100644 index 75c3d81..0000000 --- a/src/main/java/com/application/fxgraph/cells/TriangleCell.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.application.fxgraph.cells; - -import com.application.fxgraph.graph.Cell; -import javafx.scene.paint.Color; -import javafx.scene.shape.Polygon; - -public class TriangleCell extends Cell { - - public TriangleCell( String id) { - super( id); - - double width = 50; - double height = 50; - - Polygon view = new Polygon( width / 2, 0, width, height, 0, height); - - view.setStroke(Color.RED); - view.setFill(Color.RED); - - setView( view); - - } - -} \ No newline at end of file diff --git a/src/main/java/com/application/fxgraph/graph/CellLayer.java b/src/main/java/com/application/fxgraph/graph/CellLayer.java deleted file mode 100644 index e8b2d30..0000000 --- a/src/main/java/com/application/fxgraph/graph/CellLayer.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.application.fxgraph.graph; - -import javafx.scene.layout.Pane; - -public class CellLayer extends Pane { - -} \ No newline at end of file diff --git a/src/main/java/com/application/fxgraph/graph/CellType.java b/src/main/java/com/application/fxgraph/graph/CellType.java deleted file mode 100644 index 9ee7814..0000000 --- a/src/main/java/com/application/fxgraph/graph/CellType.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.application.fxgraph.graph; - -public enum CellType { - - RECTANGLE, - TRIANGLE, - CIRCLE - ; - -} \ No newline at end of file diff --git a/src/main/java/com/application/fxgraph/graph/CollapseType.java b/src/main/java/com/application/fxgraph/graph/CollapseType.java deleted file mode 100644 index 6dcf42d..0000000 --- a/src/main/java/com/application/fxgraph/graph/CollapseType.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.application.fxgraph.graph; - -public class CollapseType { - public static int CELL_VISIBLE = 0; - public static int CELL_NOTVISIBLE = 1; - public static int CELL_CLICKED = 2; - public static int CELL_CLICKED_NOTVISIBLE = 3; - public static int CELL_PARENT_NOTVISIBLE = 4; - - public static int EDGE_VISIBLE = 0; - public static int EDGE_NOTVISIBLE = 1; - public static int EDGE_PARENT_NOTVISIBLE = 2; -} diff --git a/src/main/java/com/application/fxgraph/graph/ColorProp.java b/src/main/java/com/application/fxgraph/graph/ColorProp.java deleted file mode 100644 index 93d60d5..0000000 --- a/src/main/java/com/application/fxgraph/graph/ColorProp.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.application.fxgraph.graph; - -import javafx.scene.paint.Color; - -/** - * Defines all the colors. - */ -public class ColorProp { - public final static Color DISABLED = Color.LIGHTGRAY; - public final static Color ENABLED = Color.DIMGRAY; - public final static Color ENABLED_COLORFUL = Color.LAWNGREEN; - - public final static Color POSITIVE_GREEN = Color.LIMEGREEN; - public final static Color NEGATIVE_RED = Color.RED; - public final static Color INFO_BLUE = Color.SKYBLUE; - -} diff --git a/src/main/java/com/application/fxgraph/graph/Delta.java b/src/main/java/com/application/fxgraph/graph/Delta.java deleted file mode 100644 index 2c1f6e3..0000000 --- a/src/main/java/com/application/fxgraph/graph/Delta.java +++ /dev/null @@ -1,130 +0,0 @@ -/* -package com.application.fxgraph.graph; - -import com.application.db.DAOImplementation.ElementDAOImpl; -import com.application.db.DAOImplementation.TraceDAOImpl; -import javafx.concurrent.Task; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.LinkedHashMap; - -public class Delta { - - private final static int numberOfLeafsInGrid = 10; - private final static int gridSize = numberOfLeafsInGrid * BoundBox.unitHeightFactor; - - private static double height; - private static double screenBottomY; - private static LinkedHashMap deltaValMap = new LinkedHashMap<>(); - private static LinkedHashMap cellIDMap = new LinkedHashMap<>(); - - private static boolean calledOnce = false; - - - public static void init() { - ResultSet rootElementRS = ElementDAOImpl.selectWhere("ID_ENTER_CALL_TRACE = -1"); - try { - if (rootElementRS.next()) { - height = rootElementRS.getDouble("Bound_Box_Y_Bottom_Left"); - } - } catch (SQLException e) { - e.printStackTrace(); - } - - int ind = 0; - double val = 0; - while (ind < height) { - deltaValMap.put(ind, val++); - cellIDMap.put(ind, 0); - ind += gridSize; - } - } - - public static int getNextGridBottomY(double y) { - return ((int) (screenBottomY / gridSize) + 2) * gridSize; - } - - - public static void clearNextGridBottomY(double y) { - int nextGridBottomY = ((int) (y / gridSize) + 2 ) * gridSize; - deltaValMap.put(nextGridBottomY, 0d); - - System.out.println("Delta::clearNextGridBottomY: setting delta = 0 at y = " + y + " and nextGridBottomY = " + nextGridBottomY); - } - - - */ -/** - * This method is invoked when screen is scrolled. - * It checks if any updates are required in the cells below the next grid and if needed, triggers the updates in a background thread, - * - * @param screenBottomY - *//* - - public static void onScroll(double screenBottomY) { - Delta.screenBottomY = screenBottomY; - - // get next grid's bottom delta value - int nextGridBottomY = ((int) (Delta.screenBottomY / gridSize) + 2) * gridSize; - double delta = deltaValMap.get(nextGridBottomY); - - // trigger updates only if next grid's delta != 0 - // and if the updates were not already triggered for that grid. - if (delta != 0 && !calledOnce) { - calledOnce = true; - Task updateTask = EventHandlers.updateTreeBelowYWrapper(nextGridBottomY, delta); - // set delta = 0 at this gridbottom - updateTask.setOnSucceeded(event -> { - System.out.println("Delta::onScroll: background thread updateTask completed. Setting delta = 0 at this grid bottom."); - unSetCalledOnce(); - deltaValMap.put(nextGridBottomY, 0d); - }); - - new Thread(updateTask).start(); - } - } - - - public synchronized static void unSetCalledOnce() { - calledOnce = false; - } - - - // Keep recurring till the end of next grid is reached - public static boolean shouldRecurse(double y, int cellId, double delta) { - int nextGridBottomY = ((int) (screenBottomY / gridSize) + 2) * gridSize; - if (y < nextGridBottomY) { - return true; - } else { - updateDeltaVal(y, cellId, delta); - return false; - } - } - - public static double getDeltaVal(double y) { - int thisGridBottomY = ((int) (y / gridSize)) * gridSize; - return deltaValMap.get(thisGridBottomY); - } - - public static void updateDeltaVal(double y, int cellId, double newDeltaVal) { - int nextGridBottomY = ((int) (y / gridSize)) * gridSize; - cellIDMap.put(nextGridBottomY, cellId); - deltaValMap.put(nextGridBottomY, newDeltaVal + deltaValMap.get(nextGridBottomY)); - } - - - public static void resetDelta() { - deltaValMap.clear(); - cellIDMap.clear(); - calledOnce = false; - } - - // happy region -> current grid + upper grid + lower grid. - // loaded region -> happy + 1 upper grid + 1 lower grid. - - - // on scroll. - // if view port is not completely contained by happy region, then UIDrawing is required. - -}*/ diff --git a/src/main/java/com/application/fxgraph/graph/EventHandlers.java b/src/main/java/com/application/fxgraph/graph/EventHandlers.java deleted file mode 100644 index 0d94ce9..0000000 --- a/src/main/java/com/application/fxgraph/graph/EventHandlers.java +++ /dev/null @@ -1,1728 +0,0 @@ -package com.application.fxgraph.graph; - -import com.application.fxgraph.ElementHelpers.ConvertDBtoElementTree; -import com.application.Main; -import com.application.db.DAOImplementation.*; -import com.application.db.DatabaseUtil; -import com.application.db.TableNames; -import com.application.fxgraph.cells.CircleCell; -import javafx.application.Platform; -import javafx.concurrent.Task; -import javafx.event.EventHandler; -import javafx.geometry.Insets; -import javafx.scene.Node; -import javafx.scene.control.Button; -import javafx.scene.control.Label; -import javafx.scene.input.MouseEvent; -import javafx.scene.layout.GridPane; -import javafx.scene.paint.Color; -import javafx.scene.shape.Circle; -import org.controlsfx.control.PopOver; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.*; - -import static com.application.fxgraph.graph.Graph.cellLayer; - -public class EventHandlers { - - private static ConvertDBtoElementTree convertDBtoElementTree; - final DragContext dragContext = new DragContext(); - // static Map deltaCache = new HashMap<>(); - private boolean clickable = true; - private boolean subtreeExpanded = true; - private boolean posUpdated = true; - - - Graph graph; - static Main main; - - public EventHandlers(Graph graph) { - this.graph = graph; - } - - public static void resetEventHandlers() { - // deltaCache = new HashMap<>(); - } - - public void setCustomMouseEventHandlers(final Node node) { - // ***************** - // Show popup to display element details on mouse hover on an element. - // node.setOnMouseEntered(onMouseHoverToShowInfoEventHandler); - node.setOnMousePressed(onMouseHoverToShowInfoEventHandler); - // node.setOnMousePressed(onMousePressedToCollapseTree); - // ***************** - - - // ***************** - // For debugging. Prints all mouse events. - // node.addEventFilter(MouseEvent.ANY, onMouseHoverToShowInfoEventHandler); - // node.addEventFilter(MouseEvent.ANY, event -> System.out.println(event)); - // ***************** - - - // ***************** - // Click on an element to collapse the subtree rooted at that element. - // node.setOnMousePressed(onMousePressedToCollapseTree); - // ***************** - - - // ***************** - // To dismiss the pop over when cursor leaves the circle. But this makes it impossible to click buttons on pop - // over because the pop over hides when the cursor is moved to click the button. - // node.setOnMouseExited(onMouseExitToDismissPopover); - // ***************** - - - // ***************** - // Make elements draggable. - // node.setOnMousePressed(onMousePressedEventHandler); - // node.setOnMouseDragged(onMouseDraggedEventHandler); - // node.setOnMouseReleased(onMouseReleasedEventHandler); - // ***************** - - } - - private PopOver popOver; - - private EventHandler onMouseHoverToShowInfoEventHandler = new EventHandler() { - - @Override - public void handle(MouseEvent event) { - if (popOver != null) { - popOver.hide(); - } - - Node node = (Node) event.getSource(); - CircleCell cell = (CircleCell) node; - String timeStamp; - int methodId, processId, threadId; - String parameters, packageName = "", methodName = "", parameterTypes = "", eventType, lockObjectId; - double xCord, yCord; - - - // Do Not Uncomment - // String sql = "Select * from " + TableNames.ELEMENT_TABLE + " " + - // "JOIN " + TableNames.CALL_TRACE_TABLE + " ON " + TableNames.CALL_TRACE_TABLE + ".id = " + TableNames.ELEMENT_TABLE+ ".ID_ENTER_CALL_TRACE " + - // "JOIN " + TableNames.METHOD_DEFINITION_TABLE + " ON " + TableNames.METHOD_DEFINITION_TABLE + ".ID = " + TableNames.CALL_TRACE_TABLE + ".METHOD_ID " + - // "WHERE " + TableNames.ELEMENT_TABLE + ".ID = " + cell.getCellId(); - // System.out.println("your query: " + sql); - - // Please. Please do not try to combine the next two queries into one. Unless you want to spend another day tyring to prove it to yourself. - - String sql = "Select * from " + TableNames.ELEMENT_TABLE + " " + - "JOIN " + TableNames.CALL_TRACE_TABLE + " ON " + TableNames.CALL_TRACE_TABLE + ".id = " + TableNames.ELEMENT_TABLE + ".ID_ENTER_CALL_TRACE " + - "WHERE " + TableNames.ELEMENT_TABLE + ".ID = " + cell.getCellId(); - - try (ResultSet callTraceRS = DatabaseUtil.select(sql)) { - // try (ResultSet callTraceRS = CallTraceDAOImpl.selectWhere("id = (Select id_enter_call_trace FROM " + TableNames.ELEMENT_TABLE + - // " WHERE id = " + cell.getCellId() + ")")) { - if (callTraceRS.next()) { - timeStamp = callTraceRS.getString("time_instant"); - methodId = callTraceRS.getInt("method_id"); - processId = callTraceRS.getInt("process_id"); - threadId = callTraceRS.getInt("thread_id"); - parameters = callTraceRS.getString("parameters"); - eventType = callTraceRS.getString("message"); - lockObjectId = callTraceRS.getString("lockobjid"); - xCord = callTraceRS.getFloat("bound_box_x_coordinate"); - yCord = callTraceRS.getFloat("bound_box_y_coordinate"); - - - try (ResultSet methodDefRS = MethodDefnDAOImpl.selectWhere("id = " + methodId)) { - if (methodDefRS.next()) { - packageName = methodDefRS.getString("package_name"); - methodName = methodDefRS.getString("method_name"); - parameterTypes = methodDefRS.getString("parameter_types"); - } - - if (methodId == 0) { - methodName = eventType; - packageName = "N/A"; - parameterTypes = "N/A"; - parameters = "N/A"; - } - } catch (SQLException e) { - } - - // Save the clicked element into recent menu. - graph.addToRecent(packageName + "." + methodName, new Graph.XYCoordinate(xCord, yCord, threadId)); - - // System.out.println("hValue: " + graph.getScrollPane().getHvalue()); - // System.out.println("vValue: " + graph.getScrollPane().getVvalue()); - - - Label lMethodName = new Label(methodName); - Label lPackageName = new Label(packageName); - Label lParameterTypes = new Label(parameterTypes); - Label lParameters = new Label(parameters); - Label lProcessId = new Label(String.valueOf(processId)); - Label lThreadId = new Label(String.valueOf(threadId)); - Label lTimeInstant = new Label(timeStamp); - - GridPane gridPane = new GridPane(); - gridPane.setPadding(new Insets(10, 10, 10, 10)); - gridPane.setVgap(10); - gridPane.setHgap(20); - gridPane.add(new Label("Method Name: "), 0, 0); - gridPane.add(lMethodName, 1, 0); - - gridPane.add(new Label("Package Name: "), 0, 1); - gridPane.add(lPackageName, 1, 1); - - gridPane.add(new Label("Parameter Types: "), 0, 2); - gridPane.add(lParameterTypes, 1, 2); - - gridPane.add(new Label("Parameters: "), 0, 3); - gridPane.add(lParameters, 1, 3); - - gridPane.add(new Label("Process ID: "), 0, 4); - gridPane.add(lProcessId, 1, 4); - - gridPane.add(new Label("Thread ID: "), 0, 5); - gridPane.add(lThreadId, 1, 5); - - gridPane.add(new Label("Time of Invocation: "), 0, 6); - gridPane.add(lTimeInstant, 1, 6); - - - /* - * wait-enter -> lock released. - * Get all elements with same lock id and notify-enter - * wait-exit -> lock reacquired. - * - * notify-enter / notify-exit -> lock released - * - * object lock flow: - * wait-enter -> notify-enter / notify-exit -> wait-exit - * */ - - List ctIdList = new ArrayList<>(); - List eleIdList = new ArrayList<>(); - if (eventType.equalsIgnoreCase("WAIT-ENTER")) { - int ctId = -2; // Will throw exception if value not changed. Which is what we want. - sql = "lockobjid = '" + lockObjectId + "'" + - " AND (message = 'NOTIFY-ENTER' OR message = 'NOTIFYALL-ENTER')" + - " AND time_instant >= " + "'" + timeStamp + "'"; - - try (ResultSet rs = CallTraceDAOImpl.selectWhere(sql)) { - if (rs.next()) { - ctId = rs.getInt("id"); - ctIdList.add(ctId); - } - } - - try (ResultSet elementRS = ElementDAOImpl.selectWhere("id_enter_call_trace = " + ctId)) { - // Expecting to see a single row. - if (elementRS.next()) { - int elementId = elementRS.getInt("id"); - eleIdList.add(elementId); - } - } - } else if (eventType.equalsIgnoreCase("NOTIFY-ENTER")) { - - try (Connection conn = DatabaseUtil.getConnection(); Statement ps = conn.createStatement()) { - - - sql = "SELECT * FROM " + TableNames.CALL_TRACE_TABLE + " AS parent\n" + - "WHERE MESSAGE = 'WAIT-EXIT' \n" + - "AND LOCKOBJID = '" + lockObjectId + "' " + - "AND TIME_INSTANT >= '" + timeStamp + "' \n" + - "AND (SELECT count(*) \n" + - "FROM " + TableNames.CALL_TRACE_TABLE + " AS child \n" + - "WHERE child.message = 'WAIT-ENTER' \n" + - "AND LOCKOBJID = '" + lockObjectId + "' " + - "AND child.TIME_INSTANT >= '" + timeStamp + "' \n" + - "AND child.TIME_INSTANT <= parent.time_instant\n" + - ")\n" + - "= 0\n"; - - // System.out.println("Sql: " + sql); - int ctId = -2; - try (ResultSet resultSet = ps.executeQuery(sql)) { - if (resultSet.next()) { - ctId = resultSet.getInt("id"); - ctIdList.add(ctId); - } - } - - try (ResultSet elementRS = ElementDAOImpl.selectWhere("id_exit_call_trace = " + ctId)) { - // Expecting to see a single row. - if (elementRS.next()) { - int elementId = elementRS.getInt("id"); - eleIdList.add(elementId); - } - } - } - - } else if (eventType.equalsIgnoreCase("NOTIFYALL-ENTER")) { - try (Connection conn = DatabaseUtil.getConnection(); - Statement ps = conn.createStatement();) { - - - sql = "SELECT * FROM " + TableNames.CALL_TRACE_TABLE + " AS parent WHERE MESSAGE = 'WAIT-EXIT' " + - "AND LOCKOBJID = '" + lockObjectId + "' " + - "AND TIME_INSTANT >= '" + timeStamp + "' " + - "AND (SELECT count(*) FROM " + TableNames.CALL_TRACE_TABLE + " AS child " + - "WHERE child.message = 'WAIT-ENTER' " + - "AND LOCKOBJID = '" + lockObjectId + "' " + - "AND child.TIME_INSTANT >= '" + timeStamp + "' " + - "AND child.TIME_INSTANT <= parent.time_instant ) = 0"; - - int ctId = -2; - - try (ResultSet resultSet = ps.executeQuery(sql)) { - while (resultSet.next()) { - ctId = resultSet.getInt("id"); - ctIdList.add(ctId); - } - } - - ctIdList.stream().forEach(id -> { - try (ResultSet elementRS = ElementDAOImpl.selectWhere("id_exit_call_trace = " + id)) { - // Can be more than a single row. - while (elementRS.next()) { - int elementId = elementRS.getInt("id"); - eleIdList.add(elementId); - } - } catch (SQLException e) { - } - }); - } - } - - List