1 package com.quikj.application.utilities.sqlc; 2 3 4 import java.awt.*; 5 import java.awt.event.*; 6 import java.sql.*; 7 import java.util.*; 8 import java.io.*; 9 10 public class SqlConsole extends Frame 11 { 12 private static final String VERSION = "1.1b"; 13 14 private static final int FONT_STYLE = Font.PLAIN; 15 private static final int FONT_SIZE = 14; 16 private static final String PRINT_FONT_NAME = "Monospaced"; 17 private static final float FONT_PRINT_SCALE_FACTOR = (float)0.5; 18 private static final int FONT_PRINT_INSET_X = 30; 19 private static final int FONT_PRINT_INSET_Y = 30; 20 private static final String FONT_WIDTH_MEASUREMENT_STRING = 21 " ABCDabcd01231234 pqrsPQRS 012 "; 22 23 private TextArea commandString; 24 private TextArea resultString; 25 26 private static final int MAX_COLUMN_LENGTH = 255; 27 28 private Connection connection = null; 29 private DBConnection dbConn = null; 30 private String dbName; 31 private String fileName = null; 32 private boolean standalone; 33 private SQLConsoleExitListener listener = null; 34 private boolean enableExitOnLoginDialog = false; 35 private String loginName; 36 37 public SqlConsole(String jdbc_driver, 38 String db_name, 39 String file, 40 boolean standalone, 41 boolean disable_logout, 42 boolean enable_exit_on_login_dialog, 43 String login_name) 44 throws Exception 45 { 46 super("SQL Console : not logged in"); 47 dbName = db_name; 48 fileName = file; 49 this.standalone = standalone; 50 enableExitOnLoginDialog = enable_exit_on_login_dialog; 51 loginName = login_name; 52 53 dbConn = new DBConnection(jdbc_driver); 55 GridBagLayout gbl = new GridBagLayout(); 56 GridBagConstraints gbc = new GridBagConstraints(); 57 setLayout(gbl); 58 59 MenuBar mbar = new MenuBar(); 60 setMenuBar(mbar); 61 62 Menu file_menu = new Menu(" File "); 63 mbar.add(file_menu); 64 65 if (disable_logout == false) 66 { 67 MenuItem logout_mi = new MenuItem(" logout "); 68 logout_mi.addActionListener(new LogoutListener()); 69 file_menu.add(logout_mi); 70 } 71 72 MenuItem import_mi = new MenuItem(" Execute from File ... "); 73 import_mi.addActionListener(new ImportListener()); 74 file_menu.add(import_mi); 75 76 MenuItem save_mi = new MenuItem(" Save ... "); 77 save_mi.addActionListener(new SaveListener()); 78 file_menu.add(save_mi); 79 80 MenuItem print_mi = new MenuItem(" Print ... "); 81 print_mi.addActionListener(new PrintListener()); 82 file_menu.add(print_mi); 83 84 file_menu.addSeparator(); 85 86 MenuItem exit_mi = new MenuItem(" Exit "); 87 exit_mi.addActionListener(new ExitListener()); 88 file_menu.add(exit_mi); 89 90 Menu edit_menu = new Menu(" Edit "); 91 mbar.add(edit_menu); 92 93 MenuItem clear_mi = new MenuItem(" Clear "); 94 clear_mi.addActionListener(new ResetListener()); 95 edit_menu.add(clear_mi); 96 97 edit_menu.addSeparator(); 98 99 MenuItem select_mi = new MenuItem(" Select All "); 100 select_mi.addActionListener(new SelectListener()); 101 edit_menu.add(select_mi); 102 103 MenuItem copy_mi = new MenuItem(" Copy "); 104 copy_mi.addActionListener(new CopyListener()); 105 edit_menu.add(copy_mi); 106 107 MenuItem paste_mi = new MenuItem(" Paste "); 108 paste_mi.addActionListener(new PasteListener()); 109 edit_menu.add(paste_mi); 110 111 Panel panel1 = new Panel(); 112 panel1.setLayout(gbl); 113 114 addToContainer(panel1, 115 gbl, 116 gbc, 117 new Label("SQL>"), 118 0, 119 0, 120 1, 121 1, 122 GridBagConstraints.BOTH, 123 GridBagConstraints.NORTHWEST, 124 0, 0); 125 126 commandString = new TextArea(5, 80); 127 commandString.setFont(new Font("Monospaced", 128 Font.PLAIN, 129 14)); 130 commandString.setEditable(false); 131 132 addToContainer(panel1, 133 gbl, 134 gbc, 135 commandString, 136 0, 137 1, 138 1, 139 1, 140 GridBagConstraints.BOTH, 141 GridBagConstraints.NORTHWEST, 142 100, 0); 143 commandString.addKeyListener(new SpecialKeyListener()); 144 145 Button submit_button = new Button(" Submit "); 146 submit_button.addActionListener(new SubmitListener()); 147 addToContainer(panel1, 148 gbl, 149 gbc, 150 submit_button, 151 1, 152 1, 153 1, 154 1, 155 GridBagConstraints.NONE, 156 GridBagConstraints.NORTHWEST, 157 0, 0); 158 159 addToContainer(panel1, 160 gbl, 161 gbc, 162 new Label("Result"), 163 0, 164 2, 165 1, 166 1, 167 GridBagConstraints.NONE, 168 GridBagConstraints.NORTHWEST, 169 0, 0); 170 171 resultString = new TextArea(8, 80); 172 resultString.setFont(new Font("Monospaced", 173 Font.PLAIN, 174 14)); 175 resultString.setEditable(false); 176 addToContainer(panel1, 177 gbl, 178 gbc, 179 resultString, 180 0, 181 3, 182 1, 183 1, 184 GridBagConstraints.BOTH, 185 GridBagConstraints.NORTHWEST, 186 100, 100); 187 188 addToContainer(this, 190 gbl, 191 gbc, 192 panel1, 193 0, 194 0, 195 1, 196 1, 197 GridBagConstraints.BOTH, 198 GridBagConstraints.NORTHWEST, 199 100, 100, 200 new Insets(5, 5, 0, 5)); 201 202 Panel panel2 = new Panel(); 203 panel2.setLayout(gbl); 204 205 Button logout_button = new Button(" logout "); 206 logout_button.addActionListener(new LogoutListener()); 207 addToContainer(panel2, 208 gbl, 209 gbc, 210 logout_button, 211 0, 212 0, 213 1, 214 1, 215 GridBagConstraints.NONE, 216 GridBagConstraints.CENTER, 217 0, 0); 218 219 if (disable_logout == true) 220 { 221 logout_button.setEnabled(false); 222 } 223 224 Button reset_button = new Button(" Clear "); 225 reset_button.addActionListener(new ResetListener()); 226 addToContainer(panel2, 227 gbl, 228 gbc, 229 reset_button, 230 1, 231 0, 232 1, 233 1, 234 GridBagConstraints.NONE, 235 GridBagConstraints.CENTER, 236 0, 0); 237 238 addToContainer(this, 240 gbl, 241 gbc, 242 panel2, 243 0, 244 1, 245 1, 246 1, 247 GridBagConstraints.BOTH, 248 GridBagConstraints.NORTHWEST, 249 0, 0, new Insets(5, 5, 5, 5)); 250 251 addWindowListener(new WindowCloseListener()); 252 253 pack(); 254 show(); 255 while (login(db_name) == false) ; 256 } 257 258 public void setExitListener(SQLConsoleExitListener listener) 259 { 260 this.listener = listener; 261 } 262 263 private boolean login(String db_name) 264 { 265 LoginDialog ld = new LoginDialog(this, "", enableExitOnLoginDialog, loginName); 266 String host = ld.getHost(); 267 if (host.length() <= 0) host = new String ("localhost"); 268 String db = ld.getDb(); 269 if (db.length() <= 0) db = new String ("test"); 270 271 try 272 { 273 dbConn.login("jdbc:" + db_name, 274 host, 275 ld.getUser(), 276 ld.getPassword(), 277 db); 278 279 connection = dbConn.getConnection(); 280 setTitle("SQL Console : user \"" 281 + dbConn.getUser() 282 + "\" host \"" + dbConn.getHost() + "\""); 283 284 if (fileName != null) 285 { 286 File file = new File(fileName); 287 try 288 { 289 FileReader freader = new FileReader(file); 290 291 StringBuffer buffer = new StringBuffer (); 292 int count = 0; 293 char[] read_buffer = new char[100]; 294 while(count >= 0) 295 { 296 count = freader.read(read_buffer); 297 if (count >= 0) 298 { 299 buffer.append(read_buffer, 0, count); 300 } 301 } 302 303 freader.close(); 304 305 commandString.setText(buffer.toString()); 307 308 processQuery(); 310 } 311 catch (IOException ex1) 312 { 313 new YesNoDialog(this, "Error ! ", 314 "IO Exception : " + ex1.getMessage(), 315 " Dismiss ", null); 316 } 317 } 318 319 commandString.setEditable(true); 320 return true; 321 } 322 catch (SQLException ex1) 323 { 324 new YesNoDialog(this, "Error !", 325 ex1.getMessage(), 326 " Dismiss ", null); 327 return false; 328 } 329 } 330 331 private void close() 332 { 333 try 334 { 335 if (connection != null) dbConn.dispose(); 336 } 337 catch (SQLException ex) 338 { 339 new YesNoDialog(SqlConsole.this, "Error ! ", 340 "SQLException : " + ex.getMessage(), 341 " Dismiss ", null); 342 } 343 344 SqlConsole.this.hide(); 345 SqlConsole.this.dispose(); 346 347 if (standalone == true) 348 { 349 System.exit(0); 350 } 351 else if (listener != null) 352 { 353 listener.actionPerformed(); 354 } 355 } 356 357 private void logout() 358 { 359 try 360 { 361 dbConn.dispose(); 362 connection = null; 363 clear(); 364 setTitle("SQL Console : not logged in"); 365 commandString.setEditable(false); 366 367 while (login(dbName) == false) ; 368 } 369 catch (SQLException ex) 370 { 371 new YesNoDialog(SqlConsole.this, "Error ! ", 372 "SQLException : " + ex.getMessage(), 373 " Dismiss ", null); 374 } 375 } 376 377 private void clear() 378 { 379 resultString.setText(""); 380 commandString.setText(""); 381 } 382 383 private void processQuery() 384 { 385 String command = commandString.getText(); 386 387 StringTokenizer strtok = new StringTokenizer(command, ";"); 388 int num_tokens = strtok.countTokens(); 389 390 commandString.setText(""); 391 for (int k = 0; k < num_tokens; k++) 392 { 393 String token = strtok.nextToken().trim(); 394 395 if (token.length() > 0) 396 { 397 resultString.append("SQL> " + token + '\n'); 398 try 399 { 400 Statement s = connection.createStatement(); 401 boolean result_available = s.execute(token); 402 403 if (result_available == true) 404 { 405 ResultSet r = s.getResultSet(); 406 ResultSetMetaData m = r.getMetaData(); 407 408 int cols = m.getColumnCount(); 410 int width = 0; 411 StringBuffer buffer = new StringBuffer (); 412 StringBuffer bar = new StringBuffer (); 413 int i; 414 int row_count = 0; 415 416 for (i = 0; i < cols; i++) 418 { 419 int col_width = m.getColumnDisplaySize(i+1); 420 if (col_width > MAX_COLUMN_LENGTH) 421 { 422 col_width = MAX_COLUMN_LENGTH; 423 } 424 width += col_width; 425 } 426 width += 1 + cols; 427 428 for (i = 0; i < width; i++) 429 { 430 bar.append('-'); 431 } 432 bar.append('\n'); 433 buffer.append(bar + "|"); 434 435 for (i = 0; i < cols; i++) 437 { 438 StringBuffer filler = new StringBuffer (); 439 String label = m.getColumnLabel(i+1); 440 int size = m.getColumnDisplaySize(i+1); 441 if (size > MAX_COLUMN_LENGTH) 442 { 443 size = MAX_COLUMN_LENGTH; 444 } 445 446 int x; 447 if (label.length() > size) 448 { 449 label = label.substring(0, size); 450 } 451 452 if (label.length() < size) 453 { 454 x = size - label.length(); 455 int j; 456 for (j = 0; j < x; j++) 457 { 458 filler.append(' '); 459 } 460 461 label = label + filler; 462 } 463 464 buffer.append(label + "|"); 465 } 466 467 buffer.append("\n" + bar); 469 470 while (r.next() == true) 472 { 473 row_count++; 474 buffer.append("|"); 475 476 for (i = 0; i < cols; i++) 478 { 479 StringBuffer filler = new StringBuffer (); 480 Object value = r.getObject(i+1); 481 482 int size = m.getColumnDisplaySize(i+1); 483 if (size > MAX_COLUMN_LENGTH) 484 { 485 size = MAX_COLUMN_LENGTH; 486 } 487 String str; 488 489 if (value == null) 490 { 491 str = ""; 492 } 493 else 494 { 495 if ((value instanceof byte[]) == true) 496 { 497 str = new String ((byte[])value); 498 } 499 else 500 { 501 str = value.toString(); 502 } 503 } 504 505 if (str.length() > size) 506 { 507 str = str.substring(0, size); 508 } 509 510 if (str.length() < size) 511 { 512 int x = size - str.length(); 513 int j; 514 for (j = 0; j < x; j++) 515 { 516 filler.append(' '); 517 } 518 str = str + filler; 519 } 520 521 str = str.replace('\n', ' '); 522 523 524 buffer.append(str + "|"); 525 } 526 buffer.append("\n"); 527 } 528 buffer.append(bar + "\n" + "Row count = " + row_count + "\n\n"); 529 resultString.append(buffer.toString()); 530 531 r.close(); 532 } 533 else 534 { 535 resultString.append("Number of affected rows = " + 536 s.getUpdateCount() + "\n\n"); 537 } 538 539 s.close(); 540 } 541 catch (SQLException ex) 542 { 543 resultString.append (ex.getMessage() + "\n\n"); 544 new YesNoDialog(this, "Error ! ", 545 "SQLException : " + ex.getMessage(), 546 " Dismiss ", null); 547 continue; 548 } 549 } 550 } 551 } 552 553 private void printOutput() 554 { 555 String text = resultString.getText(); 556 if (text.length() == 0) return; 557 558 Toolkit tk = getToolkit(); 559 PrintJob pj = tk.getPrintJob(SqlConsole.this, "Print SQL Output", 560 new Properties()); 561 if (pj != null) 562 { 563 Graphics g = pj.getGraphics(); 564 565 Font font = new Font(PRINT_FONT_NAME, 566 FONT_STYLE, 567 (int)(FONT_SIZE * FONT_PRINT_SCALE_FACTOR)); 568 FontMetrics fm = getFontMetrics(font); 569 int lineheight = fm.getHeight(); 570 int cwidth = fm.stringWidth(FONT_WIDTH_MEASUREMENT_STRING) / 571 FONT_WIDTH_MEASUREMENT_STRING.length(); 572 573 Dimension dim = pj.getPageDimension(); 574 int pagewidth = dim.width; 575 int pageheight = dim.height; 576 int num_char_line = (pagewidth - (2 * FONT_PRINT_INSET_X)) / cwidth; 577 578 g.setFont(font); 579 g.setColor(Color.black); 580 581 int line = 0; 582 583 StringTokenizer strtok = new StringTokenizer(text, "\n"); 585 int num_tokens = strtok.countTokens(); 586 for (int i = 0; i < num_tokens; i++) 587 { 588 String line_text = strtok.nextToken(); 589 int len = line_text.length(); 590 int num_lines = len / num_char_line; 591 if ((len % num_char_line) > 0) num_lines++; 592 593 int offset = 0; 594 for (int j = 0; j < num_lines; j++) 595 { 596 String submsg; 597 try 598 { 599 submsg = line_text.substring(offset, 600 offset+num_char_line); 601 } 602 catch (StringIndexOutOfBoundsException ex) 603 { 604 submsg = line_text.substring(offset); 605 } 606 607 offset+= num_char_line; 608 609 int ycoord = FONT_PRINT_INSET_Y + ((line+1)*lineheight); 610 if (ycoord >= pageheight - FONT_PRINT_INSET_Y) { 612 g.dispose(); 613 g = pj.getGraphics(); 614 g.setFont(font); 615 616 ycoord = FONT_PRINT_INSET_Y + lineheight; 617 line = 0; 618 } 619 620 g.drawString(submsg, FONT_PRINT_INSET_X, ycoord); 621 line++; 622 } } g.dispose(); 625 pj.end(); 626 } 627 } 628 629 private void saveOutput() 630 { 631 FileDialog fd = new FileDialog(SqlConsole.this, "Save SQL output to a file", 632 FileDialog.SAVE); 633 fd.show(); 634 String file_name = fd.getFile(); 635 if (file_name == null) 636 { 637 return; 639 } 640 641 File file = new File(fd.getDirectory(), file_name); 642 String path_name = file.getAbsolutePath(); 643 try 644 { 645 FileOutputStream fos = new FileOutputStream(path_name, true); 647 OutputStreamWriter osw = new OutputStreamWriter(fos); 648 649 String output = new String ("Output generated at " 650 + (new java.util.Date ()) 651 + " by user : " 652 + dbConn.getUser() 653 + " logged on to host : " 654 + dbConn.getHost() 655 + '\n' 656 + '\n' 657 + resultString.getText() 658 + '\n' 659 + '\n'); 660 osw.write(output, 0, output.length()); 661 osw.close(); 662 } 663 catch (IOException ex1) 664 { 665 new YesNoDialog(SqlConsole.this, "Error ! ", 666 "IO Exception : " + ex1.getMessage(), 667 " Dismiss ", null); 668 return; 669 } 670 } 671 672 673 private void importFile() 674 { 675 FileDialog fd = new FileDialog(SqlConsole.this, "Read from file", 676 FileDialog.LOAD); 677 fd.show(); 678 String file_name = fd.getFile(); 679 if (file_name == null) 680 { 681 return; 683 } 684 685 File file = new File(fd.getDirectory(), file_name); 686 try 687 { 688 FileReader freader = new FileReader(file); 689 690 StringBuffer buffer = new StringBuffer (); 691 int count = 0; 692 char[] read_buffer = new char[100]; 693 while(count >= 0) 694 { 695 count = freader.read(read_buffer); 696 if (count >= 0) 697 { 698 buffer.append(read_buffer, 0, count); 699 } 700 } 701 702 freader.close(); 703 704 commandString.setText(buffer.toString()); 706 707 processQuery(); 709 } 710 catch (IOException ex1) 711 { 712 new YesNoDialog(SqlConsole.this, "Error ! ", 713 "IO Exception : " + ex1.getMessage(), 714 " Dismiss ", null); 715 return; 716 } 717 } 718 719 private void addToContainer(Container cont, 720 GridBagLayout gbl, 721 GridBagConstraints gbc, 722 Component comp, 723 int gridx, 724 int gridy, 725 int gridwidth, 726 int gridheight, 727 int fill, 728 int anchor, 729 int weightx, 730 int weighty, 731 Insets insets) 732 { 733 gbc.gridx = gridx; 734 gbc.gridy = gridy; 735 gbc.gridwidth = gridwidth; 736 gbc.gridheight = gridheight; 737 gbc.fill = fill; 738 gbc.anchor = anchor; 739 gbc.weightx = weightx; 740 gbc.weighty = weighty; 741 742 if (insets != null) 743 { 744 gbc.insets = insets; 745 } 746 747 gbl.setConstraints(comp, gbc); 748 cont.add(comp); 749 } 750 751 private void addToContainer(Container cont, 752 GridBagLayout gbl, 753 GridBagConstraints gbc, 754 Component comp, 755 int gridx, 756 int gridy, 757 int gridwidth, 758 int gridheight, 759 int fill, 760 int anchor, 761 int weightx, 762 int weighty) 763 { 764 addToContainer(cont, gbl, gbc, comp, gridx, gridy, gridwidth, gridheight, 765 fill, anchor, weightx, weighty, null); 766 } 767 768 769 770 class LogoutListener implements ActionListener 771 { 772 public void actionPerformed(ActionEvent e) 773 { 774 logout(); 775 } 776 }; 777 778 class WindowCloseListener extends WindowAdapter 779 { 780 public void windowClosing(WindowEvent e) 781 { 782 close(); 783 } 784 }; 785 786 class ExitListener implements ActionListener 787 { 788 public void actionPerformed(ActionEvent e) 789 { 790 close(); 791 } 792 }; 793 794 class ResetListener implements ActionListener 795 { 796 public void actionPerformed(ActionEvent e) 797 { 798 clear(); 799 } 800 }; 801 802 class SelectListener implements ActionListener 803 { 804 public void actionPerformed(ActionEvent e) 805 { 806 resultString.selectAll(); 807 } 808 }; 809 810 class CopyListener implements ActionListener 811 { 812 public void actionPerformed(ActionEvent e) 813 { 814 String text = commandString.getSelectedText(); 815 if (text.length() == 0) { 817 text = resultString.getSelectedText(); 818 if (text.length() == 0) return; 819 else { 821 int cp = resultString.getCaretPosition(); 822 resultString.select(0, 0); 823 resultString.setCaretPosition(cp); 824 } 825 } 826 else { 828 int cp = commandString.getCaretPosition(); 829 commandString.select(0, 0); 830 commandString.setCaretPosition(cp); 831 } 832 833 TextClipBoard.Instance().copyToClipBoard(text); 834 } 835 }; 836 837 class PasteListener implements ActionListener 838 { 839 public void actionPerformed(ActionEvent e) 840 { 841 String text = TextClipBoard.Instance().getClipBoardContent(); 842 if (text.length() > 0) 843 { 844 commandString.insert(text, commandString.getCaretPosition()); 845 } 846 } 847 }; 848 849 class ImportListener implements ActionListener 850 { 851 public void actionPerformed(ActionEvent e) 852 { 853 importFile(); 854 } 855 }; 856 857 class SaveListener implements ActionListener 858 { 859 public void actionPerformed(ActionEvent e) 860 { 861 saveOutput(); 862 } 863 }; 864 865 class PrintListener implements ActionListener 866 { 867 public void actionPerformed(ActionEvent e) 868 { 869 printOutput(); 870 } 871 }; 872 873 class SubmitListener implements ActionListener 874 { 875 public void actionPerformed(ActionEvent e) 876 { 877 processQuery(); 878 } 879 }; 880 881 class SpecialKeyListener extends KeyAdapter 882 { 883 public void keyPressed(KeyEvent e) 884 { 885 int key = e.getKeyCode(); 886 Component parent = e.getComponent(); 887 888 if (key == KeyEvent.VK_END) 889 { 890 processQuery(); 891 } 892 } 893 }; 894 895 896 public static void main(String [] args) 897 { 898 String jdbc_driver = "com.mysql.jdbc.Driver"; 899 String db_name = "mysql"; 900 String file_name = null; 901 902 for (int i = 0; i < args.length; i++) 903 { 904 if (args[i].equals("-d") == true) 905 { 906 if (i == args.length - 1) { 908 System.out.println("No driver specified"); 909 System.exit(1); 910 } 911 912 i++; 913 jdbc_driver = args[i]; 914 continue; 915 } 916 else if (args[i].equals("-u") == true) 917 { 918 if (i == args.length - 1) { 920 System.out.println("No database type specified"); 921 System.exit(1); 922 } 923 924 i++; 925 db_name = args[i]; 926 continue; 927 } 928 else if (args[i].equals("-v") == true) 929 { 930 System.out.println("SQL Console Version " + VERSION); 931 System.exit(0); 932 } 933 else if (args[i].equals("-f") == true) 934 { 935 if (i == args.length - 1) { 937 System.out.println("No file specified"); 938 System.exit(1); 939 } 940 941 i++; 942 file_name = args[i]; 943 continue; 944 } 945 946 System.out.println("Unknown option " + args[i]); 947 System.exit(1); 948 } 949 950 try 951 { 952 SqlConsole console = new SqlConsole(jdbc_driver, db_name, file_name, true, false, true, ""); 953 } 954 catch (Exception ex) 955 { 956 System.out.println("Exception : " + ex.getMessage()); 957 System.exit(1); 958 } 959 } 960 } 961 | Popular Tags |