Chapter 12: Complex Examples of Java Applications

This chapter provides advanced examples of Java applications using database metadata and Remote Method Invocation (RMI).

Dynamic Database Access: A Java Database Explorer

My first example illustrates how to use JDBC’s DatabaseMetaData and ResultSetMetaData methods. This example is a Java database explorer, and it runs as a standalone application. It can dynamically discover database content thanks to a very intuitive, SWING-based graphical user interface (GUI). Numerous JDBC database metadata methods are exploited in this example to enable the exploration of virtually any relational database management system (RDBMS), provided that a compliant JDBC driver is available for it.

The main features of this example are the following:

  • Displays DBMS information such as specifications, supported features, and inherent limitations of the engine. These features and limitations are normally not driver-dependent: Different drivers connecting to the same database will report identical information. Although JDBC is portable, databases have different capabilities and limitations that a developer may want to verify first. The tool in this example provides a simple way to fetch this kind of information from the database.

  • Explores most database objects, including database catalogs, tables, and stored procedures. For tables, metadata as well as data contained in the table can be displayed within the tool.

  • Gives relational information — that is, primary, imported, and exported keys for all tables. The tool reports the key columns and other characteristics of all types of keys.

  • Provides an Interactive SQL query and update tool. This handy tool enables you to quickly execute SQL statements and display the results in a tabular format. The SQL statement is directly passed to the driver and database. You can issue Data Definition Language (DDL) statements as well as Data Manipulation Language (DML) statements: DDL statements are used to create or modify tables and indexes, for example, whereas DML consists of the usual SELECT, UPDATE, INSERT, and DELETE statements. The tool supports statements that return a result set as well as statements that return a number, such as an update count.

  • Displays ResultSet content as formatted tabular output.

The graphical user interface part of this example was written using the SWING part of the Java Foundation Classes, part of Java 2 Standard Edition. It is currently using the SWING Metal look and feel, which can easily be changed to the Windows, Motif, or Macintosh look and feel.

The main database explorer window is divided into two areas:

  • The main database navigation widget — the left-sided tree control, from which nearly all database metadata method invocations are performed

  • The result window, showing a table widget to represent either database metadata information or table data (up to 200 rows in this example)

Figure 12-1 depicts the main window of this example.

The following subsections explain how the user interacts with this standalone Java application, discovers the database properties using the DatabaseMetaData interface, and executes SQL statements.

Logging in to the database

As shown in Figure 12-2, logging in to the database engine requires a correct database URL, JDBC driver, user login, and user password. The syntax of the URL is driver-dependant. The login and password are the identification and authorization strings for a particular user in the database management system (DBMS). Note that sample URL strings and driver class names are provided and accessible via the bottom-left drop-down list box. These samples are located in the connections. properties file provided in the jdbcexplorer package directory of the jar file. Adding or changing entries is simply done by editing this property file. An example is provided in Listing 12-1 (later in this chapter). An entry looks like the following:

Hypersonic: jdbc:HypersonicSQL:hsql://localhost|org.hsql.jdbcDriver

click to expand
Figure 12-1: The JDBCExplorer main window.

click to expand
Figure 12-2: Supplying login data.

Three fields are specified per entry:

  • The connection name, which cannot contain spaces.

  • The JDBC URL used to connect to a given database; its format is driver-dependent.

  • The JDBC driver class name, including the package name; this driver will be dynamically loaded and must be present in the CLASSPATH.

Click Connect to log in to the DBMS. Use Disconnect to disconnect from the database engine without quitting the application. You can enter another JDBC URL, and you can click the Connect button again. Disconnect can be used as a temporary logout if you intend to reboot the database server or before logging in as another user. This sample program tries to load the JDBC driver at the connect time, which will throw an exception if the required driver isn’t in the CLASSPATH.

The navigation graphical control

The tree widget on the left side, which controls the whole application and navigates within the database, is a SWING JTree component. The Session, Engine, and Objects nodes intensively use database metadata methods to get information from the database. Double-clicking these tree nodes performs all actions. The resulting data displays in the right window, a SWING JTable.

The tree widget shown in Figure 12-3 controls the whole program.

click to expand
Figure 12-3: The main navigation control widget.

Database engine specifications and limitations

Database information is divided into four categories. Figure 12-4 illustrates one of the four categories, Specs, or the database specifications. Figure 12-4 shows a small part of the features supported by the database engine. Each topic has its corresponding JDBC database metadata method, which, in general, returns true or false, an integer value, or a list of string values.

click to expand
Figure 12-4: Database specifications.

Browsing database catalogs and their content

The database-browsing features are the most interesting. The main navigation widget enables you to browse through many database objects by expanding and collapsing its nodes. Each activation of a node issues database metadata method invocations to dynamically discover the database objects. Figure 12-5 shows the database catalog nodes. All metadata available about any particular database object is shown in the table on the right side.

click to expand
Figure 12-5: Database catalog nodes.

When you click the Objects Catalogs node, the program fetches information about database objects, such as system tables, user tables, and stored procedures. Catalogs are simply database subspaces. In a DBMS managing multiple databases, a catalog is one database. Each catalog can contain system and user tables as well as stored procedures. Both types of database objects can be discovered using the JDBC MetaData interface. Figure 12-6 shows the effect of selecting a table object.

click to expand
Figure 12-6: Table objects.

As shown in Figure 12-7, metadata about the table columns is available. The metadata that is available is database and driver dependent. It may provide column details such as the following:

click to expand
Figure 12-7: Columns.

  • The catalog of the table

  • The schema of the table

  • The SQL data type integer

  • The SQL type name

  • The column size

  • The buffer length

  • The number of decimal digits

  • Whether or not the column is nullable

Primary key columns, as well as details for imported keys and exported keys, are available, too, for user and system tables. This is shown in Figure 12-8.

The procedure node lists all database-stored procedures in the current catalog and displays the results of the DatabaseMetaData.getProcedureColumns() method.

click to expand
Figure 12-8: Primary keys.

An Interactive SQL tool

Figure 12-9 depicts the Interactive SQL tool that enables you to type and execute SQL statements, such as queries and updates. The results, which can be composed of rows or an update counter, are displayed in the JTable.

click to expand
Figure 12-9: An Interactive SQL tool.

SQLException messages aren’t standardized: They are database and driver dependent. Comparing exception messages thrown by different drivers for the same query is a good exercise.

click to expand
Figure 12-10: A SQLException message window.

As shown in Figure 12-11, a help screen is available. Help is provided as an HTML file loaded in a SWING JEditorPane. It is fairly simple to use hyperlinks within the help files as well as to provide contextual help; however, in this example, help isn’t context-sensitive.

click to expand
Figure 12-11: JDBCExplorer help.

Finally, a simple About box provides version information, as shown in Figure 12-12.

click to expand
Figure 12-12: The JDBCExplorer About box.

The source code for the JDBCExplorer example

Listing 12-1 shows the connections.properties file used by JDBCExplorer. It defines several database URLs and drivers that can be used within the tool. Listings 12-2 through 12-10 contain the whole source code for the Java database explorer.

Listing 12-1: connections.properties

start example
DB2: jdbc:db2://localhost:4100/mydb;|com.ibm.DB2.JdbcDriver Cloudscape: jdbc:cloudscape:HelloWorldDB;create=true| \   COM.cloudscape.core.JDBCDriver Connect_SW: jdbc:sybase://localhost:8192|connect.sybase.SybaseDriver Hypersonic: jdbc:HypersonicSQL:hsql://localhost|org.hsql.jdbcDriver Informix: jdbc:informix-sqli://localhost:1526/mydb:INFORMIXSERVER=prod01_ol;| \   com.informix.jdbc.IfxDriver MiniSQL: jdbc:msql://localhost:4333/Testdb|COM.imaginary.sql.msql.MsqlDriver ODBC_Bridge: jdbc:odbc:data-source-name|sun.jdbc.odbc.JdbcOdbcDriver Oracle: jdbc:oracle://localhost:1521/ORACLE_SID;|com.oracle.jdbc.OracleDriver Oracle_Lite: jdbc:polite:data_sourcename|oracle.pol.poljdbc.POLJDBCDriver Sybase: jdbc:sybase:Tds:localhost:8192|com.sybase.jdbc.SybDriver Other: add it in the connections.properties file!|...
end example

Each entry of this file contains both a key and connection information. The key is an arbitrary name for your database. The connection information is structured: It contains a JDBC URL, followed by a pipe character (|), followed by the class name of the JDBC driver that understands the preceding URL format. You are free to add as many lines as you want or to adapt these lines to your database.

Listing 12-2: AboutBox.java

start example
package jdbcexplorer; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; /**  * Title:        AboutBox  * Description:  * Company:  * @author Bernard Van Haecke  * @version 2.0  */ public class AboutBox extends JDialog implements ActionListener {   JPanel panel1 = new JPanel();   JPanel panel2 = new JPanel();   JPanel insetsPanel1 = new JPanel();   JPanel insetsPanel2 = new JPanel();   JPanel insetsPanel3 = new JPanel();   JButton button1 = new JButton();   JLabel imageLabel = new JLabel();   JLabel label1 = new JLabel();   JLabel label2 = new JLabel();   JLabel label3 = new JLabel();   JLabel label4 = new JLabel();   BorderLayout borderLayout1 = new BorderLayout();   BorderLayout borderLayout2 = new BorderLayout();   FlowLayout flowLayout1 = new FlowLayout();   GridLayout gridLayout1 = new GridLayout();   String product = "JDBCExplorer";   String version = "2.0";   String copyright = "Copyright (c) 1996, 2000, 2001";   String comments = "Bernard.Vanhaecke@Belgium.Sun.COM";   public AboutBox(Frame parent) {     super(parent);     enableEvents(AWTEvent.WINDOW_EVENT_MASK);     try {       jbInit();     }     catch(Exception e) {       e.printStackTrace();     }     pack();   }   /**Component initialization*/   private void jbInit() throws Exception  {     //imageLabel.setIcon(new ImageIcon(        Mainframe_AboutBox.class.getResource("[Your Image]")));     this.setTitle("About");     setResizable(false);     panel1.setLayout(borderLayout1);     panel2.setLayout(borderLayout2);     insetsPanel1.setLayout(flowLayout1);     insetsPanel2.setLayout(flowLayout1);     insetsPanel2.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));     gridLayout1.setRows(4);     gridLayout1.setColumns(1);     label1.setText(product);     label2.setText(version);     label3.setText(copyright);     label4.setText(comments);     insetsPanel3.setLayout(gridLayout1);     insetsPanel3.setBorder(BorderFactory.createEmptyBorder(10, 60, 10, 10));     button1.setText("Ok");     button1.addActionListener(this);     imageLabel.setIcon(new ImageIcon(AboutBox.class.getResource("logo.gif")));     insetsPanel2.add(imageLabel, null);     panel2.add(insetsPanel2, BorderLayout.WEST);     this.getContentPane().add(panel1, null);     insetsPanel3.add(label1, null);     insetsPanel3.add(label2, null);     insetsPanel3.add(label3, null);     insetsPanel3.add(label4, null);     panel2.add(insetsPanel3, BorderLayout.CENTER);     insetsPanel1.add(button1, null);     panel1.add(insetsPanel1, BorderLayout.SOUTH);     panel1.add(panel2, BorderLayout.NORTH);   }   /**Overridden so we can exit when window is closed*/   protected void processWindowEvent(WindowEvent e) {     if (e.getID() == WindowEvent.WINDOW_CLOSING) {       cancel();     }     super.processWindowEvent(e);   }   /**Close the dialog*/   void cancel() {     dispose();   }   /**Close the dialog on a button event*/   public void actionPerformed(ActionEvent e) {     if (e.getSource() == button1) {       cancel();     }   } } 
end example

Listing 12-3: ConnectionBox.java

start example
package jdbcexplorer; import java.awt.*; import java.awt.event.*; import java.util.*; import java.io.*; import javax.swing.*; import javax.swing.border.*; /**  * Title:        ConnectionBox  * Description:  * Company:  * @author Bernard Van Haecke  * @version 2.0  */ public class ConnectionBox extends JDialog {   BorderLayout borderLayout1 = new BorderLayout();   JPanel jPanel1 = new JPanel();   FlowLayout flowLayout1 = new FlowLayout();   JButton jButton1 = new JButton();   JButton jButton2 = new JButton();   JPanel jPanel2 = new JPanel();   JTextField jTextField3 = new JTextField();   JTextField jTextField2 = new JTextField();   JTextField jTextField1 = new JTextField();   JPasswordField jPasswordField1 = new JPasswordField();   GridBagLayout gridBagLayout1 = new GridBagLayout();   JLabel jLabel4 = new JLabel();   JLabel jLabel3 = new JLabel();   JLabel jLabel2 = new JLabel();   JLabel jLabel1 = new JLabel();   JPanel jPanel3 = new JPanel();   FlowLayout flowLayout2 = new FlowLayout();   JComboBox jComboBox1 = new JComboBox();   JLabel jLabel5 = new JLabel();   String databases[][] = new String[20][2];   Mainframe mf;   public ConnectionBox(Mainframe parent) {     super((Frame) parent);     mf = parent;     enableEvents(AWTEvent.WINDOW_EVENT_MASK);     try {       jbInit();     }     catch(Exception e) {       e.printStackTrace();     }     pack();   }   private void jbInit() throws Exception {     this.getContentPane().setLayout(borderLayout1);     jPanel1.setLayout(flowLayout1);     jButton1.setText("Connect");     if (DatabaseConnection.getInstance() != null) {       if (DatabaseConnection.getInstance().isActive()) {          jButton1.setText("Disconnect");       }     }     jButton1.addActionListener(new java.awt.event.ActionListener() {       public void actionPerformed(ActionEvent e) {         jButton1_actionPerformed(e);       }     });     jButton2.setText("Close");     jButton2.addActionListener(new java.awt.event.ActionListener() {       public void actionPerformed(ActionEvent e) {         jButton2_actionPerformed(e);       }     });     this.setTitle("JDBC Connection Parameters");     jPanel2.setLayout(flowLayout2);     jTextField3.setSelectionEnd(15);     jLabel4.setText("Password:");     jLabel3.setText("Login:");     jLabel2.setText("Driver:");     jLabel1.setText("URL:");     jPanel3.setLayout(gridBagLayout1);     jLabel5.setText("Bookmarks:");     jComboBox1.addActionListener(new java.awt.event.ActionListener() {       public void actionPerformed(ActionEvent e) {         jComboBox1_actionPerformed(e);       }     });     this.getContentPane().add(jPanel1, BorderLayout.SOUTH);     jPanel1.add(jLabel5, null);     jPanel1.add(jComboBox1, null);     jPanel1.add(jButton1, null);     jPanel1.add(jButton2, null);     this.getContentPane().add(jPanel2, BorderLayout.CENTER);     jPanel2.add(jPanel3, null);     jPanel3.add(jLabel1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,             GridBagConstraints.WEST, GridBagConstraints.NONE,              new Insets(0, 10, 0, 0), 10, 0));     jPanel3.add(jTextField1, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0,             GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL,              new Insets(10, 0, 10, 10), 233, 0));     jPanel3.add(jLabel2, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0,             GridBagConstraints.WEST, GridBagConstraints.NONE,              new Insets(0, 10, 0, 0), 10, 0));     jPanel3.add(jTextField2, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0,             GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL,              new Insets(10, 0, 10, 10), 164, 0));     jPanel3.add(jLabel3, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0,             GridBagConstraints.WEST, GridBagConstraints.NONE,              new Insets(0, 10, 0, 0), 10, 0));     jPanel3.add(jTextField3, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0,             GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL,              new Insets(10, 0, 10, 10), 163, 0));     jPanel3.add(jLabel4, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0,             GridBagConstraints.WEST, GridBagConstraints.NONE,              new Insets(0, 10, 0, 0), 10, 0));     jPanel3.add(jPasswordField1, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0,             GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL,              new Insets(10, 0, 10, 10), 131, 0));     Properties p = new Properties();     p.load(ConnectionBox.class.getResourceAsStream("connections.properties"));     int i=0;     for (Enumeration e = p.propertyNames(); e.hasMoreElements();) {         String name = (String) e.nextElement();         String entry = p.getProperty(name);         databases[i][0] = entry.substring(0, entry.indexOf(‘|’));         databases[i][1] = entry.substring(entry.indexOf(‘|’) + 1);         jComboBox1.addItem(name);         i++;     }   }   public void showError(Exception e) {     mf.showError(e);   }   void jButton1_actionPerformed(ActionEvent e) {     DatabaseConnection conn = DatabaseConnection.getInstance();     try {       if (conn == null) {         conn = new DatabaseConnection(jTextField1.getText(),           jTextField2.getText(), jTextField3.getText(),            new String(jPasswordField1.getPassword()));         jButton1.setText("Disconnect");         this.dispose();       } else if (conn.isActive()) {         conn.disconnect();         conn = null;         jButton1.setText("Connect");       } else {         conn.connect(jTextField1.getText(), jTextField2.getText(),            jTextField3.getText(), new String(jPasswordField1.getPassword()));         jButton1.setText("Disconnect");         this.dispose();       }     } catch (Exception ex) {       showError(ex);       conn = null;       jButton1.setText("Connect");     }   }   void jButton2_actionPerformed(ActionEvent e) {     this.dispose();   }   void jComboBox1_actionPerformed(ActionEvent e) {     int i = jComboBox1.getSelectedIndex();     jTextField1.setText(databases[i][0]);     jTextField2.setText(databases[i][1]);   } } 
end example

Listing 12-4: DatabaseConnection.java

start example
package jdbcexplorer; import java.sql.*; import java.util.*; /**  * Title:        DatabaseConnection  * Description:  * Company:  * @author Bernard Van Haecke  * @version 2.0  */ public class DatabaseConnection {   private boolean connected = false;   private Connection conn = null;   private DatabaseMetaData mtdt = null;   private static DatabaseConnection instance;   public DatabaseConnection() {     instance = this;   }   public DatabaseConnection(String url, String driver, String login,                             String password) throws Exception {     instance = this;     connect(url, driver, login, password);   }   public static void main(String[] args) throws Exception {     DatabaseConnection databaseConnection1 = new DatabaseConnection(args[0],        args[1], args[2], args[3]);     databaseConnection1.test();   }   public void connect(String url, String driver, String login,                        String password) throws Exception {     Class.forName(driver);     conn = DriverManager.getConnection(url, login, password);     if (conn != null) {       connected = true;     }   }   public void disconnect() {     try {       conn.close();       connected = false;       mtdt = null;       conn = null;     } catch (Exception e) {     }   }   public static DatabaseConnection getInstance() {     return instance;   }   public boolean isActive() {     return connected;   }   public String[][] getSession() throws Exception {     if (mtdt == null) { mtdt = conn.getMetaData(); }     String[][] s = new String[3][2];     s[0] = setString2("Property", "Value");     s[1] = setString2("URL in use", mtdt.getURL());     s[2] = setString2("Username", mtdt.getUserName());     mtdt = null;     return s;   }   public String[][] getEngineInfo() throws Exception {     if (mtdt == null) { mtdt = conn.getMetaData(); }     String[][] s = new String[5][2];     s[0] = setString2("Property", "Value");     s[1] = setString2("Database name", mtdt.getDatabaseProductName());     s[2] = setString2("Database version", mtdt.getDatabaseProductVersion());     s[3] = setString2("Driver name", mtdt.getDriverName());     s[4] = setString2("Driver version", mtdt.getDriverVersion());     mtdt = null;     return s;   }   public String[][] getEngineSpecs() throws Exception {     if (mtdt == null) { mtdt = conn.getMetaData(); }     String[][] s = new String[13][2];     s[0] = setString2("Property", "Value");     s[1] = setString2("Uses local files", mtdt.usesLocalFiles());     s[2] = setString2(" Uses local file per table", mtdt.usesLocalFilePerTable());     s[3] = setString2("Nulls are sorted high", mtdt.nullsAreSortedHigh());     s[4] = setString2("Nulls are sorted at end", mtdt.nullsAreSortedAtEnd());     s[5] = setString2("Supports mixed case identifiers",                        mtdt.supportsMixedCaseIdentifiers());     s[6] = setString2("Stores mixed case identifiers",                         mtdt.storesMixedCaseIdentifiers());     s[7] = setString2(" Identifier quote string", mtdt.getIdentifierQuoteString());     s[8] = setString2("Supported SQL keywords", mtdt.getSQLKeywords());     s[9] = setString2("Numeric functions", mtdt.getNumericFunctions());     s[10] = setString2("String functions", mtdt.getStringFunctions());     s[11] = setString2("System functions", mtdt.getSystemFunctions());     s[12] = setString2("Time and date functions", mtdt.getTimeDateFunctions());     mtdt = null;     return s;   }   public String[][] getEngineFeatures() throws Exception {     if (mtdt == null) { mtdt = conn.getMetaData(); }     String[][] s = new String[27][2];     s[0] = setString2("Property", "Value");     s[1] = setString2("Minimun SQL grammar", mtdt.supportsMinimumSQLGrammar());     s[2] = setString2("Core SQL grammar", mtdt.supportsCoreSQLGrammar());     s[3] = setString2(" Extended SQL grammar", mtdt.supportsExtendedSQLGrammar());     s[4] = setString2("ANSI-92 Entry Level SQL",                          mtdt.supportsANSI92EntryLevelSQL());     s[5] = setString2("ANSI-92 Intermediate SQL",                         mtdt.supportsANSI92IntermediateSQL());     s[6] = setString2("ANSI-92 Full SQL grammar", mtdt.supportsANSI92FullSQL());     s[7] = setString2("Integrity enhancement facility",                         mtdt.supportsIntegrityEnhancementFacility());     s[8] = setString2("Outer joins", mtdt.supportsOuterJoins());     s[9] = setString2("Full outer joins", mtdt.supportsFullOuterJoins());     s[10] = setString2("Limited outer joins", mtdt.supportsLimitedOuterJoins());     s[11] = setString2("Alter table with add column",                          mtdt.supportsAlterTableWithAddColumn());     s[12] = setString2("Alter table with drop column",                          mtdt.supportsAlterTableWithDropColumn());     s[13] = setString2("Column aliasing", mtdt.supportsColumnAliasing());     s[14] = setString2("Table correlation names",                          mtdt.supportsTableCorrelationNames());     s[15] = setString2("Expressions in order by",                          mtdt.supportsExpressionsInOrderBy());     s[16] = setString2("Unrelated order by", mtdt.supportsOrderByUnrelated());     s[17] = setString2("Group by", mtdt.supportsGroupBy());     s[18] = setString2("Unrelated group by", mtdt.supportsGroupByUnrelated());     s[19] = setString2("Group by beyond select",                          mtdt.supportsGroupByBeyondSelect());     s[20] = setString2("Like escape clause", mtdt.supportsLikeEscapeClause());     s[21] = setString2(" Multiple result sets", mtdt.supportsMultipleResultSets());     s[22] = setString2("Multiple transactions",                          mtdt.supportsMultipleTransactions());     s[23] = setString2(" Non nullable columns",  mtdt.supportsNonNullableColumns());     s[24] = setString2("Term for schemas", mtdt.getSchemaTerm());     s[25] = setString2("Term for procedures", mtdt.getProcedureTerm());     s[26] = setString2("Term for catalogs", mtdt.getCatalogTerm());     mtdt = null;     return s;   }   public String[][] getEngineLimitations() throws Exception {     if (mtdt == null) { mtdt = conn.getMetaData(); }     String[][] s = new String[10][2];     s[0] = setString2("Property", "Value");     s[1] = setString2(" Binary literal length", mtdt.getMaxBinaryLiteralLength());     s[2] = setString2(" Character literal length", mtdt.getMaxCharLiteralLength());     s[3] = setString2("Column name length", mtdt.getMaxColumnNameLength());     s[4] = setString2("Columns in group by", mtdt.getMaxColumnsInGroupBy());     s[5] = setString2("Columns in index", mtdt.getMaxColumnsInIndex());     s[6] = setString2("Columns in order by", mtdt.getMaxColumnsInOrderBy());     s[7] = setString2("Columns in select", mtdt.getMaxColumnsInSelect());     s[8] = setString2("Columns in table", mtdt.getMaxColumnsInTable());     s[9] = setString2("Number of connections", mtdt.getMaxConnections());     mtdt = null;     return s;   }   public String[] getCatalogs() throws Exception {     if (mtdt == null) { mtdt = conn.getMetaData(); }     String[] s = getResultSetColumn(mtdt.getCatalogs(), 1);     if (s.length == 0) {       s = new String[1];       s[0] = ""; // anonymous catalog     }     mtdt = null;     return s;   }   public String[] getTables(String catalog, String type) throws Exception {     if (mtdt == null) { mtdt = conn.getMetaData(); }     String[] types = new String[1];     types[0] = type;     String[] s = getResultSetColumn(mtdt.getTables(catalog, null, "%", types),                                      "TABLE_NAME");     mtdt = null;     return s;   }   public String[][] getTableColumns(String catalog, String table)                      throws Exception {     if (mtdt == null) { mtdt = conn.getMetaData(); }     String[][] s = getAllResultSetColumns(mtdt.getColumns(catalog, null, table,                                            "%"));     mtdt = null;     return s;   }   public String[][] getTablePrimaryKeys(String catalog, String table)                     throws Exception {     if (mtdt == null) { mtdt = conn.getMetaData(); }     String[][] s = getAllResultSetColumns(mtdt.getPrimaryKeys(catalog, null,                                            table));     mtdt = null;     return s;   }   public String[][] getTableImportedKeys(String catalog, String table)                      throws Exception {     if (mtdt == null) { mtdt = conn.getMetaData(); }     String[][] s = getAllResultSetColumns(mtdt.getImportedKeys(catalog, null,                                            table));     mtdt = null;     return s;   }   public String[][] getTableExportedKeys(String catalog, String table)                      throws Exception {     if (mtdt == null) { mtdt = conn.getMetaData(); }     String[][] s = getAllResultSetColumns(mtdt.getExportedKeys(catalog, null,                                           table));     mtdt = null;     return s;   }   public String[] getProcedures(String catalog) throws Exception {     if (mtdt == null) { mtdt = conn.getMetaData(); }     String[] s = getResultSetColumn(mtdt.getProcedures(catalog, null, "%"),                                      "PROCEDURE_NAME");     mtdt = null;     return s;   }   public String[][] getProcedureColumns(String catalog, String procedure)                      throws Exception {     if (mtdt == null) { mtdt = conn.getMetaData(); }     String[][] s = getAllResultSetColumns(mtdt.getProcedureColumns(catalog, null,                                            procedure, "%"));     mtdt = null;     return s;   }   public void test() throws Exception {     String text =        toString2(getSession()) +                          toString2(getEngineInfo()) +                          toString2(getEngineSpecs()) +                          toString2(getEngineFeatures()) +                          toString2(getEngineLimitations());     System.out.println("-> METADATAS\n" + text);     String[] catalogs = getCatalogs();     System.out.println("-> CATALOGS\n" + toString1(catalogs));     for (int i = 0; i<catalogs.length; i++) {       System.out.println("-> USER TABLES IN " + catalogs[i]);       System.out.println(toString1(getTables(catalogs[i], "TABLE")));     }     for (int i = 0; i<catalogs.length; i++) {       System.out.println("-> SYSTEM TABLES IN " + catalogs[i]);       System.out.println(toString1(getTables(catalogs[i], "SYSTEM TABLE")));     }     System.out.println(toString2(getAllResultSetColumns(                                     getResultSet("SELECT * FROM TEST"))));     System.out.println("OK");   }   // ************************************************************************   public String[] getResultSetColumn(ResultSet rs, String column)                    throws Exception {     Vector v = new Vector();     while (rs.next()) {       v.addElement(rs.getString(column));     }     String s[] = new String[v.size()];     s = v2a(v);     return s;   }   public String[] getResultSetColumn(ResultSet rs, int i) throws Exception {     Vector v = new Vector();     while (rs.next()) {       v.addElement(rs.getString(i));     }     String s[] = new String[v.size()];     s = v2a(v);     return s;   }   public ResultSet getResultSet(String sql) throws Exception {     Statement st = conn.createStatement();     st.setMaxRows(200);     System.out.println(sql);     return st.executeQuery(sql);   }   public String[][] executeComplexQuery(String sql) throws Exception {     boolean resultSetIsAvailable;     boolean moreResultsAvailable;     int i = 0;     int res=0;     String[][] bigresult = null;     String[][] result = null;     Statement curStmt = conn.createStatement();     resultSetIsAvailable = curStmt.execute(sql);     ResultSet rs = null;     for (moreResultsAvailable = true; moreResultsAvailable; ) {       if (resultSetIsAvailable) {         if ((rs = curStmt.getResultSet()) != null) {           // we have a resultset           result = getAllResultSetColumns(rs);         }       } else {         if ((res = curStmt.getUpdateCount()) != -1) {           // we have an updatecount           result = new String[2][2];           result[0] = setString2("UPDATE", "");           result[1] = setString2("Update count", res);         } else {           // else no more results           moreResultsAvailable = false;         }       }       if (moreResultsAvailable) {           resultSetIsAvailable = curStmt.getMoreResults();       }       bigresult = concat(bigresult, result);     }     if (rs != null) rs.close();     curStmt.close();     return bigresult;   }   public String[][] getAllResultSetColumns(ResultSet rs) throws Exception {     String[] headers = getResultSetColumnHeaders(rs);     String[][] rows = getResultSetRows(rs);     String[][] t = new String[rows.length+1][headers.length];     t[0] = headers;     for (int i=0; i<rows.length; i++) {       t[i+1] = rows[i];     }     return t;   }   public String[] getResultSetColumnHeaders(ResultSet rs) throws Exception {     ResultSetMetaData rsmd = rs.getMetaData();     String[] headers = new String[rsmd.getColumnCount()];     for (int i=0; i<headers.length; i++) {       headers[i] = rsmd.getColumnLabel(i+1);     }     return headers;   }   public String[][] getResultSetRows(ResultSet rs) throws Exception {     ResultSetMetaData rsmd = rs.getMetaData();     Vector v = new Vector();     while (rs.next()) {       String[] columns = new String[rsmd.getColumnCount()];       for (int i=0; i<columns.length; i++) {           columns[i] = rs.getString(i+1);       }       v.addElement(columns);     }     String[][] t = new String[v.size()][rsmd.getColumnCount()];     for (int i=0; i<v.size(); i++) {       t[i] = (String[]) v.elementAt(i);     }     rs.close();     return t;   }   public String[] setString2(String s, String t) {     String[] r = new String[2];     r[0] = new String(s);     r[1] = new String(t);     return r;   }   public String[] setString2(String s, boolean b) {     String[] r = new String[2];     r[0] = new String(s);     r[1] = new String(b?"yes":"no");     return r;   }   public String[] setString2(String s, int i) {     String[] r = new String[2];     r[0] = new String(s);     r[1] = "" + i;     return r;   }   public String toString1(String[] s1) {     String s = "\n";     for (int i=0; i<s1.length; i++) {       s += s1[i] + "\n";     }     return s;   }   public String toString2(String[][] s2) {     String s = "\n";     for (int i=0; i<s2.length; i++) {       for (int j=0; j<s2[0].length; j++) {         s += s2[i][j] + "\t";       }       s += "\n";     }     return s;   }   public String[] v2a(Vector v) {     String[] s = new String[v.size()];     for (int i=0; i<v.size(); i++) {       s[i] = (String) v.elementAt(i);     }     return s;   }   public String[][] concat(String[][] a, String[][] b) {     if (a == null) return b;     if (b == null) return a;     String[][] out =         new String[a.length + b.length][Math.max(a[0].length, b[0].length)];     for (int i=0; i<a.length; i++) {       out[i] = a[i];     }     for (int j=0; j<b.length; j++) {       out[a.length + j] = b[j];     }     return out;   } } 
end example

Listing 12-5: ErrorBox.java

start example
package jdbcexplorer; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; /**  * Title:        ErrorBox  * Description:  * Company:  * @author Bernard Van Haecke  * @version 2.0  */ public class ErrorBox extends JDialog {   JPanel panel1 = new JPanel();   JPanel insetsPanel1 = new JPanel();   JButton button1 = new JButton();   BorderLayout borderLayout1 = new BorderLayout();   JScrollPane jScrollPane1 = new JScrollPane();   JTextPane jTextPane1 = new JTextPane();   static Exception lastException = new Exception("No Exception");   public ErrorBox(Frame parent, Exception ex) {     super(parent);     enableEvents(AWTEvent.WINDOW_EVENT_MASK);     try {       jbInit();       String text = "";       if (ex != null) {          lastException = ex;       }       java.io.StringWriter s = new java.io.StringWriter();       lastException.printStackTrace(new java.io.PrintWriter(s));       text = s.toString();       jTextPane1.setText(text);       this.setTitle(lastException.getMessage());     }     catch(Exception e) {       e.printStackTrace();     }     pack();   }   /**Component initialization*/   private void jbInit() throws Exception  {     //imageLabel.setIcon(          new ImageIcon( Mainframe_AboutBox.class.getResource("[Your Image]")));     panel1.setLayout(borderLayout1);     button1.setText("Close");     button1.addActionListener(new java.awt.event.ActionListener() {       public void actionPerformed(ActionEvent e) {         jButton1_actionPerformed(e);       }     });     jScrollPane1.setHorizontalScrollBarPolicy(             JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);     jScrollPane1.setVerticalScrollBarPolicy(             JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);     jScrollPane1.setPreferredSize(new Dimension(400, 150));     jTextPane1.setForeground(Color.red);     jTextPane1.setPreferredSize(new Dimension(400, 150));     jTextPane1.setEditable(false);     this.getContentPane().add(panel1, null);     insetsPanel1.add(button1, null);     panel1.add(jScrollPane1, BorderLayout.CENTER);     jScrollPane1.getViewport().add(jTextPane1, null);     panel1.add(insetsPanel1, BorderLayout.SOUTH);   }   /**Overridden so we can exit when window is closed*/   protected void processWindowEvent(WindowEvent e) {     if (e.getID() == WindowEvent.WINDOW_CLOSING) {       cancel();     }     super.processWindowEvent(e);   }   /**Close the dialog*/   void cancel() {     dispose();   }   void jButton1_actionPerformed(ActionEvent e) {     cancel();   }   /**Close the dialog on a button event*/   public void actionPerformed(ActionEvent e) {     if (e.getSource() == button1) {       cancel();     }   } } 
end example

Listing 12-6: HelpBox.java

start example
package jdbcexplorer; import java.io.*; import java.net.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; import javax.swing.text.html.*; /**  * Title:        HelpBox  * Description:  * Company:  * @author Bernard Van Haecke  * @version 2.0  */ public class HelpBox extends JDialog {   JPanel panel1 = new JPanel();   JPanel insetsPanel1 = new JPanel();   JButton button1 = new JButton();   BorderLayout borderLayout1 = new BorderLayout();   JScrollPane jScrollPane1 = new JScrollPane();   JEditorPane jEditorPane = new JEditorPane();   public HelpBox(Frame parent) {     super(parent);     enableEvents(AWTEvent.WINDOW_EVENT_MASK);     jbInit();     this.setTitle("Help");     pack();   }   /**Component initialization*/   private void jbInit() {     //imageLabel.setIcon(new ImageIcon(              Mainframe_AboutBox.class.getResource("[Your Image]")));     panel1.setLayout(borderLayout1);     button1.setText("Close");     button1.addActionListener(new java.awt.event.ActionListener() {       public void actionPerformed(ActionEvent e) {         jButton1_actionPerformed(e);       }     });     jScrollPane1.setHorizontalScrollBarPolicy(             JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);     jScrollPane1.setVerticalScrollBarPolicy(             JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);     jScrollPane1.setPreferredSize(new Dimension(400, 300));     jEditorPane.setPreferredSize(new Dimension(400, 300));     jEditorPane.setEditable(false);     URL url = jdbcexplorer.Mainframe.class.getResource("help.html");     try {       jEditorPane.setPage(url);     } catch (IOException e) {       System.err.println("Attempted to read a bad URL: " + url);     }     HyperlinkListener h = new HyperlinkListener() {       public void hyperlinkUpdate(HyperlinkEvent e) {         if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {           JEditorPane pane = (JEditorPane) e.getSource();             if (e instanceof HTMLFrameHyperlinkEvent) {               HTMLFrameHyperlinkEvent  evt = (HTMLFrameHyperlinkEvent)e;               HTMLDocument doc = (HTMLDocument)pane.getDocument();               doc.processHTMLFrameHyperlinkEvent(evt);             } else {               try {                   pane.setPage(e.getURL());               } catch (Throwable t) {                   t.printStackTrace();               }             }         }       }     };     jEditorPane.addHyperlinkListener(h);     this.getContentPane().add(panel1, null);     insetsPanel1.add(button1, null);     panel1.add(jScrollPane1, BorderLayout.CENTER);     jScrollPane1.getViewport().add(jEditorPane, null);     panel1.add(insetsPanel1, BorderLayout.SOUTH);   }   /**Overridden so we can exit when window is closed*/   protected void processWindowEvent(WindowEvent e) {     if (e.getID() == WindowEvent.WINDOW_CLOSING) {       cancel();     }     super.processWindowEvent(e);   }   /**Close the dialog*/   void cancel() {     dispose();   }   void jButton1_actionPerformed(ActionEvent e) {     cancel();   }   /**Close the dialog on a button event*/   public void actionPerformed(ActionEvent e) {     if (e.getSource() == button1) {       cancel();     }   } } 
end example

Listing 12-7: JDBCExplorer.java

start example
package jdbcexplorer; import javax.swing.UIManager; import java.awt.*; /** * Title:        JDBCExplorer  * Description:  * Company:  * @author Bernard Van Haecke  * @version 2.0  */ public class JDBCExplorer {   boolean packFrame = false;   /**Construct the application*/   public JDBCExplorer() {     Mainframe frame = new Mainframe();     //Validate frames that have preset sizes     //Pack frames that have useful preferred size info, e.g. from their layout     if (packFrame) {       frame.pack();     }     else {       frame.validate();     }     //Center the window     Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();     Dimension frameSize = frame.getSize();     if (frameSize.height > screenSize.height) {       frameSize.height = screenSize.height;     }     if (frameSize.width > screenSize.width) {       frameSize.width = screenSize.width;     }     frame.setLocation((screenSize.width - frameSize.width) / 2,                       (screenSize.height - frameSize.height) / 2);     frame.setVisible(true);   }   /**Main method*/   public static void main(String[] args) {     try {       UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");     }     catch(Exception e) {       e.printStackTrace();     }     new JDBCExplorer();   } } 
end example

Listing 12-8: Mainframe.java

start example
package jdbcexplorer; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.table.*; /**  * Title:        Mainframe  * Description:  * Company:  * @author Bernard Van Haecke  * @version 2.0  */ public class Mainframe extends JFrame {   JPanel contentPane;   JMenuBar jMenuBar1 = new JMenuBar();   JMenu jMenuFile = new JMenu();   JMenuItem jMenuFileConnect = new JMenuItem();   JMenuItem jMenuFileSQL = new JMenuItem();   JMenuItem jMenuFileError = new JMenuItem();   JMenuItem jMenuFileExit = new JMenuItem();   JMenu jMenuHelp = new JMenu();   JMenuItem jMenuHelpHelp = new JMenuItem();   JMenuItem jMenuHelpAbout = new JMenuItem();   JToolBar jToolBar = new JToolBar();   JButton jButton1 = new JButton();   JButton jButton2 = new JButton();   JButton jButton3 = new JButton();   JButton jButton4 = new JButton();   ImageIcon image1;   ImageIcon image2;   ImageIcon image3;   ImageIcon image4;   JLabel statusBar = new JLabel();   BorderLayout borderLayout1 = new BorderLayout();   JLabel status = new JLabel();   TitledBorder titledBorder1;   JSplitPane jSplitPane1 = new JSplitPane();   JScrollPane jScrollPane2 = new JScrollPane();   JTable jTable;   Navigator navigator;   public void showTable(String[][] data) {     if (data != null) {       String[] headers = data[0];       String[][] rows = new String[data.length-1][data[0].length];       for (int i=1; i<data.length; i++) {         rows[i-1] = data[i];       }       jTable = new JTable(rows, headers);       jScrollPane2 = new JScrollPane(jTable);       jScrollPane2.setHorizontalScrollBarPolicy(              JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);       jScrollPane2.setVerticalScrollBarPolicy(              JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);       //jTable.setPreferredScrollableViewportSize(new Dimension(800, 600));       jSplitPane1.add(jScrollPane2, JSplitPane.RIGHT);       jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);       TableColumn column = null;       int max = 600;       int growf = 20;       if (headers.length > 2) {         growf = 12;       }       for (int i = 0; i < headers.length; i++) {         column = jTable.getColumnModel().getColumn(i);         //column.sizeWidthToFit();         if (i == (headers.length-1)) {           if (max < (headers[i].length() * growf)) {             max = (headers[i].length() * growf);           }           column.setPreferredWidth(max);         } else {           column.setPreferredWidth(headers[i].length() * growf);           max = max - (headers[i].length() * growf);         }       }     }   }   /**Construct the frame*/   public Mainframe() {     enableEvents(AWTEvent.WINDOW_EVENT_MASK);     try {       jbInit();     }     catch(Exception e) {       e.printStackTrace();     }   }   /**Component initialization*/   private void jbInit() throws Exception  {     navigator = new Navigator(this);     image1 = new ImageIcon(jdbcexplorer.Mainframe.class.getResource(                                                                "connect.gif"));     image2 = new ImageIcon(jdbcexplorer.Mainframe.class.getResource("isql.gif"));     image3 = new ImageIcon(jdbcexplorer.Mainframe.class.getResource("error.gif"));     image4 = new ImageIcon(jdbcexplorer.Mainframe.class.getResource("help.gif"));     //setIconImage(Toolkit.getDefaultToolkit().createImage(           Mainframe.class.getResource("[Your Icon]")));     contentPane = (JPanel) this.getContentPane();     titledBorder1 = new TitledBorder("");     contentPane.setLayout(borderLayout1);     this.setSize(new Dimension(800, 600));     this.setTitle("JDBCExplorer");     statusBar.setText(" ");     jMenuFile.setText("File");     jMenuFileConnect.setText("Connect");     jMenuFileConnect.addActionListener(new ActionListener()  {       public void actionPerformed(ActionEvent e) {         jMenuFileConnect_actionPerformed(e);       }     });     jMenuFileSQL.setText("SQL Command");     jMenuFileSQL.addActionListener(new ActionListener()  {       public void actionPerformed(ActionEvent e) {         jMenuFileSQL_actionPerformed(e);       }     });     jMenuFileError.setText("Show Last Error");     jMenuFileError.addActionListener(new ActionListener()  {       public void actionPerformed(ActionEvent e) {         jMenuFileError_actionPerformed(e);       }     });     jMenuFileExit.setText("Exit");     jMenuFileExit.addActionListener(new ActionListener()  {       public void actionPerformed(ActionEvent e) {         jMenuFileExit_actionPerformed(e);       }     });     jMenuHelp.setText("Help");     jMenuHelpHelp.setText("Quick Tips");     jMenuHelpHelp.addActionListener(new ActionListener()  {       public void actionPerformed(ActionEvent e) {         jMenuHelpHelp_actionPerformed(e);       }     });     jMenuHelpAbout.setText("About");     jMenuHelpAbout.addActionListener(new ActionListener()  {       public void actionPerformed(ActionEvent e) {         jMenuHelpAbout_actionPerformed(e);       }     });     jButton1.setIcon(image1);     jButton1.setToolTipText("Open Connection");     jButton1.addActionListener(new ActionListener()  {       public void actionPerformed(ActionEvent e) {         jMenuFileConnect_actionPerformed(e);       }     });     jButton2.setIcon(image2);     jButton2.setToolTipText("SQL Command");     jButton2.addActionListener(new ActionListener()  {       public void actionPerformed(ActionEvent e) {         jMenuFileSQL_actionPerformed(e);       }     });     jButton3.setIcon(image3);     jButton3.setToolTipText("Error Log");     jButton3.addActionListener(new ActionListener()  {       public void actionPerformed(ActionEvent e) {         jMenuFileError_actionPerformed(e);       }     });     jButton4.setIcon(image4);     jButton4.setToolTipText("Help");     jButton4.addActionListener(new ActionListener()  {       public void actionPerformed(ActionEvent e) {         jMenuHelpHelp_actionPerformed(e);       }     });     status.setBorder(BorderFactory.createLoweredBevelBorder());     status.setText("JDBCExplorer");     jSplitPane1.setContinuousLayout(true);     jSplitPane1.setOneTouchExpandable(true);     jToolBar.add(jButton1);     jToolBar.add(jButton2);     jToolBar.add(jButton3);     jToolBar.add(jButton4);     jMenuFile.add(jMenuFileConnect);     jMenuFile.add(jMenuFileSQL);     jMenuFile.add(jMenuFileError);     jMenuFile.add(jMenuFileExit);     jMenuHelp.add(jMenuHelpHelp);     jMenuHelp.add(jMenuHelpAbout);     jMenuBar1.add(jMenuFile);     jMenuBar1.add(jMenuHelp);     this.setJMenuBar(jMenuBar1);     contentPane.add(statusBar, BorderLayout.WEST);     contentPane.add(status, BorderLayout.SOUTH);     contentPane.add(jSplitPane1, BorderLayout.CENTER);     jSplitPane1.add(navigator, JSplitPane.LEFT);     jSplitPane1.add(jScrollPane2, JSplitPane.RIGHT);     contentPane.add(jToolBar, BorderLayout.NORTH);   }   /**File | Exit action performed*/   public void jMenuFileExit_actionPerformed(ActionEvent e) {     System.exit(0);   }   /**File | Connect action performed*/   public void jMenuFileConnect_actionPerformed(ActionEvent e) {     ConnectionBox dlg = new ConnectionBox(this);     Dimension dlgSize = dlg.getPreferredSize();     Dimension frmSize = getSize();     Point loc = getLocation();     dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x,         (frmSize.height - dlgSize.height) / 2 + loc.y);     dlg.setModal(true);     dlg.show();   }   /**File | SQL action performed*/   public void jMenuFileSQL_actionPerformed(ActionEvent e) {     SQLCommandBox dlg = new SQLCommandBox(this);     Dimension dlgSize = dlg.getPreferredSize();     Dimension frmSize = getSize();     Point loc = getLocation();     dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x,          (frmSize.height - dlgSize.height) / 2 + loc.y);     dlg.setModal(false);     dlg.show();   }   /**File | Error action performed*/   public void jMenuFileError_actionPerformed(ActionEvent e) {     showError(null);   }   public void showError(Exception e) {     ErrorBox dlg = new ErrorBox(this, e);     Dimension dlgSize = dlg.getPreferredSize();     Dimension frmSize = getSize();     Point loc = getLocation();     dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x,          (frmSize.height - dlgSize.height) / 2 + loc.y);     dlg.setModal(true);     dlg.show();   }   /**Help | Help action performed*/   public void jMenuHelpHelp_actionPerformed(ActionEvent e) {     HelpBox dlg = new HelpBox(this);     Dimension dlgSize = dlg.getPreferredSize();     Dimension frmSize = getSize();     Point loc = getLocation();     dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x,          (frmSize.height - dlgSize.height) / 2 + loc.y);     dlg.setModal(false);     dlg.show();   }   /**Help | About action performed*/   public void jMenuHelpAbout_actionPerformed(ActionEvent e) {     AboutBox dlg = new AboutBox(this);     Dimension dlgSize = dlg.getPreferredSize();     Dimension frmSize = getSize();     Point loc = getLocation();     dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x,          (frmSize.height - dlgSize.height) / 2 + loc.y);     dlg.setModal(true);     dlg.show();   }   /**Overridden so we can exit when window is closed*/   protected void processWindowEvent(WindowEvent e) {     super.processWindowEvent(e);     if (e.getID() == WindowEvent.WINDOW_CLOSING) {       jMenuFileExit_actionPerformed(null);     }   } } 
end example

Listing 12-9: Navigator.java

start example
package jdbcexplorer; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.tree.*; /**  * Title:        Navigator  * Description:  * Company:  * @author Bernard Van Haecke  * @version 2.0  */ public class Navigator extends JPanel {   public JTree tree;   public Mainframe mf;   public DefaultMutableTreeNode root;   public DefaultMutableTreeNode session;   public DefaultMutableTreeNode engine;   public DefaultMutableTreeNode engine_info;   public DefaultMutableTreeNode engine_specs;   public DefaultMutableTreeNode engine_features;   public DefaultMutableTreeNode engine_limitations;   public DefaultMutableTreeNode objects;   public DefaultMutableTreeNode objects_catalogs;   public DefaultMutableTreeNode objects_catalogs_default;   public DefaultMutableTreeNode objects_catalogs_default_tables;   public DefaultMutableTreeNode objects_catalogs_default_tables_system;   public DefaultMutableTreeNode objects_catalogs_default_tables_user;   public DefaultMutableTreeNode objects_catalogs_default_tables_x_table;   public DefaultMutableTreeNode objects_catalogs_default_procedures;   public DefaultMutableTreeNode objects_catalogs_default_procedures_x_procedure;   public DefaultMutableTreeNode tools;   public DefaultMutableTreeNode tools_isql;   public Navigator(Mainframe mf) {     this.mf = mf;     setLayout(new BorderLayout());     root = new DefaultMutableTreeNode("Database");     addTopNodes(root);     tree = new JTree(root);     JScrollPane pane = new JScrollPane();     pane.getViewport().add(tree);     add(pane, BorderLayout.CENTER);     tree.setCellRenderer(new MyRenderer());     tree.putClientProperty("JTree.lineStyle", "Angled");     MouseListener ml = new MouseAdapter() {       public void mouseClicked(MouseEvent e) {          int selRow = tree.getRowForLocation(e.getX(), e.getY());          TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());          if(selRow != -1) {            System.out.println(selPath.toString());            Object[] nodes = selPath.getPath();            String[] path = new String[nodes.length];            for (int i=0; i<nodes.length; i++) {              path[i] = ((DefaultMutableTreeNode) nodes[i]).toString();            }            DatabaseConnection conn = DatabaseConnection.getInstance();            try {              if (conn == null || !conn.getInstance().isActive() ||                   path.length == 1) { return; }              if (path[1].equals("Session")) {                showTable(conn.getSession());              } else if ((path.length == 3) && (path[1].equals("Engine"))) {                if (path[2].equals("Info")) {                  showTable(conn.getEngineInfo());                } else if (path[2].equals("Specs")) {                  showTable(conn.getEngineSpecs());                } else if (path[2].equals("Features")) {                  showTable(conn.getEngineFeatures());                } else if (path[2].equals("Limitations")) {                  showTable(conn.getEngineLimitations());                }              } else if ((path.length == 3) && (path[2].equals("Catalogs"))) {                // refresh catalog nodes                addCatalogs(conn.getCatalogs());              } else if ((path.length == 6) && (path[4].equals("Tables"))) {                // refresh tables in catalog                addTables((DefaultMutableTreeNode) selPath.getLastPathComponent(),                           conn.getTables(path[3],                           path[5].equals("User")?"TABLE":"SYSTEM TABLE"));                tree.treeDidChange();              } else if ((path.length == 7) && (path[4].equals("Tables"))) {                // display table content                String cat = !path[3].equals("")? path[3] + "..":"";                showTable(conn.getAllResultSetColumns(                    conn.getResultSet("SELECT * FROM " + cat + path[6])));              } else if ((path.length == 8) && (path[4].equals("Tables")) &&                          (path[7].equals("Columns"))) {                // display table columns                showTable(conn.getTableColumns(path[3], path[6]));              } else if ((path.length == 8) && (path[4].equals("Tables")) &&                          (path[7].equals("Primary Keys"))) {                // display primary key                showTable(conn.getTablePrimaryKeys(path[3], path[6]));              } else if ((path.length == 8) && (path[4].equals("Tables")) &&                          (path[7].equals("Imported Keys"))) {                // display imported keys                showTable(conn.getTableImportedKeys(path[3], path[6]));              } else if ((path.length == 8) && (path[4].equals("Tables")) &&                          (path[7].equals("Exported Keys"))) {                // display exported keys                showTable(conn.getTableExportedKeys(path[3], path[6]));              } else if ((path.length == 5) && (path[4].equals("Procedures"))) {                // refresh procedures in catalog                addProcedures((DefaultMutableTreeNode)                               selPath.getLastPathComponent(),                               conn.getProcedures(path[3]));                tree.treeDidChange();              } else if ((path.length == 6) && (path[4].equals("Procedures"))) {                // display procedure content                showTable(conn.getProcedureColumns(path[3], path[5]));              } else if ((path.length == 3) && (path[2].equals("ISQL"))) {                showISQL();              }            } catch (Exception ex) {              ex.printStackTrace();              showError(ex);            }          }       }     };     tree.addMouseListener(ml);   }   public void showTable(String[][] data) {     mf.showTable(data);   }   public void showError(Exception e) {     mf.showError(e);   }   public void showISQL() {     mf.jMenuFileSQL_actionPerformed(null);   }   public void addCatalogs(String[] catalogs) {     objects_catalogs.removeAllChildren();     for (int i=0; i<catalogs.length; i++) {       objects_catalogs_default = new DefaultMutableTreeNode(catalogs[i]);       objects_catalogs.add(objects_catalogs_default);       objects_catalogs_default_tables = new DefaultMutableTreeNode("Tables");       objects_catalogs_default.add(objects_catalogs_default_tables);       objects_catalogs_default_tables_system =            new DefaultMutableTreeNode("System");       objects_catalogs_default_tables.add(objects_catalogs_default_tables_system);       objects_catalogs_default_tables_user = new DefaultMutableTreeNode("User");       objects_catalogs_default_tables.add(objects_catalogs_default_tables_user);       objects_catalogs_default_procedures =            new DefaultMutableTreeNode("Procedures");       objects_catalogs_default.add(objects_catalogs_default_procedures);     }   }   public void addTables(DefaultMutableTreeNode hook, String[] tables) {     hook.removeAllChildren();     for (int i=0; i<tables.length; i++) {       objects_catalogs_default_tables_x_table =            new DefaultMutableTreeNode(tables[i]);       objects_catalogs_default_tables_x_table.add(           new DefaultMutableTreeNode("Columns"));       objects_catalogs_default_tables_x_table.add(           new DefaultMutableTreeNode("Primary Keys"));       objects_catalogs_default_tables_x_table.add(           new DefaultMutableTreeNode("Imported Keys"));       objects_catalogs_default_tables_x_table.add(           new DefaultMutableTreeNode("Exported Keys"));       hook.add(objects_catalogs_default_tables_x_table);     }   }   public void addProcedures(DefaultMutableTreeNode hook, String[] procedures) {     hook.removeAllChildren();     for (int i=0; i<procedures.length; i++) {       objects_catalogs_default_procedures_x_procedure =            new DefaultMutableTreeNode(procedures[i]);       hook.add(objects_catalogs_default_procedures_x_procedure);     }   }   public void addTopNodes(DefaultMutableTreeNode root) {     session = new DefaultMutableTreeNode("Session");     engine = new DefaultMutableTreeNode("Engine");     engine_info = new DefaultMutableTreeNode("Info");     engine.add(engine_info);     engine_specs = new DefaultMutableTreeNode("Specs");     engine.add(engine_specs);     engine_features = new DefaultMutableTreeNode("Features");     engine.add(engine_features);     engine_limitations = new DefaultMutableTreeNode("Limitations");     engine.add(engine_limitations);     objects = new DefaultMutableTreeNode("Objects");     objects_catalogs = new DefaultMutableTreeNode("Catalogs");     objects.add(objects_catalogs);     String[] def = { "" };     addCatalogs(def);     addCatalogs(def);     addCatalogs(def);     tools = new DefaultMutableTreeNode("Tools");     tools_isql = new DefaultMutableTreeNode("ISQL");     tools.add(tools_isql);     root.add(session);     root.add(engine);     root.add(objects);     root.add(tools);   }     class MyRenderer extends DefaultTreeCellRenderer {       ImageIcon rootIcon;       ImageIcon tableIcon;       ImageIcon sessionIcon;       ImageIcon docIcon;       ImageIcon dbIcon;       ImageIcon isqlIcon;       ImageIcon keyIcon;       ImageIcon pkIcon;       ImageIcon objectIcon;       ImageIcon blueIcon;       ImageIcon redIcon;       ImageIcon greenIcon;       ImageIcon magentaIcon;       public MyRenderer() {          rootIcon =             new ImageIcon(jdbcexplorer.Mainframe.class.getResource("db.gif"));         tableIcon =            new ImageIcon(jdbcexplorer.Mainframe.class.getResource("table.gif"));         sessionIcon =            new ImageIcon(jdbcexplorer.Mainframe.class.getResource("session.gif"));         docIcon =            new ImageIcon(jdbcexplorer.Mainframe.class.getResource("archivs.gif"));         dbIcon =            new ImageIcon(jdbcexplorer.Mainframe.class.getResource("db.gif"));         isqlIcon =            new ImageIcon(jdbcexplorer.Mainframe.class.getResource("isql.gif"));         keyIcon =            new ImageIcon(jdbcexplorer.Mainframe.class.getResource("key.gif"));         pkIcon =            new ImageIcon(jdbcexplorer.Mainframe.class.getResource("pk.gif"));         objectIcon =           new ImageIcon(jdbcexplorer.Mainframe.class.getResource("object.gif"));         blueIcon =            new ImageIcon(jdbcexplorer.Mainframe.class.getResource("blue.gif"));         redIcon =            new ImageIcon(jdbcexplorer.Mainframe.class.getResource("red.gif"));         greenIcon =            new ImageIcon(jdbcexplorer.Mainframe.class.getResource("green.gif"));         magentaIcon =            new ImageIcon(jdbcexplorer.Mainframe.class.getResource("magenta.gif"));      }      public Component getTreeCellRendererComponent(JTree tree, Object value,        boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {        super.getTreeCellRendererComponent(tree, value, sel, expanded,                                            leaf, row, hasFocus);        if (((DefaultMutableTreeNode) value).toString().equals("Database")) {           setIcon(rootIcon);        } else if (((DefaultMutableTreeNode) value).toString().equals("Session")) {           setIcon(sessionIcon);        } else if (((DefaultMutableTreeNode) value).toString().equals("Engine")) {           setIcon(docIcon);        } else if (((DefaultMutableTreeNode) value).toString().equals("Info")) {           setIcon(redIcon);        } else if (((DefaultMutableTreeNode) value).toString().equals("Specs")) {           setIcon(blueIcon);        } else if (((DefaultMutableTreeNode) value).toString().equals("Features")) {           setIcon(greenIcon);        } else if (           ((DefaultMutableTreeNode) value).toString().equals("Limitations")) {           setIcon(magentaIcon);        } else if (           ((DefaultMutableTreeNode) value).toString().equals("Catalogs")) {           setIcon(dbIcon);        } else if (((DefaultMutableTreeNode) value).getLevel() == 4) {           setIcon(objectIcon);         } else if (            ((DefaultMutableTreeNode) value).toString().equals("Primary Keys")) {           setIcon(pkIcon);         } else if (            ((DefaultMutableTreeNode) value).toString().endsWith("Keys")) {           setIcon(keyIcon);        } else if (((DefaultMutableTreeNode) value).toString().equals("ISQL")) {           setIcon(isqlIcon);        } else if (((DefaultMutableTreeNode) value).getLevel() == 6) {           setIcon(tableIcon);        }        return this;      }    } } 
end example

Listing 12-10: SQLCommandBox.java

start example
package jdbcexplorer; import javax.swing.*; import java.awt.*; import java.awt.event.*; /**  * Title:        SQLCommandBox  * Description:  * Company:  * @author Bernard Van Haecke  * @version 2.0 */ public class SQLCommandBox extends JDialog {   BorderLayout borderLayout2 = new BorderLayout();   JPanel jPanel1 = new JPanel();   JButton jButton1 = new JButton();   JButton jButton2 = new JButton();   JScrollPane jScrollPane1 = new JScrollPane();   JTextPane jTextPane1 = new JTextPane();   static String sql = "SELECT * FROM TEST";   Mainframe mf;   public SQLCommandBox(Mainframe parent) {     super((Frame) parent);     mf = parent;     enableEvents(AWTEvent.WINDOW_EVENT_MASK);     try {       jbInit();     }     catch(Exception e) {       e.printStackTrace();     }     pack();   }   private void jbInit() throws Exception {     this.getContentPane().setLayout(borderLayout2);     jButton1.setText("Execute");     jButton1.addActionListener(new java.awt.event.ActionListener() {       public void actionPerformed(ActionEvent e) {         jButton1_actionPerformed(e);       }     });     jButton2.setText("Close");     jButton2.addActionListener(new java.awt.event.ActionListener() {       public void actionPerformed(ActionEvent e) {         jButton2_actionPerformed(e);       }     });     this.setTitle("SQL Command");     jScrollPane1.setHorizontalScrollBarPolicy(            JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);     jScrollPane1.setVerticalScrollBarPolicy(            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);     jScrollPane1.setPreferredSize(new Dimension(400, 150));     jTextPane1.setBackground(Color.black);     jTextPane1.setFont(new java.awt.Font("Monospaced", 0, 12));     jTextPane1.setForeground(Color.green);     jTextPane1.setPreferredSize(new Dimension(400, 200));     jTextPane1.setCaretColor(Color.white);     jTextPane1.setText(sql);     this.getContentPane().add(jPanel1, BorderLayout.SOUTH);     jPanel1.add(jButton1, null);     jPanel1.add(jButton2, null);     this.getContentPane().add(jScrollPane1, BorderLayout.CENTER);     jScrollPane1.getViewport().add(jTextPane1, null);   }   public void showTable(String[][] data) {     mf.showTable(data);   }   public void showError(Exception e) {     mf.showError(e);   }   void jButton1_actionPerformed(ActionEvent e) {     try {       sql = jTextPane1.getText();       DatabaseConnection conn = DatabaseConnection.getInstance();       if (conn == null || !conn.getInstance().isActive()) { return; }       //showTable(conn.getAllResultSetColumns(conn.getResultSet(sql)));       showTable(conn.executeComplexQuery(sql));     } catch (Exception ex) {       showError(ex);     }   }   void jButton2_actionPerformed(ActionEvent e) {     this.dispose();   } }
end example



JDBC 3. 0. JAVA Database Connectivity
JDBC 3: Java Database Connectivity
ISBN: 0764548751
EAN: 2147483647
Year: 2002
Pages: 148

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net