001: package com.pk;
002:
003: import javax.swing.JInternalFrame;
004: import javax.swing.*;
005:
006: import java.awt.event.*;
007:
008: import javax.swing.event.*;
009:
010: import java.awt.*;
011:
012: import javax.swing.table.*;
013: import javax.swing.text.Document;
014: import javax.swing.undo.CannotRedoException;
015: import javax.swing.undo.CannotUndoException;
016: import javax.swing.undo.UndoManager;
017:
018: import java.sql.*;
019: import java.text.MessageFormat;
020: import java.util.*;
021:
022: public class MyInternalFrame extends JInternalFrame implements
023: InternalFrameListener, Constants {
024:
025: /**
026: *
027: */
028: private static final long serialVersionUID = 9103843865329019956L;
029:
030: class ConnectionDialog extends JInternalFrame implements
031: FocusListener {
032:
033: /**
034: *
035: */
036: private static final long serialVersionUID = -5200934680040088833L;
037: protected boolean canceled;
038: public MyInternalFrame jif;
039: protected JTextField passwordField;
040: protected ConnectionInformation tmpConnectionInformation;
041: protected JComboBox urlField;
042:
043: protected JTextField useridField;
044:
045: public ConnectionDialog(MyInternalFrame f) {
046:
047: setTitle("Connect To A Database");
048: jif = f;
049: Toolkit dKit = getToolkit(); // Get the toolkit of window
050: Dimension wSize = dKit.getScreenSize(); // Get the size of window
051: setBounds(wSize.width / 2 - 200, wSize.height / 2 - 200, // location
052: wSize.width / 2, wSize.height / 2); // size
053: buildDialogLayout();
054: setSize(300, 200);
055: }
056:
057: protected boolean attemptConnection() {
058: try {
059: tmpConnectionInformation = new ConnectionInformation();
060: userid = useridField.getText();
061: ConnectionConfig tmpConnectionConfig = (ConnectionConfig) urlField
062: .getSelectedItem();
063: jif.setConnectionName(tmpConnectionConfig.getName());
064:
065: tmpConnectionInformation.setUrl(tmpConnectionConfig
066: .getUrl());
067: tmpConnectionInformation.setConnectionListKey(String
068: .valueOf(System.currentTimeMillis()));
069: tmpConnectionInformation.setPassword(passwordField
070: .getText());
071: tmpConnectionInformation.setUserID(useridField
072: .getText());
073: tmpConnectionInformation.setNumberOfWindows(1);
074: tmpConnectionInformation
075: .setDatabaseDialect(tmpConnectionConfig
076: .getDatabaseDialect());
077: setKeywords(tmpConnectionConfig.getDatabaseDialect()
078: .getKeywords());
079: connection = DriverManager.getConnection(
080: tmpConnectionInformation.getUrl(),
081: tmpConnectionInformation.getUserID(),
082: tmpConnectionInformation.getPassword());
083: connection.setAutoCommit(false);
084: return true;
085: } catch (Exception e) {
086: e.printStackTrace();
087: JOptionPane.showMessageDialog(this ,
088: "Error connecting to " + "database: "
089: + e.getMessage());
090: }
091: return false;
092: }
093:
094: protected void buildDialogLayout() {
095: JLabel label;
096: urlField = new JComboBox();
097: java.util.List connectionConfigs = jif.mainFrame
098: .getConfig().getConnections();
099: int size = connectionConfigs.size();
100: for (int x = 0; x < size; x++) {
101: urlField.addItem(connectionConfigs.get(x));
102: }
103: Container pane = getContentPane();
104: pane.setLayout(new GridBagLayout());
105: GridBagConstraints gbc = new GridBagConstraints();
106: gbc.anchor = GridBagConstraints.WEST;
107: gbc.insets = new Insets(6, 15, 6, 15);
108:
109: gbc.gridx = 0;
110: gbc.gridy = 0;
111: label = new JLabel("Userid:", JLabel.LEFT);
112: pane.add(label, gbc);
113:
114: gbc.gridy++;
115: label = new JLabel("Password:", JLabel.LEFT);
116: pane.add(label, gbc);
117:
118: gbc.gridy++;
119: label = new JLabel("Url:", JLabel.LEFT);
120: pane.add(label, gbc);
121:
122: gbc.gridy++;
123: //label = new JLabel("Oracle:", JLabel.LEFT);
124:
125: gbc.gridx = 1;
126: gbc.gridy = 0;
127:
128: useridField = new JTextField(10);
129: pane.add(useridField, gbc);
130:
131: gbc.gridy++;
132: passwordField = new JPasswordField(10);
133: pane.add(passwordField, gbc);
134:
135: gbc.gridy++;
136: //urlField = new JTextField("",15);
137:
138: pane.add(urlField, gbc);
139:
140: gbc.gridx = 0;
141: gbc.gridy = 4;
142: gbc.gridwidth = GridBagConstraints.REMAINDER;
143: gbc.anchor = GridBagConstraints.CENTER;
144: pane.add(getButtonPanel(), gbc);
145: }
146:
147: public void focusGained(FocusEvent e) {
148: }
149:
150: public void focusLost(FocusEvent e) {
151: }
152:
153: protected JPanel getButtonPanel() {
154: JPanel panel = new JPanel();
155: JButton btn1 = new JButton("Ok");
156: getRootPane().setDefaultButton(btn1);
157: btn1.addActionListener(new ActionListener() {
158: public void actionPerformed(ActionEvent event) {
159: onDialogOk();
160: }
161: });
162: panel.add(btn1);
163: JButton btn2 = new JButton("Cancel");
164: btn2.addActionListener(new ActionListener() {
165: public void actionPerformed(ActionEvent event) {
166: onDialogCancel();
167: }
168: });
169: panel.add(btn2);
170: return panel;
171: }
172:
173: public Connection getConnection() {
174: setVisible(true);
175: return connection;
176: }
177:
178: protected void onDialogCancel() {
179: if (openFrameCount <= 1) {
180: System.exit(0);
181: } else {
182: setVisible(false);
183: jif.getDesktopPane().remove(this );
184: }
185: }
186:
187: protected void onDialogOk() {
188:
189: if (attemptConnection()) {
190: setVisible(false);
191:
192: try {
193: statement = connection.createStatement();
194: }
195:
196: catch (SQLException sqle) {
197: JOptionPane
198: .showMessageDialog(this , "Oops! " + sqle);
199: System.exit(0);
200: }
201:
202: jif.setTitle(userid.toUpperCase());
203:
204: statusBar.setUserPane(jif.getConnectionName());
205:
206: jif.setConncetionKey(tmpConnectionInformation
207: .getConnectionListKey());
208:
209: mainFrame.getConnectionList()
210: .put(
211: tmpConnectionInformation
212: .getConnectionListKey(),
213: tmpConnectionInformation);
214:
215: jif.setPreferredSize(new java.awt.Dimension(700, 500));
216: jif.pack();
217: jif.setVisible(true);
218: jif.getDesktopPane().remove(this );
219: jif.sqlTextArea.requestFocus();
220: }
221: }
222:
223: }
224:
225: class ListenerScrollBar implements AdjustmentListener {
226: public void adjustmentValueChanged(AdjustmentEvent e) {
227: if (jsb.getMaximum() != 0) {
228: System.out.println(String.valueOf(jsb.getMaximum()));
229: if ((jsb.getMaximum() - jsb.getVisibleAmount()) <= e
230: .getValue())
231: // if ((jsb.getMaximum() - 300) <= e.getValue())
232: {
233: model.setNextResultSet(table);
234:
235: setMyTableWidth();
236:
237: try {
238: if (model.gResults.getRow() == 0
239: && table.getBackground() != Color.black) {
240: statusBar.messagePane.setVisible(true);
241: statusBar
242: .setMessagePane(model.totalRowCount
243: + " row(s) selected.");
244: }
245: } catch (SQLException sqle) {
246: System.err.println(sqle);
247: }
248: }
249: }
250: }
251: }
252:
253: static int openFrameCount = 0;
254: static final int xOffset = 30, yOffset = 30;
255: //Connection connect;
256:
257: private int frameIndex = -1;
258: ConnectionDialog argConnectionDialog;
259: int commentFlag;
260: String conncetionKey = null;
261:
262: Connection connection;
263: private String connectionName;
264: //String dbUrl;
265: int index_of_sqls = 0;
266: int indexBrowseFlag = 0;
267:
268: JPanel jPanel1 = new JPanel();
269: JScrollBar jsb;
270: int local_index_of_sqls = 0;
271: PrettyKid mainFrame;
272: ResultsModel model = new ResultsModel();
273:
274: String newWinUrl;
275: int packageBrowseFlag = 0;
276: JTextArea planArea = new JTextArea();
277: int procedureBrowseFlag = 0;
278:
279: String queryWithComment;
280: JTabbedPane resultTabbedPane = new JTabbedPane();
281:
282: java.util.List sqls = new ArrayList();
283:
284: JTextPane sqlTextArea = new JTextPane();
285: Statement statement;
286:
287: StatusBar statusBar = new StatusBar();
288: JTable table = new JTable(model);
289:
290: int tableBrowseFlag = 0;
291:
292: String userid;
293: final UndoManager undo = new UndoManager();
294:
295: public MyInternalFrame(PrettyKid argMainFrame) {
296: super ("Document #" + (++openFrameCount), true, true, true, true);
297:
298: mainFrame = argMainFrame;
299:
300: argConnectionDialog = new ConnectionDialog(this );
301: connection = argConnectionDialog.getConnection();
302:
303: argConnectionDialog.setLocation(250, 100);
304: argMainFrame.desktop.add(argConnectionDialog);
305: try {
306: argConnectionDialog.setSelected(true);
307: } catch (java.beans.PropertyVetoException e) {
308: }
309: init(argMainFrame, "", "");
310:
311: }
312:
313: public MyInternalFrame(PrettyKid jf, Connection con, String user,
314: String url) {
315: super ("Document #" + (++openFrameCount), true, true, true, true);
316:
317: init(jf, user, url);
318: this .connection = con;
319: try {
320: statement = connection.createStatement();
321: } catch (SQLException sqle) {
322: System.err.println(sqle); // error connection to database
323: JOptionPane.showMessageDialog(this ,
324: "Can not create statement : " + sqle);
325: }
326:
327: pack();
328: setVisible(true);
329: }
330:
331: private void init(PrettyKid mainFrame, String user, String url) {
332: this .mainFrame = mainFrame;
333: this .userid = user;
334: this .newWinUrl = url;
335: setConnectionName(url);
336:
337: sqlTextArea.setFont(new Font("Courier", Font.BOLD, 12));
338:
339: CodeDocument doc = new CodeDocument();
340:
341: //undo function
342: initUndo(doc);
343: sqlTextArea.setDocument(doc);
344:
345: JScrollPane scrollPane = new JScrollPane();
346: scrollPane.getViewport().add(sqlTextArea, null);
347:
348: table
349: .setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
350: table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // Use scrollbars
351:
352: JScrollPane resultsPane = new JScrollPane(table,
353: JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
354: JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); // Create scrollpane for table
355:
356: jsb = resultsPane.getVerticalScrollBar();
357:
358: planArea.setEditable(false);
359: planArea.setFont(new Font("Default", Font.BOLD, 12));
360: JScrollPane planScrollPane = new JScrollPane(planArea,
361: JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
362: JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
363:
364: resultTabbedPane.addTab("ResultSet", resultsPane);
365: resultTabbedPane.addTab("Query plan", planScrollPane);
366:
367: BorderLayout bdLayout = new BorderLayout();
368: jPanel1.setLayout(bdLayout);
369: getContentPane().add(jPanel1, BorderLayout.CENTER);
370:
371: JSplitPane splitPane = new JSplitPane(
372: JSplitPane.VERTICAL_SPLIT, true, scrollPane,
373: resultTabbedPane);
374: jPanel1.add(splitPane, BorderLayout.CENTER);
375: splitPane.setDividerLocation(150);
376: getContentPane().add(splitPane, BorderLayout.CENTER);
377: getContentPane().add(statusBar, BorderLayout.SOUTH);
378:
379: addInternalFrameListener(this );
380: addComponentListener(new ComponentAdapter() {
381: public void componentResized(ComponentEvent e) {
382: }
383: });
384: jsb.addAdjustmentListener(new ListenerScrollBar());
385:
386: setLocation(xOffset * openFrameCount, yOffset * openFrameCount);
387:
388: statusBar.elapsedTimePane.setVisible(false);
389: statusBar.messagePane.setVisible(false);
390:
391: setPreferredSize(new java.awt.Dimension(600, 450));
392:
393: setTitle(userid.toUpperCase());
394:
395: statusBar.setUserPane(newWinUrl);
396:
397: }
398:
399: /**
400: * @param doc
401: */
402: private void initUndo(CodeDocument doc) {
403: doc.addUndoableEditListener(new UndoableEditListener() {
404: public void undoableEditHappened(UndoableEditEvent evt) {
405: undo.addEdit(evt.getEdit());
406: }
407: });
408:
409: sqlTextArea.getActionMap().put("Undo",
410: new AbstractAction("Undo") {
411: /**
412: *
413: */
414: private static final long serialVersionUID = 4956600639019775601L;
415:
416: public void actionPerformed(ActionEvent evt) {
417: try {
418: if (undo.canUndo()) {
419: undo.undo();
420: }
421: } catch (CannotUndoException e) {
422: }
423: }
424: });
425:
426: sqlTextArea.getInputMap().put(
427: KeyStroke.getKeyStroke("control Z"), "Undo");
428:
429: sqlTextArea.getActionMap().put("Redo",
430: new AbstractAction("Redo") {
431: /**
432: *
433: */
434: private static final long serialVersionUID = 237382599844729867L;
435:
436: public void actionPerformed(ActionEvent evt) {
437: try {
438: if (undo.canRedo()) {
439: undo.redo();
440: }
441: } catch (CannotRedoException e) {
442: }
443: }
444: });
445:
446: sqlTextArea.getInputMap().put(
447: KeyStroke.getKeyStroke("control Y"), "Redo");
448:
449: }
450:
451: public String commentHandling(String query) {
452: query = query.trim();
453: int cmtAstStart = query.indexOf("/*");
454: int cmtDasStart = query.indexOf("--");
455:
456: if (cmtAstStart == 0) {
457: int cmtEnd = query.indexOf("*/");
458: StringBuffer queryStrBuffer = new StringBuffer(query);
459: queryStrBuffer = queryStrBuffer.delete(cmtAstStart,
460: cmtEnd + 2);
461: query = queryStrBuffer.toString();
462: }
463:
464: if (cmtDasStart == 0) {
465: int cmtEnd = query.indexOf("\n", cmtDasStart);
466:
467: StringBuffer queryStrBuffer = new StringBuffer(query);
468: queryStrBuffer = queryStrBuffer.delete(cmtDasStart,
469: cmtEnd - 1);
470: query = queryStrBuffer.toString();
471: }
472: return query;
473: }
474:
475: public void commitTransaction() {
476: //make sure that this connection is used with only one window.
477: //If it has more than one window ask user to confirm commit.
478:
479: try {
480: if (connection.getAutoCommit()) {
481: JOptionPane
482: .showMessageDialog(this ,
483: "This connection is in auto-commit mode and cannot be committed manually.");
484: return;
485: }
486:
487: ConnectionInformation tmpConnectionInformation = (ConnectionInformation) mainFrame
488: .getConnectionList().get(conncetionKey);
489: if (tmpConnectionInformation.getNumberOfWindows() > 1) {
490: int answer = JOptionPane
491: .showConfirmDialog(
492: this ,
493: "This connection is being used by more than one window. \nAre you sure that you want to commit?",
494: "Warning", JOptionPane.YES_NO_OPTION,
495: JOptionPane.WARNING_MESSAGE);
496: if (answer == JOptionPane.NO_OPTION) {
497: return;
498: }
499: }
500:
501: connection.commit();
502: JOptionPane
503: .showMessageDialog(this , "Transaction committed");
504: } catch (SQLException ex) {
505: JOptionPane.showMessageDialog(this , ex.getMessage());
506: }
507:
508: }
509:
510: public void executeDescSQL(String argQuery) {
511:
512: ConnectionInformation tmpConnectionInformation = getConnectionInformation();
513: String queryDesc = tmpConnectionInformation
514: .getDatabaseDialect().getDescribeSQLString(argQuery,
515: tmpConnectionInformation);
516: if (queryDesc == null || queryDesc.equals("")) {
517: //if this dialect does not support this feature must report to user and exit method.
518: featureNotAvailable("Describe feature",
519: tmpConnectionInformation.getDatabaseDialect()
520: .getClass().getName(), this );
521: return;
522: }
523: doHistory(argQuery);
524:
525: if (queryDesc == null) // If there's nothing we are done
526: return;
527: int color = 0;
528: try {
529: if (table.getBackground() == Color.black)
530: color = 1;
531: table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // Use scrollbars
532: table.setForeground(Color.black);
533: table.setBackground(Color.white);
534: table.setFont(new Font("Default", Font.BOLD, 12));
535: table.setShowGrid(true);
536: long startTime = System.currentTimeMillis();
537: model.setResultSet(statement.executeQuery(queryDesc));
538: float qTime = System.currentTimeMillis() - startTime;
539: qTime = qTime / 1000;
540:
541: setMyTableWidth();
542:
543: statusBar.elapsedTimePane.setVisible(true);
544: statusBar.messagePane.setVisible(true);
545: statusBar.setElapsedTimePane(qTime + " Sec.");
546: statusBar.setMessagePane(model.getRowCount()
547: + " row(s) selected.");
548: } catch (SQLException sqle) {
549: JOptionPane.showMessageDialog(this , sqle.getMessage());
550: statusBar.messagePane.setVisible(true);
551: statusBar.setMessagePane(sqle.getMessage()); // Display error message
552: if (color == 1) {
553: table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
554: DefaultTableColumnModel tcm = (DefaultTableColumnModel) table
555: .getColumnModel();
556: TableColumn tc = tcm.getColumn(0);
557: table.setShowGrid(false);
558: tc.setWidth(600);
559: table.setForeground(Color.white);
560: table.setBackground(Color.black);
561: table.setFont(new Font("Default", Font.BOLD, 12));
562: tc.setResizable(true);
563: }
564: }
565: }
566:
567: public void executePlanSQL() {
568:
569: String planOut = "";
570:
571: try {
572: ConnectionInformation tmpConnectionInformation = getConnectionInformation();
573: planOut = tmpConnectionInformation.getDatabaseDialect()
574: .doExecutePlan(sqlTextArea.getText(),
575: tmpConnectionInformation, connection);
576: if (planOut == null || planOut.equals("")) {
577: //if this dialect does not support this feature must report to user and exit method.
578: featureNotAvailable("Execution Plan",
579: tmpConnectionInformation.getDatabaseDialect()
580: .getClass().getName(), this );
581: return;
582: }
583:
584: planArea.setText(planOut);
585:
586: resultTabbedPane.setSelectedIndex(1);
587: } catch (SQLException sqle) {
588: JOptionPane.showMessageDialog(this , sqle.getMessage());
589: sqle.printStackTrace();
590: statusBar.messagePane.setVisible(true);
591: statusBar.setMessagePane(sqle.getMessage()); // Display error message
592: }
593: }
594:
595: /**
596: *
597: */
598:
599: public void executeSQL(String query) {
600:
601: resultTabbedPane.setSelectedIndex(0);
602:
603: doHistory(query);
604: query = commentHandling(query);
605:
606: if (query == null) // If there's nothing we are done
607: return;
608: int color = 0;
609: try {
610: if (table.getBackground() == Color.black)
611: color = 1;
612: table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // Use scrollbars
613: table.setForeground(Color.black);
614: table.setBackground(Color.white);
615: table.setFont(new Font("Default", Font.BOLD, 12));
616: table.setShowGrid(true);
617: //table.set
618:
619: sqlTextArea.setCursor(Cursor
620: .getPredefinedCursor(Cursor.WAIT_CURSOR));
621: this .setCursor(Cursor
622: .getPredefinedCursor(Cursor.WAIT_CURSOR));
623: long startTime = System.currentTimeMillis();
624: model.setResultSet(statement.executeQuery(query));
625: float qTime = System.currentTimeMillis() - startTime;
626: this .setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
627: sqlTextArea.setCursor(Cursor
628: .getPredefinedCursor(Cursor.TEXT_CURSOR));
629:
630: setMyTableWidth();
631:
632: qTime = qTime / 1000;
633: statusBar.elapsedTimePane.setVisible(true);
634: statusBar.setElapsedTimePane(qTime + " Sec.");
635: if (model.totalRowCount < 100) {
636: statusBar.messagePane.setVisible(true);
637: statusBar.setMessagePane(model.getRowCount()
638: + " row(s) selected.");
639: } else {
640: statusBar.messagePane.setVisible(false);
641: }
642: } catch (SQLException sqle) {
643: JOptionPane.showMessageDialog(this , sqle.getMessage());
644: statusBar.messagePane.setVisible(true);
645: statusBar.setMessagePane(sqle.getMessage()); // Display error message
646: this .setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
647: sqlTextArea.setCursor(Cursor
648: .getPredefinedCursor(Cursor.TEXT_CURSOR));
649: if (color == 1) {
650: table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
651: DefaultTableColumnModel tcm = (DefaultTableColumnModel) table
652: .getColumnModel();
653: TableColumn tc = tcm.getColumn(0);
654: table.setShowGrid(false);
655: table.setCellSelectionEnabled(true);
656: tc.setWidth(600);
657: table.setForeground(Color.white);
658: table.setBackground(Color.black);
659: table.setFont(new Font("Default", Font.BOLD, 12));
660: tc.setResizable(true);
661: }
662: }
663: }
664:
665: /**
666: * @return
667: */
668: public String getConncetionKey() {
669: return conncetionKey;
670: }
671:
672: /**
673: * @return
674: */
675: public String getConnectionName() {
676: return connectionName;
677: }
678:
679: /**
680: * @return
681: */
682: public java.util.List getSqls() {
683: return sqls;
684: }
685:
686: public void internalFrameActivated(InternalFrameEvent e) {
687: sqlTextArea.requestFocus();
688: }
689:
690: public void internalFrameClosed(InternalFrameEvent e) {
691: ConnectionInformation tmpConnectionInformation = (ConnectionInformation) mainFrame
692: .getConnectionList().get(conncetionKey);
693:
694: if (tmpConnectionInformation.getNumberOfWindows() == 1) {
695: try {
696: if (connection != null) {
697: connection.close();
698: }
699: } catch (SQLException e1) {
700: e1.printStackTrace();
701: }
702: } else {
703: tmpConnectionInformation
704: .setNumberOfWindows(tmpConnectionInformation
705: .getNumberOfWindows() - 1);
706: mainFrame.getConnectionList().put(conncetionKey,
707: tmpConnectionInformation);
708: }
709: openFrameCount--;
710: }
711:
712: public void internalFrameClosing(InternalFrameEvent e) {
713: mainFrame.getMyInternalFrameList().remove(this );
714: mainFrame.createWindowMenu();
715: }
716:
717: public void internalFrameDeactivated(InternalFrameEvent e) {
718: }
719:
720: public void internalFrameDeiconified(InternalFrameEvent e) {
721: }
722:
723: public void internalFrameIconified(InternalFrameEvent e) {
724: }
725:
726: public void internalFrameOpened(InternalFrameEvent e) {
727: mainFrame.getMyInternalFrameList().add(this );
728: mainFrame.createWindowMenu();
729: sqlTextArea.transferFocus();
730: }
731:
732: public void prexecuteSQL() {
733: DatabaseDialect tmpDatabaseDialect = getConnectionInformation()
734: .getDatabaseDialect();
735:
736: String query = sqlTextArea.getSelectedText();
737: if (query == null || query.length() <= 0) {
738: query = sqlTextArea.getText();
739: }
740:
741: query = commentHandling(query);
742:
743: query = query.trim();
744:
745: if (tmpDatabaseDialect.isSelectStatement(query)) {
746: executeSQL(query);
747: } else if (tmpDatabaseDialect.isDescribeStatement(query)) {
748: executeDescSQL(query);
749: } else if (query.equalsIgnoreCase("COMMIT")) {
750: commitTransaction();
751: } else if (query.equalsIgnoreCase("ROLLBACK")) {
752: rollBackTransaction();
753: } else {
754: updateSQL(query);
755: }
756: }
757:
758: public void rollBackTransaction() {
759: //make sure that this connection is used with only one window.
760: //If it has more than one window ask user to confirm rollback.
761:
762: try {
763: if (connection.getAutoCommit()) {
764: JOptionPane
765: .showMessageDialog(this ,
766: "This connection is in auto-commit mode and cannot be rolled back.");
767: return;
768: }
769:
770: ConnectionInformation tmpConnectionInformation = (ConnectionInformation) mainFrame
771: .getConnectionList().get(conncetionKey);
772: if (tmpConnectionInformation.getNumberOfWindows() > 1) {
773: int answer = JOptionPane
774: .showConfirmDialog(
775: this ,
776: "This connection is being used by more than one window. \nAre you sure that you want to rollback?",
777: "Warning", JOptionPane.YES_NO_OPTION,
778: JOptionPane.WARNING_MESSAGE);
779: if (answer == JOptionPane.NO_OPTION) {
780: return;
781: }
782: }
783:
784: connection.rollback();
785: JOptionPane.showMessageDialog(this ,
786: "Transaction Rolled back", "Information",
787: JOptionPane.INFORMATION_MESSAGE);
788: } catch (SQLException ex) {
789: JOptionPane.showMessageDialog(this , ex.getMessage());
790: }
791:
792: }
793:
794: /**
795: * @param string
796: */
797: public void setConncetionKey(String string) {
798: conncetionKey = string;
799: }
800:
801: /**
802: * @param string
803: */
804: public void setConnectionName(String string) {
805: connectionName = string;
806: }
807:
808: public void setMyTableWidth() {
809: int tableWidth = 0;
810: FontMetrics metrics = table.getFontMetrics(table.getFont());
811: for (int i = 0; i < table.getColumnCount(); ++i) {
812: int width = 0;
813: int maxWidth = 0;
814: Vector data = new Vector();
815: data.addElement(table.getColumnName(i));
816: for (int j = 0; j < table.getRowCount(); ++j) {
817: if (table.getValueAt(j, i) == null) {
818: data.addElement(" ");
819: } else {
820: data.addElement(table.getValueAt(j, i).toString());
821: }
822: }
823: Enumeration enumeration = data.elements();
824: while (enumeration.hasMoreElements()) {
825: if ((width = metrics.stringWidth((String) enumeration
826: .nextElement())) > maxWidth) {
827: maxWidth = width + 30;
828: }
829: }
830: Insets insets = ((JComponent) table.getCellRenderer(0, i))
831: .getInsets();
832: maxWidth += insets.left + insets.right;
833: table.getColumnModel().getColumn(i).setPreferredWidth(
834: maxWidth);
835: tableWidth += maxWidth;
836: }
837: Dimension d = table.getSize();
838: d.width = tableWidth;
839: table.setSize(d);
840: table.setCellSelectionEnabled(true);
841:
842: }
843:
844: public void setSqlTextArea(String s) {
845: sqlTextArea.setText(s);
846: }
847:
848: public void updateSQL(String query) {
849:
850: int rowsHandled;
851:
852: doHistory(query);
853:
854: if (query == null) // If there's nothing we are done
855: return;
856: try {
857:
858: long startTime = System.currentTimeMillis();
859: rowsHandled = statement.executeUpdate(query);
860: model.setResultSet(null);
861: float qTime = System.currentTimeMillis() - startTime;
862: qTime = qTime / 1000;
863: query = query.trim();
864:
865: statusBar.elapsedTimePane.setVisible(true);
866: statusBar.messagePane.setVisible(true);
867:
868: if (query.toUpperCase().startsWith("INSERT")) {
869: statusBar.setElapsedTimePane(qTime + " Sec.");
870: statusBar.setMessagePane(rowsHandled
871: + " row(s) inserted.");
872: } else if (query.toUpperCase().startsWith("UPDATE")) {
873: statusBar.setElapsedTimePane(qTime + " Sec.");
874: statusBar.setMessagePane(rowsHandled
875: + " row(s) updated.");
876: } else if (query.toUpperCase().startsWith("DELETE")) {
877: statusBar.setElapsedTimePane(qTime + " Sec.");
878: statusBar.setMessagePane(rowsHandled
879: + " row(s) deleted.");
880: } else {
881: statusBar.setElapsedTimePane(qTime + " Sec.");
882: statusBar.setMessagePane("Executed successfully ");
883: }
884: } catch (SQLException sqle) {
885: JOptionPane.showMessageDialog(this , sqle.getMessage());
886: statusBar.messagePane.setVisible(true);
887: statusBar.setMessagePane(sqle.getMessage()); // Display error message
888: }
889: }
890:
891: public ConnectionInformation getConnectionInformation() {
892: return (ConnectionInformation) mainFrame.getConnectionList()
893: .get(conncetionKey);
894: }
895:
896: public void setKeywords(Vector argKeywords) {
897: Document tmpDocument = sqlTextArea.getDocument();
898: if (tmpDocument != null && tmpDocument instanceof CodeDocument) {
899: ((CodeDocument) tmpDocument).setKeywords(argKeywords);
900: }
901: }
902:
903: public void featureNotAvailable(String argfeatureName,
904: String argDialect, Component argComponent) {
905: Object tmp[] = { argfeatureName, argDialect };
906: String msg = MessageFormat
907: .format(
908: "The {0} feature is not available for database dialect {1}.",
909: tmp);
910: JOptionPane.showMessageDialog(argComponent, msg,
911: "Feature Not Available",
912: JOptionPane.INFORMATION_MESSAGE);
913: }
914:
915: public void undoLastEdit() {
916: try {
917: if (undo.canUndo()) {
918: undo.undo();
919: }
920: } catch (CannotUndoException e) {
921: }
922: }
923:
924: public void redoLastEdit() {
925: try {
926: if (undo.canRedo()) {
927: undo.redo();
928: }
929: } catch (CannotRedoException e) {
930: }
931: }
932:
933: /**
934: * @return Returns the frameIndex.
935: */
936: public int getFrameIndex() {
937: return frameIndex;
938: }
939:
940: /**
941: * @param frameIndex The frameIndex to set.
942: */
943: public void setFrameIndex(int frameIndex) {
944: this .frameIndex = frameIndex;
945: }
946:
947: private void doHistory(String argQuery) {
948: //Check to see if this is the first sql run.
949: if (index_of_sqls != 0) {
950: int historyMode = mainFrame.getConfig().getHistoryMode();
951: if (historyMode == Config.HISTORY_MODE_UNIQUE) {
952: //See if this query is already in the history
953: int size = sqls.size();
954: for (int x = 0; x < size; x++) {
955: if (((String) sqls.get(x)).equals(argQuery)) {
956: //if already in history do not add it again.
957: return;
958: }
959:
960: }
961: } else if (historyMode == Config.HISTORY_MODE_DIFF_FROM_LAST) {
962: if (((String) sqls.get(index_of_sqls - 1))
963: .equals(argQuery)) {
964: return;
965: }
966: }
967: }
968: if (this .index_of_sqls == 29) {
969: sqls.remove(0);
970: sqls.add((index_of_sqls - 1), argQuery);
971: } else {
972: sqls.add(index_of_sqls, argQuery);
973: this .index_of_sqls++;
974: }
975: this .local_index_of_sqls = this .index_of_sqls - 1;
976: }
977: }
|