001: package com.pk;
002:
003: import javax.swing.*;
004: import javax.swing.event.*;
005: import java.awt.*;
006: import java.awt.event.*;
007: import javax.swing.border.*;
008: import javax.swing.tree.*; //import javax.swing.table.*;
009: import java.sql.*;
010:
011: class TableBrowse extends JFrame implements ActionListener,
012: TreeSelectionListener {
013:
014: /**
015: *
016: */
017: private static final long serialVersionUID = -974168039259650580L;
018:
019: public TableBrowse(MyInternalFrame mif, Connection connection,
020: String userID) {
021: super ("Table Browser");
022:
023: this .mif = mif;
024: this .connection = connection;
025: this .userID = userID;
026:
027: setBounds(0, 0, 400, 400);
028: setDefaultCloseOperation(DISPOSE_ON_CLOSE);
029: addWindowListener(new WindowHandler());
030:
031: // Add message area
032: status.setText("Enter a database URL and/or press Enter");
033: status.setEditable(false); // No user input
034: status.setLineWrap(true); // Lines wrap
035: status.setWrapStyleWord(true); // on word boundaries
036: status.setBorder(BorderFactory
037: .createBevelBorder(BevelBorder.LOWERED));
038: getContentPane().add(status, BorderLayout.SOUTH);
039:
040: // Create tree to go in left split pane
041: dbNode = new DefaultMutableTreeNode("No database");
042: dbTreeModel = new DefaultTreeModel(dbNode);
043: dbTree = new JTree(dbTreeModel);
044: treePane = new JScrollPane(dbTree);
045: treePane.setBorder(BorderFactory
046: .createLineBorder(Color.darkGray));
047:
048: // Create table to go in right split pane
049: tableModel = new ResultsModel();
050: JTable table = new JTable(tableModel);
051: //table.setPreferredSize(new Dimension(800,800)); // Table sizing...
052: table
053: .setPreferredScrollableViewportSize(new Dimension(500,
054: 70));
055: table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
056: tablePane = new JScrollPane(table);
057: tablePane
058: .setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
059: tablePane.setBorder(BorderFactory
060: .createLineBorder(Color.darkGray));
061:
062: JSplitPane splitpane = new JSplitPane(
063: JSplitPane.HORIZONTAL_SPLIT, true, // Continuous relayout
064: treePane, // Left pane content
065: tablePane); // Right pane content
066: getContentPane().add(splitpane, BorderLayout.CENTER);
067: splitpane.setDividerLocation(150); // Left pane 150 pixels wide
068:
069: // Add event listeners
070: database.addActionListener(this );
071: userIDInput.addActionListener(this );
072: passwordInput.addActionListener(this );
073: dbTree.addTreeSelectionListener(this );
074:
075: pack();
076:
077: setVisible(true); // Set window visible
078: show(); // Display the window
079: }
080:
081: private String userID = null;
082: private String password = null;
083: private String url = null;
084:
085: MyInternalFrame mif;
086: Connection connection;
087: Statement statement;
088:
089: private JTextField database = new JTextField(url);
090: private JTextField userIDInput = new JTextField(userID);
091: private JPasswordField passwordInput = new JPasswordField(password);
092: private JTextArea status = new JTextArea(3, 30);
093:
094: private DefaultMutableTreeNode dbNode; // Root node for the database tree
095: private DefaultTreeModel dbTreeModel; // Model for the database metadata
096: private JTree dbTree; // Tree to display the metadata
097: private JScrollPane treePane; // Scroll pane holding the tree
098:
099: ResultsModel tableModel; // Model for table
100:
101: JScrollPane tablePane; // Scroll pane holding the table
102:
103: // private String[] drivers = { // Oracle driver
104: // "sun.jdbc.odbc.JdbcOdbcDriver", // ODBC bridge
105: // "com.imaginary.sql.msql.MsqlDriver" // mSQL driver
106: // };
107:
108: public void actionPerformed(ActionEvent e) {
109: Object source = e.getSource(); // Get source of the event
110: if (source == database || // If its URL input,
111: source == userIDInput || // or userID input,
112: source == passwordInput) // or password input,
113: { // we will try for a connection
114: url = database.getText(); // Get database URL
115: userID = userIDInput.getText(); // Get user ID
116:
117: char[] pw = passwordInput.getPassword(); // Get password
118: if (pw != null)
119: password = new String(pw);
120:
121: if (url == null || url.length() == 0) {
122: status.setText("Please specify a database URL ");
123: return;
124: }
125: openConnection();
126: password = null; // For security
127: }
128: }
129:
130: public void openConnection() {
131: try {
132: status.setText("Database connection established");
133:
134: statement = connection.createStatement(); // Create statement for query
135:
136: dbNode = new DefaultMutableTreeNode(url); // Root node is URL
137: dbTreeModel.setRoot(dbNode); // Set root in model
138: setupTree(connection.getMetaData()); // Set up tree with metadata
139:
140: treePane.setBorder(BorderFactory.createTitledBorder(
141: BorderFactory.createLineBorder(Color.darkGray),
142: //url,
143: userID.toUpperCase(), TitledBorder.CENTER,
144: TitledBorder.DEFAULT_POSITION));
145: dbTree.setRootVisible(false); // Now show the root node
146: dbTreeModel.reload(); // Get the tree redisplayed
147:
148: } catch (SQLException sqle) {
149: status.setText(sqle.getMessage()); // Display first message
150: do // loop through exceptions
151: {
152: System.err.println("Exception occurred:\nMessage: "
153: + sqle.getMessage());
154: System.err.println("SQL state: " + sqle.getSQLState());
155: System.err.println("Vendor code: "
156: + sqle.getErrorCode() + "\n----------------");
157: } while ((sqle = sqle.getNextException()) != null);
158: }
159: }
160:
161: private void setupTree(DatabaseMetaData metadata)
162: throws SQLException {
163: String[] tableTypes = { "TABLE" }; // We want only tables
164:
165: String catalog = connection.getCatalog();
166: ResultSet tables = metadata.getTables(// Get the tables info
167: catalog, userID.toUpperCase(), null, tableTypes);
168:
169: String tableName; // Stores a table name
170: DefaultMutableTreeNode tableNode; // Stores a tree node for a table
171: while (tables.next()) // For each table
172: {
173: tableName = tables.getString(3); // get the table name
174: tableNode = new DefaultMutableTreeNode(tableName);
175: dbNode.add(tableNode); // Add the node to the tree
176: }
177: }
178:
179: public void valueChanged(TreeSelectionEvent e) {
180: TreePath[] paths = dbTree.getSelectionPaths();
181: if (paths == null)
182: return;
183:
184: boolean tableSelected = false; // Set true if a table is selected
185: String column; // Stores a column name from a path
186: String table; // Stores a table name from a path
187: String columnsParam = null; // Column names in SQL SELECT
188: String tableParam = null; // Table name in SQL SELECT
189: String message = null; // Message for status area
190: for (int j = 0; j < paths.length; j++) {
191: switch (paths[j].getPathCount()) {
192: case 2: // We have a table selected
193: tableParam = (String) (((DefaultMutableTreeNode) (paths[j]
194: .getPathComponent(1))).getUserObject());
195: columnsParam = "*"; // Select all columns
196: tableSelected = true; // Set flag for a table selected
197: message = "Complete " + tableParam + " table displayed";
198: break;
199:
200: case 3: // Column selected
201: table = (String) (((DefaultMutableTreeNode) (paths[j]
202: .getPathComponent(1))).getUserObject());
203: if (tableParam == null)
204: tableParam = table;
205:
206: else if (tableParam != table)
207: break;
208: column = (String) (((DefaultMutableTreeNode) (paths[j]
209: .getPathComponent(2))).getUserObject());
210: if (columnsParam == null) // If no previous columns
211: columnsParam = column; // add the column
212: else
213: // otherwise
214: columnsParam += "," + column; // we need a comma too
215: message = columnsParam + " displayed from "
216: + tableParam + " table.";
217: break;
218: }
219: if (tableSelected) // If a table was selected
220: break; // we are done
221: }
222: try {
223: ConnectionInformation tmpConnectionInformation = mif
224: .getConnectionInformation();
225: //tableModel.setResultSet(statement.executeQuery("SELECT COLUMN_NAME, DECODE(NULLABLE,'N', 'NOT NULL', 'Y', NULL) AS NULLABLE, " + "DATA_TYPE, DECODE(DATA_TYPE, 'VARCHAR2', TO_CHAR(DATA_LENGTH), 'NUMBER', " + "DECODE(DATA_SCALE,0,TO_CHAR(DATA_PRECISION),NULL,NULL,DATA_PRECISION||','||DATA_SCALE)) AS \"SIZE\" " + "FROM USER_TAB_COLUMNS " + "WHERE TABLE_NAME = '" + tableParam + "'" + " ORDER BY COLUMN_ID"));
226: tableModel.setResultSet(statement
227: .executeQuery(tmpConnectionInformation
228: .getDatabaseDialect()
229: .getTableInfoSQLString(tableParam,
230: tmpConnectionInformation)));
231: tablePane.setBorder(BorderFactory.createTitledBorder(
232: BorderFactory.createLineBorder(Color.darkGray),
233: tableParam, TitledBorder.CENTER,
234: TitledBorder.DEFAULT_POSITION));
235: } catch (SQLException sqle) {
236: message = "Selection event Error\n" + sqle.getMessage();
237: System.err.println(message);
238: }
239: if (message != null)
240: status.setText(message);
241: }
242:
243: // Inner class defining handler for window events
244: class WindowHandler extends WindowAdapter {
245: public void windowOpened(WindowEvent e) {
246: openConnection();
247: }
248:
249: // Handler for window closing event
250: public void windowClosing(WindowEvent e) {
251: mif.tableBrowseFlag = 0;
252: }
253: }
254: }
|