Advertisement
Guest User

Main

a guest
Oct 6th, 2018
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.55 KB | None | 0 0
  1. // Homework 5
  2. // Drake Herman
  3. // CIS 357
  4. // Dr. Cho
  5. // 4-10-18
  6. // Desc in first java doc comment
  7.  
  8. import java.sql.Connection;
  9. import java.sql.DatabaseMetaData;
  10. import java.sql.DriverManager;
  11. import java.sql.ResultSet;
  12. import java.sql.SQLException;
  13. import java.sql.Statement;
  14.  
  15. import javafx.application.Application;
  16. import javafx.beans.property.SimpleStringProperty;
  17. import javafx.beans.value.ObservableValue;
  18. import javafx.collections.FXCollections;
  19. import javafx.collections.ObservableList;
  20. import javafx.geometry.Insets;
  21. import javafx.scene.Scene;
  22. import javafx.scene.control.Button;
  23. import javafx.scene.control.ComboBox;
  24. import javafx.scene.control.Label;
  25. import javafx.scene.control.ListView;
  26. import javafx.scene.control.PasswordField;
  27. import javafx.scene.control.SelectionMode;
  28. import javafx.scene.control.TableColumn;
  29. import javafx.scene.control.TableColumn.CellDataFeatures;
  30. import javafx.scene.control.TableView;
  31. import javafx.scene.control.TextField;
  32. import javafx.scene.input.MouseEvent;
  33. import javafx.scene.layout.GridPane;
  34. import javafx.stage.Stage;
  35. import javafx.stage.WindowEvent;
  36. import javafx.util.Callback;
  37.  
  38. public class Homework5Herman extends Application{
  39.  
  40. private Scene scene1, scene2, scene3; // variables for scenes
  41. private Stage window; // variable for the main stage
  42. private Connection connection; // variable for connection
  43.  
  44. /**
  45. * Homework 5 implements a mechanism for connecting to a database,
  46. * searching the tables of the database, filtering specific fields
  47. * of the database table, applying conditions to these fields, and
  48. * displaying the database itself. This program implements extra
  49. * credit numbers 1, 3 (minus all function), and 4.
  50. *
  51. * @author Drake Herman
  52. * @version 1.0
  53. * @since 4-10-18
  54. *
  55. * @param args command-line arguments
  56. */
  57. public static void main(String[] args) {
  58. launch(args);
  59. }
  60.  
  61. /**
  62. * This is the start method which creates the primary stage and
  63. * assigns it to the variable window. This method calls loginScreen
  64. * and windowClosed. From this method the basis of the program is
  65. * executed and instructions on how to handle closing the window
  66. * are assigned.
  67. *
  68. * @param primaryStage creates the stage for the GUI
  69. */
  70. @Override
  71. public void start(Stage primaryStage) {
  72. window = primaryStage;
  73.  
  74. loginScreen();
  75.  
  76. // How to close windows
  77. window.setOnCloseRequest(e -> windowClosed(e));
  78. }
  79.  
  80. /**
  81. * This is the loginScreen method which calls createGridPane,
  82. * and clickedConnect. This method creates the login GUI in a
  83. * GridPane and allows the user to connect to the database.
  84. */
  85. public void loginScreen() {
  86. GridPane gdpOne = createGridPane();
  87.  
  88. //Creating GUI nodes
  89. Label lblUsername = new Label("Username :");
  90. TextField txtUsername = new TextField("ddherman");
  91. Label lblPassword = new Label("Password :");
  92. PasswordField pwfPassword = new PasswordField();
  93. pwfPassword.setText("ddhermancis357d");
  94. Button btnConnect = new Button("Connect");
  95. btnConnect.setOnMouseClicked(e -> clickedConnect(e, txtUsername, pwfPassword));
  96.  
  97. //Adding to the the GridPane
  98. gdpOne.add(lblUsername, 0, 0);
  99. gdpOne.add(txtUsername, 1, 0);
  100. gdpOne.add(lblPassword, 0, 1);
  101. gdpOne.add(pwfPassword, 1, 1);
  102. gdpOne.add(btnConnect, 1, 2);
  103.  
  104. scene1 = new Scene(gdpOne); //sets the pane to the scene
  105. window.setTitle("Login");
  106. window.setScene(scene1); //sets the scene to the stage
  107. window.show(); //displays the stage
  108. }
  109.  
  110. /**
  111. * This is the inputScreen method which calls the createGridPane and
  112. * setTableNames. This method creates the GUI for the input scene,
  113. * fills the ComboBox and assigns the action for the execute button.
  114. * From this method the user can select tables from the database,
  115. * select fields, and apply conditions.
  116. *
  117. * @throws SQLException no items to be added to the ComboBox
  118. */
  119. public void inputScreen() throws SQLException {
  120. GridPane gdpTwo = createGridPane();
  121.  
  122. //creating GUI nodes
  123. Label lblTables = new Label("Table :");
  124. Label lblFields = new Label("Fields :");
  125. Label lblConditions = new Label("Conditions :");
  126. TextField txtConditions = new TextField();
  127. Button btnExecute = new Button("Execute");
  128. ComboBox<String> cbxTables = setTableNames();
  129. ListView<String> lstView = new ListView<>();
  130.  
  131. //adding to the GridPane
  132. gdpTwo.add(lblTables, 0, 0);
  133. gdpTwo.add(cbxTables, 1, 0);
  134. gdpTwo.add(lblFields, 0, 1);
  135. gdpTwo.add(lstView, 1, 1);
  136. gdpTwo.add(lblConditions, 0, 2);
  137. gdpTwo.add(txtConditions, 1, 2);
  138. gdpTwo.add(btnExecute, 1, 3);
  139.  
  140. //populating the ComboBox
  141. cbxTables.getSelectionModel().selectedItemProperty().addListener(
  142. (observable, oldValue, newValue) -> {
  143. String selectedTable = cbxTables.getValue().toString();
  144. try {
  145. lstView.getItems().clear();
  146. lstView.setItems(getListView(selectedTable));
  147. lstView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
  148. } catch (SQLException ex) {
  149. System.out.println("No items");
  150. }
  151. });
  152.  
  153. //action for button execute
  154. btnExecute.setOnMouseClicked(e -> {
  155. String Query = createQuery(lstView, cbxTables, txtConditions);
  156. System.out.println(Query);
  157. outputScreen(Query);
  158. });
  159.  
  160. scene2 = new Scene(gdpTwo); //sets the pane to the scene
  161. window.setTitle("Input");
  162. window.setScene(scene2); //sets the scene to the stage
  163. }
  164.  
  165. /**
  166. * This is the outputScreen method which calls the conditionError
  167. * method. This method creates a table view and dynamically sizes it to
  168. * fit the given query. This method handles null values in the database
  169. * by assigning their value to none. In the even an invalid condition
  170. * is given this method will call conditionError and display an
  171. * error window.
  172. *
  173. * @param Query the query to be executed
  174. */
  175. @SuppressWarnings("unchecked")
  176. public void outputScreen(String Query) {
  177. TableView<String> tableView = new TableView<String>();
  178.  
  179. ObservableList data = FXCollections.observableArrayList();
  180.  
  181. try {
  182. ResultSet rs = connection.createStatement().executeQuery(Query);
  183.  
  184. for(int i = 0 ; i < rs.getMetaData().getColumnCount(); i++){
  185. //Setting columns for the tableView
  186. final int j = i;
  187. TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i+1));
  188. col.setCellValueFactory(new Callback<CellDataFeatures<ObservableList, String>,
  189. ObservableValue<String>>(){
  190. public ObservableValue<String> call(CellDataFeatures<ObservableList, String> param) {
  191. return new SimpleStringProperty(param.getValue().get(j).toString());
  192. }
  193. });
  194.  
  195. tableView.getColumns().addAll(col);
  196. }
  197.  
  198. //Iterating rows and columns and adding data
  199. while(rs.next()){
  200. ObservableList<String> row = FXCollections.observableArrayList();
  201. for(int i = 1 ; i <= rs.getMetaData().getColumnCount(); i++){
  202. if (rs.getString(i) == null) {
  203. row.add("none");
  204. } else {
  205. row.add(rs.getString(i));
  206. }
  207. }
  208.  
  209. data.add(row);
  210. }
  211.  
  212. tableView.setItems(data);
  213.  
  214. tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
  215. scene3 = new Scene(tableView); //sets table to scene
  216. window.setTitle("Output");
  217. window.setScene(scene3); //sets scene to stage
  218. } catch (SQLException e) {
  219. conditionError(); //call for invalid conditions
  220. }
  221. }
  222.  
  223. /**
  224. * This is the windowClosed method which calls the
  225. * inputScreen and loginScreen methods. This method handles
  226. * switching between screens on closes based on the stage
  227. * title. In the even the program does't need to be closed
  228. * Completely the method consumes the close request.
  229. *
  230. * @param e a setOnCloseRequest event
  231. */
  232. public void windowClosed(WindowEvent e) {
  233. if (window.getTitle() == "Output") {
  234. try {
  235. inputScreen(); //goes back to input screen
  236. } catch (SQLException e1) {
  237. e1.printStackTrace();
  238. }
  239. e.consume(); //keeps the GUI open
  240. } else if (window.getTitle() == "Input") {
  241. loginScreen(); //goes back to the login screen
  242. e.consume(); //keeps the GUI open.
  243. } else {
  244. //allows the GUI to close on the login screen
  245. }
  246. }
  247.  
  248. /**
  249. * This is the conditionError method which handles invalid
  250. * condition inputs in the inputScreen method. This method
  251. * creates a new stage with a GridPane that instructs the user on
  252. * how to correct the error they made.
  253. */
  254. public void conditionError() {
  255. Stage error = new Stage();
  256. GridPane gdpError = createGridPane();
  257.  
  258. //creates the user instructions
  259. Label lblInstruct = new Label("Make sure only <, >, <=, >=, " +
  260. "==, AND, or OR are being used.");
  261. Label lblInstruct2 = new Label("Also check that values are " +
  262. "surrounded in ' '");
  263.  
  264. //adds the labels to the pane
  265. gdpError.add(lblInstruct, 0, 0);
  266. gdpError.add(lblInstruct2, 0, 1);
  267.  
  268. Scene scene = new Scene(gdpError); //sets the pane to the scene
  269. error.setTitle("Invalid Conditions Error");
  270. error.setScene(scene); //sets the scene to the
  271. error.show();
  272. }
  273.  
  274. /**
  275. * This is the clickedConnect method which calls the loadDriver and inputScreen
  276. * methods. This method loads the jdbc driver and establishes a connection
  277. * from the user to the database. Once a connection has been established the
  278. * user is then sent to the input screen.
  279. *
  280. * @param e a setOnMouseClicked event
  281. * @param username the TextField the username is entered in
  282. * @param password the PasswordField the password is entered in
  283. */
  284. public void clickedConnect(MouseEvent e, TextField username, PasswordField password) {
  285. //Load the driver
  286. loadDriver();
  287.  
  288. //Establish the connection
  289. try {
  290. connection = DriverManager.getConnection("jdbc:mysql://10.8.30.49:3306/ddherman" ,
  291. username.getText(), password.getText());
  292. System.out.println("Connection successful");
  293.  
  294. inputScreen();
  295. } catch (SQLException e1) {
  296. System.out.println("Failed to connect");
  297. }
  298. }
  299.  
  300. /**
  301. * This is the setTableNames method which connects to the database and
  302. * populates the ComboBox with the table names found. This method is designed
  303. * so that if at any point more table names are found they will also be added
  304. * to the ComboBox.
  305. *
  306. * @return a ComboBox with a populated list of table names
  307. * @throws SQLException thrown when no tables can be found
  308. */
  309. public ComboBox<String> setTableNames() throws SQLException {
  310. ComboBox<String> cbx = new ComboBox<>();
  311. ObservableList<String> tableNames = FXCollections.observableArrayList();
  312.  
  313. DatabaseMetaData dbmd = connection.getMetaData();
  314. ResultSet rs = dbmd.getTables(null, null, "%", null);
  315.  
  316. while (rs.next()) {
  317. String tableName = rs.getString(3); //gets table names
  318.  
  319. tableNames.add(tableName); //adds table names to a list
  320. }
  321.  
  322. cbx.setItems(tableNames); //adds the list to the ComboBox
  323.  
  324. return cbx;
  325. }
  326.  
  327. /**
  328. * This is the getListView method which traverses the given table
  329. * for its column names and adds them to a list. This list is then returned
  330. * so it can be used to populate a ListView.
  331. *
  332. * @param table the table in which to add columns from
  333. * @return an SQL statement with the given fields
  334. * @throws SQLException throws when no columns are found
  335. */
  336. public ObservableList<String> getListView(String table) throws SQLException {
  337. //list of column names from the table
  338. ObservableList<String> columnNames = FXCollections.observableArrayList();
  339. Statement statement = connection.createStatement();
  340. ResultSet rs = statement.executeQuery("SELECT DISTINCT COLUMN_NAME " +
  341. "FROM INFORMATION_SCHEMA.COLUMNS " +
  342. "WHERE TABLE_NAME = '" + table + "'");
  343.  
  344. //adds column names to the list
  345. while (rs.next()) {
  346. columnNames.add(rs.getString("COLUMN_NAME"));
  347. }
  348.  
  349. return columnNames;
  350. }
  351.  
  352. /**
  353. * This is the createQuery method which calls the checkConditions method.
  354. * This method creates a statement based on the selected table from the
  355. * ComboBox and the selected fields from the ListView. The selected items
  356. * are then formatted into SQL syntax and added to a string.
  357. *
  358. * @param columns the ListView for selected fields
  359. * @param table the ComboBox for selected table name
  360. * @param txt the TextField containing the conditions
  361. * @return the finished, formatted SQL statement
  362. */
  363. public String createQuery(ListView<String> columns, ComboBox<String> table, TextField txt) {
  364. ObservableList<String> selectedItems = columns.getSelectionModel().getSelectedItems();
  365. String[] theQuery = {"SELECT "}; //adds SELECT to the start of the statement
  366. selectedItems.forEach((String) -> {
  367. theQuery[0] += String + ", "; //adds the field name followed by a comma
  368. });
  369.  
  370. //removes the extra end comma
  371. String editQuery = theQuery[0].substring(0, theQuery[0].length() - 2);
  372. //adds FROM and the table name to the statement
  373. editQuery += " FROM " + table.getValue().toString();
  374.  
  375. //checks if any conditions have been specified
  376. editQuery = checkConditions(editQuery, txt);
  377.  
  378. return editQuery;
  379. }
  380.  
  381. /**
  382. * This is the checkConditions method which adds any conditions
  383. * specified in the conditions TextField to the SQL statement from
  384. * createQuery and formats them to SQL statement syntax.
  385. *
  386. * @param query a previously created SQL statement
  387. * @param txt the TextField containing the specified conditions
  388. * @return an SQL statement with conditions added.
  389. */
  390. public String checkConditions(String query, TextField txt) {
  391. //check if any conditions have been specified
  392. if (txt.getText().trim().isEmpty() != true) {
  393. query += " Where " + txt.getText();
  394. }
  395.  
  396. return query;
  397. }
  398.  
  399. /**
  400. * This is the createGridPane method which creates and formats the
  401. * GridPanes used in loginScreen and inputScreen.
  402. *
  403. * @return a formatted GridPane
  404. */
  405. public GridPane createGridPane() {
  406. GridPane gridPane = new GridPane();
  407. gridPane.setPadding(new Insets(10, 10, 10, 10));
  408. gridPane.setVgap(8);
  409. gridPane.setHgap(8);
  410.  
  411. return gridPane;
  412. }
  413.  
  414. /**
  415. * This is the loadDriver method which loads the jdbc driver so the
  416. * user can connect in the connectClicked method.
  417. */
  418. public void loadDriver() {
  419. try {
  420. Class.forName("com.mysql.jdbc.Driver");
  421. System.out.println("Driver Loaded");
  422. } catch (ClassNotFoundException e1) {
  423. System.out.println("Driver failed to load");
  424. }
  425. }
  426. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement