import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.text.MessageFormat;

import jet.bean.JRCatalog;
import jet.bean.JRCatalogException;
import jet.universe.ConnectionDesc;
import jet.universe.JetUUniverse;


/**
 * The class can test the Catalog Bean installed on your computer with JReport Designer and JReport Server.  
 * It demonstrates almost all methods of the Catalog Bean.
 */
public class TestCatalogBean extends Frame implements ActionListener,
                                               ItemListener
{
	// For NT System.
    public static int txtHeight= 20;
    
	/**
     * Create a Catalog Bean instance.
     */
	JRCatalog bean = new JRCatalog();  
	
    /**
     * Controls.
     */
    Menu fileMenu;
    Menu operMenu;
    Menu windowMenu;
    MenuItem menuItem;

    CheckboxMenuItem levelOff;
    CheckboxMenuItem levelDebug;
    CheckboxMenuItem levelError;

    MenuItem codeMenu;
    String[] strFileSubMenu = { "Set Home Directory...",
                                "Get Home Directory",
                                "Set Catalog Name...",
                                "Get Catalog Name",
								"-",
                                "New Catalog",
                                "Load Catalog",
                                "Close Catalog",
                                "-",
                                "Save Catalog",
                                "Save As Catalog",
                                "-",
                                "Set Log File Name..."};
    String[] strOperSubMenu = { "Add Connection...",
                              "Modify Connection...",
                              "Modify User Infomation...",
							  "Delete Connection",
                              "Get Connection Description",
                              "-",
                              "Add Tables...",
							  "-",
							  "Add WHERE portion...",
                              "Modify WHERE portion...",
                              "Delete WHERE portion...",
                              "Get WHERE portion String...",
                              "-",
                              "Add File Query...",
                              "Delete File Query...",
                              "Get File Query String..."
							  };
    
    String strNewCatalog = "try '{'\n\tbean.newCatalog();\n'}'\n";
    String strLoadCatalog = "try '{'\n\tbean.loadCatalog();\n'}'\n";
    String strCloseCatalog = "try '{'\n\tbean.closeCatalog();\n'}'\n";
    String strSaveCatalog = "try '{'\n\tbean.saveCatalog();\n'}'\n";
    String strSaveCatalogAs = "try '{'\n\tbean.saveCatalogAs(\"{0}\");\n'}'\n";
    String strSetCatName = "bean.setCatName(\"{0}\");\n";
    String strGetCatName = "String strCatName; \nstrCatName = bean.getCatName();\n";
    String strSetHomeDir = "bean.setReportHome(\"{0}\");\n";
    String strGetHomeDir = "String strReportHome; \nstrReportHome = bean.getReportHome();\n";
    String strSetLogFile = "bean.setLogFile(\"{0}\");\n";
    String strSetInfoLevel = "// Set show infomation level.\nbean.setShowInfoLevel(bean.v{0});\n";
    String strAddConnection = "ConnectionDesc conDesc = new ConnectionDesc();\n" +                              
                           "conDesc.strName = \"{0}\";\n" + 
                           "conDesc.strURL = \"{1}\";\n" + 
                           "conDesc.strUser = \"{2}\";\n" + 
                           "conDesc.strPassword = \"{3}\";\n" + 
                           "conDesc.strDriver = \"{4}\";\n" + 
                           "try '{'\n\tbean.addConnection(conDesc);\n'}'\n";
    String strModifyConnection = "ConnectionDesc conDesc = new ConnectionDesc();\n" +                              
                           "conDesc.strName = \"{0}\";\n" + 
                           "conDesc.strURL = \"{1}\";\n" + 
                           "conDesc.strUser = \"{2}\";\n" + 
                           "conDesc.strPassword = \"{3}\";\n" + 
                           "conDesc.strDriver = \"{4}\";\n" + 
                           "try '{'\n\tbean.modifyConnection(conDesc);\n'}'\n";
	String strModifyUserInfo = "try '{'\n\tbean.modifyUserInfo(\"{0}\", \"{1}\");\n'}'\n";
    String strDeleteConnection = "try '{'\n\tbean.deleteConnection();\n'}'\n";
    String strGetConnection = "ConnectionDesc conDesc;\nconDesc = bean.getConnectionDesc();\n";
    String strAddTables = "try '{'\n\tbean.addTableViews(\"{0}\", \"{1}\", \"{2}\", {3});\n'}'\n";
	String strAddWherePortion = "try '{'\n\tbean.addWherePortion(\"{0}\", \"{1}\", \"{2}\");\n'}'\n";
    String strModifyWherePortion = "try '{'\n\tbean.modifyWherePortion(\"{0}\", \"{1}\", \"{2}\");\n'}'\n";
    String strDeleteWherePortion = "try '{'\n\tbean.deleteWherePortion(\"{0}\")\n'}'\n";
    String strGetWherePortion = "try '{'\n\tbean.getWherePortionsSQL(\"{0}\")\n'}'\n";
    String strAddFileQuery = "try '{'\n\tbean.addFileQuery(\"{0}\", new File(\"{1}\"));\n'}'\n";
    String strDeleteFileQuery = "try '{'\n\tbean.deleteFileQuery(\"{0}\");\n'}'\n";
    String strGetFileQuery = "String strSQL;\nstrSQL = bean.getFileQuerySQL(\"{0}\");\n";
	String strAddSFDataSource = "try '{'\n\tbean.addSFDataSource(\"{0}\", \"{1}\", \"{2}\", {3});\n'}'\n";
	String strRemoveSFDataSource = "try '{'\n\tbean.removeSFDataSource(\"{0}\")\n'}'\n";
    
    Panel panel;
    
    // A panel that displays errors. 
    SubPanel dataPnl = new SubPanel("Errors detail output:",Color.white);
    
    // A panel that displays Java code.
    SubPanel codePnl = new SubPanel("Java code:",Color.white);
    
    // Status panel.
    Panel statusPnl;
    
    // A label that displays status text.
    Label statusLab;

    // Report home directory.
    String strReportHome;

    // Catalog file name.
    String strCatalogName;

    // One part of output code.
    String strOutput = "";
    String strProcException = "catch (JRCatalogException e) { \n" +
                        "\tSystem.out.println(e.getMessage()); \n}\n";
    
    /**
     * Constructor.
     */
	TestCatalogBean()
	{
		super("Test Catalog Bean - ");
		initControls();
		getSystemInfo();
    }

	void getSystemInfo()
	{
		if(System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") == -1)
		{
			txtHeight = 40;
		}
	}

    /**
     * Invoked by initControls().
     */
    void initMenu()
    {
        // Create Menu components.
        fileMenu = new Menu("File");
		operMenu = new Menu("Operation");
        windowMenu = new Menu("Window");

        // Create "File" sub menu.
        int fileCount = strFileSubMenu.length;
        for (int i = 0; i < fileCount; i++)
        {
            menuItem = new MenuItem(strFileSubMenu[i]);
            menuItem.addActionListener(this);
            fileMenu.add(menuItem);
        }

        Menu optionItem1 = new Menu("Show Information Level");

        levelOff = new CheckboxMenuItem("Off", true);
        levelOff.addItemListener(this);
        optionItem1.add(levelOff);
        levelDebug = new CheckboxMenuItem("Debug");
        levelDebug.addItemListener(this);
        optionItem1.add(levelDebug);
        levelError = new CheckboxMenuItem("Error");
        levelError.addItemListener(this);
        optionItem1.add(levelError);

        fileMenu.add(optionItem1);
        fileMenu.addSeparator();

        menuItem = new MenuItem("Exit");
        menuItem.addActionListener(this);
        fileMenu.add(menuItem);

        // Create "Operation" sub menu.
        int operCount = strOperSubMenu.length;
        for (int i = 0; i < operCount; i++)
        {
            menuItem = new MenuItem(strOperSubMenu[i]);
            menuItem.addActionListener(this);
            operMenu.add(menuItem);
        }
        
        // Create "Window" sub menu.
        codeMenu = new MenuItem("Hide code output");
        codeMenu.addActionListener(this);
        windowMenu.add(codeMenu);
        
        // Create Menu bar and add it to frame.
        MenuBar mb = new MenuBar();          
		mb.add(fileMenu);
        mb.add(operMenu);            
        mb.add(windowMenu);

        //operMenu.setEnabled(false);
        setMenuBar(mb);
    }

    public void initControls()
    {
        setLayout(new BorderLayout());
		setBounds(0, 0, 450, 400);
        
        // Initiate Menu.
        initMenu();

        // Center part of BorderLayout.
        panel = new Panel();
        panel.setLayout(new GridLayout(0,1,1,1));
        panel.setBackground(Color.blue);

        panel.add(dataPnl);
        panel.add(codePnl);
        
        add(panel,BorderLayout.CENTER);

        // South part of BorderLayout.
        statusPnl = new Panel(new FlowLayout(FlowLayout.LEFT,0,0));
        statusPnl.setBackground(Color.lightGray);
        statusLab = new Label("Ready!");
        statusPnl.add(statusLab);

        add(statusPnl,BorderLayout.SOUTH);

        addWindowListener(new WindowAdapter()
		{
			public void windowClosing(WindowEvent e) 
			{
				System.exit(0);
			}
		} );

        setVisible(true);
	}

    /**
     * Implements the interface: ItemListener.
     * Switch the show information level between Off, Debug and Error.
     */
    public void itemStateChanged(ItemEvent e)
    {
        levelOff.setState(false);
        levelDebug.setState(false);
        levelError.setState(false);       
        Object source = e.getSource();
        ((CheckboxMenuItem)source).setState(true);
       
        codePnl.setOutput("// Set show information level.\n" + 
                              "bean.setShowInfoLevel(bean.v" +
                              ((CheckboxMenuItem)source).getLabel() + 
                              ");\n"); 
    }

    /**
     * Implement the interface: ActionListener.
     */
    public void actionPerformed(ActionEvent e)
	{
        setStatus("Waiting...");
        
        // Clear the error output window.
        dataPnl.setOutput("");
        
        // If the action is a Menu command.
		String label = e.getActionCommand();
        strOutput = "// " + label + ".\n";
		try
        {
            // Execute method corresponding with the menu.
            if ( label.equals("New Catalog") )
		    {
                newCatalog();
            }
		    else if ( label.equals("Load Catalog") )
		    {
                loadCatalog();
            }
		    else if ( label.equals("Save Catalog") )
		    {
                saveCatalog();
            }
            else if ( label.equals("Save As Catalog") )
		    {
                saveCatalogAs();
            }
		    else if ( label.equals("Close Catalog") )
		    {
                closeCatalog();
            }
		    else if ( label.equals("Set Home Directory...") )
		    {
                setHomeDir();
            }
            else if ( label.equals("Set Catalog Name...") )
		    {
                setCatName();
            }
            else if ( label.equals("Set Log File Name...") )
		    {
                setLogFile();
            }
            else if ( label.equals("Add Connection...") )
		    {
		        addConnection();	
            }
            else if ( label.equals("Modify Connection...") )
		    {
		        modifyConnection();
            }
			else if ( label.equals("Modify User Infomation...") )
		    {
		        modifyUserInfo();
            }
			else if ( label.equals("Delete Connection") )
		    {
		        deleteConnection();
            }
            else if ( label.equals("Set Home Directory...") )
		    {
                setHomeDir();
			}
			else if ( label.equals("Add Tables...") )
		    {
                addTableViews();
			}
		    else if (label.equals("Add WHERE portion..."))
		    {
		        addWherePortion();    
            }
            else if (label.equals("Modify WHERE portion..."))
		    {
		        modifyWherePortion();    
            }
            else if (label.equals("Delete WHERE portion..."))
		    {
		        deleteWherePortion();
            }
            else if (label.equals("Add File Query..."))
		    {
		        addFileQuery();
            }
            else if (label.equals("Delete File Query..."))
		    {
		        deleteFileQuery();
            }
            else if (label.equals("Exit"))
            {
                dispose();
                System.exit(0);
            }
            else if (label.equals("Get Home Directory"))
            {
                getReportHome();
            }
            else if (label.equals("Get Catalog Name"))
            {
                getCatName();
            }
            else if (label.equals("Get Connection Description"))
            {
                getConnectionDesc();
            }
            else if (label.equals("Get WHERE portion String..."))
            {
                getWherePortion();
            }
            else if (label.equals("Get File Query String..."))
            {
                getFileQuerySQL();
            }
            else if (label.equals(codeMenu.getLabel()))
            {
                clickCode();
                strOutput = "";
            }
            
            if (codePnl.isShowing())
            {
                codePnl.setOutput(strOutput);
            }
            
            setStatus("Success!");
        }
        catch(JRCatalogException je)
        {
            setStatus("Error!");
            codePnl.setOutput(strOutput);
            dataPnl.setOutput(je.getMessage()+"\n");
        }
    }

    protected void setStatus(String strStatus)
    {
        statusLab.setText(strStatus);
    }
    /**
     * Display a File Dialog.
     *
     * @return file name.  (include path and name)
     */
    protected String getFile()
    {
        FileDialog inFileDialog=new FileDialog(this,"Select File");
		inFileDialog.setDirectory(strReportHome);
		inFileDialog.setFile("*.*");
		inFileDialog.setVisible(true);
		String inFileName = inFileDialog.getFile();
		if (inFileName != null)
		{
			return inFileDialog.getDirectory()+inFileName;
        }
        return null;
    }

    /*********************************************************************/
    /******************************** Menu method ************************/    
    /*********************************************************************/
    
    /**
     * Build a new catalog.  The report home name and catalog file name are
     * needed.
     */
    protected void newCatalog() throws JRCatalogException
    {
        strOutput = strOutput +  
                    MessageFormat.format(strNewCatalog, new String[]{}) + 
                    strProcException;
        bean.newCatalog();
    }

    /**
     * Load a existing catalog.  The catalog file name must be a existing 
     * catalog file.
     */
    public void loadCatalog() throws JRCatalogException
    {
        strOutput = strOutput +  MessageFormat.format(strLoadCatalog, new String[]{}) + strProcException;
        bean.loadCatalog();
    }
        
    /**
     * Save the catalog file.
     */
    public void saveCatalog() throws JRCatalogException
    {
        strOutput = strOutput + MessageFormat.format(strSaveCatalog, new String[]{}) + strProcException;
        bean.saveCatalog();
    }

    /**
     * Save the catalog file as. 
     */
    public void saveCatalogAs() throws JRCatalogException
    {
        String strName = getFile();
        strOutput = strOutput +  MessageFormat.format(strSaveCatalogAs, new String[]{strName}) + strProcException;
        bean.saveCatalogAs(strName);
    }
    
    /**
     * Close the catalog.  Free the resources used by catalog.
     */
    public void closeCatalog() throws JRCatalogException
    {
        strOutput = strOutput +  MessageFormat.format(strCloseCatalog, new String[]{}) + strProcException;
        bean.closeCatalog();
    }
    
    /**
     * Set report home directory.
     */
    public void setHomeDir() 
    {
        InputNameDialog inputDlg = new InputNameDialog(this, "Set Home Directory");
        String strName = "";
        if (inputDlg.isOK())
        {
            
            strName = inputDlg.getName();
            strOutput = strOutput + MessageFormat.format(strSetHomeDir, new String[]{strName})+ "\n";
            bean.setReportHome(strName);
            inputDlg.dispose();
        }
        else
        {
            strOutput = "";
        }
        
    }

    /**
     * Set catalog file name.
     */
    public void setCatName()
    {
        InputNameDialog inputDlg = new InputNameDialog(this, "Set Catalog Filename");
        String strName = "";
        if (inputDlg.isOK())
        {
            strName = inputDlg.getName();
            strOutput = strOutput +  MessageFormat.format(strSetCatName, new String[]{strName});
            bean.setCatName(strName);
            setTitle("Test Catalog Name - " + strName);
            inputDlg.dispose();
        }
        else
        {
            strOutput = "";
        }
    }

    /**
     * Set current log file.
     */
    public void setLogFile()
    {
       String fileName = getFile();
       if (fileName != null)
       {
           strOutput = strOutput +  MessageFormat.format(strSetLogFile, new String[]{fileName});  
           bean.setLogFile(fileName); 
       }
       else
       {
            strOutput = "";
       }
    }

    /**
     * Add a connection to catalog.  
     */
    public void addConnection() throws JRCatalogException
    {
        InputConnectionDialog conDlg = new InputConnectionDialog(this, "Add Connection");
		conDlg.setVisible(true);
        ConnectionDesc conDesc = new ConnectionDesc();
        boolean bIsOK = conDlg.isOK();
        if (bIsOK)
        {
            conDesc = conDlg.getConnectionDesc();
            strOutput = strOutput +  
                        MessageFormat.format(strAddConnection, 
                                            new String[]{conDesc.strName,
                                                         conDesc.strURL,
                                                         conDesc.strUser,
                                                         conDesc.strPassword,
                                                         conDesc.strDriver})+ 
                        strProcException;
            bean.addConnection(conDesc);
            conDlg.dispose();
        }
        else
        {
            strOutput = "";
        }
    }
    
    /**
     * Modify the connection of catalog.  If there are some errors during
     * modifying the connection, the connection will still keep the changes.
     */
    public void modifyConnection() throws JRCatalogException
    {
        InputConnectionDialog conDlg;
		ConnectionDesc conDesc = bean.getConnectionDesc();
		if (conDesc != null)
		{
			conDlg = new InputConnectionDialog(this, "Modify Connection", conDesc);
		}
		else
		{
			conDlg = new InputConnectionDialog(this, "Modify Connection");
		}
        
		conDlg.setVisible(true);
        boolean bIsOK = conDlg.isOK();
        if (bIsOK)
        {
            conDesc = conDlg.getConnectionDesc();    
            strOutput = strOutput +  
                        MessageFormat.format(strModifyConnection, 
                                            new String[]{conDesc.strName,
                                                         conDesc.strURL,
                                                         conDesc.strUser,
                                                         "****",
                                                         conDesc.strDriver})+ 
                        strProcException;
            bean.modifyConnection(conDlg.getConnectionDesc());
            conDlg.dispose();
        }
        else
        {
            strOutput = "";
        }

        
    }

    public void modifyUserInfo() throws JRCatalogException
    {
        InputConnectionDialog conDlg;
		ConnectionDesc conDesc = bean.getConnectionDesc();
		if (conDesc != null)
		{
			conDlg = new InputConnectionDialog(this, "Modify Connection", conDesc);
		}
		else
		{
			conDlg = new InputConnectionDialog(this, "Modify Connection");
		}

		
		conDlg.nameFld.setEnabled(false);
		conDlg.URLFld.setEnabled(false);
		conDlg.driverFld.setEnabled(false);
		conDlg.setVisible(true);

        boolean bIsOK = conDlg.isOK();
        if (bIsOK)
        {
            conDesc = conDlg.getConnectionDesc();    
            strOutput = strOutput +  
                        MessageFormat.format(strModifyUserInfo, 
                                            new String[]{conDesc.strUser,
                                                         conDesc.strPassword})+ 
                        strProcException;
            bean.modifyUserInfo(conDesc.strUser, conDesc.strPassword);
            conDlg.dispose();
        }
        else
        {
            strOutput = "";
        }

        
    }


    public void deleteConnection() throws JRCatalogException
    {
        strOutput = strOutput +  MessageFormat.format(strDeleteConnection,
                                 new String[]{}) + strProcException;
        bean.deleteConnection();
    }

	public void addTableViews() throws JRCatalogException
    {
        AddTablesDialog addTableDlg = new AddTablesDialog(this, "Add Tables");
        addTableDlg.setVisible(true);

		String strCatalogName = null;
        String strSchemaPattern = null;
		String strTablePattern = "%";
		int iType = JetUUniverse.TYPE_TABLE;

        boolean bIsOK = addTableDlg.isOK();
        if (bIsOK)
        {
            strCatalogName = addTableDlg.getCatalogName();
            strSchemaPattern = addTableDlg.getSchemaPattern();
			strTablePattern = addTableDlg.getTablePattern();
			iType = addTableDlg.getTableType();

            strOutput = strOutput +  
                    MessageFormat.format(strAddTables,
                            new String[]{strCatalogName, 
										 strSchemaPattern,
										 strTablePattern,
										 String.valueOf(iType)}) + strProcException;
            bean.addTableViews(  strCatalogName, 
								 strSchemaPattern,
								 strTablePattern,
								 iType);
            addTableDlg.dispose();
        }
        else
        {
            strOutput = "";
        }
    }

    /**
     * Add a WHERE portion string into catalog.
     * There is another method available that can add structure type WHERE portion.
     */
    public void addWherePortion() throws JRCatalogException
    {
        InputWherePortionDialog inputDlg = new InputWherePortionDialog(this, "Input WHERE Portion");
        String strName = "";
        String strQueryName = "";
        String strSQL = "";
        boolean bIsOK = inputDlg.isOK();
        if (bIsOK)
        {
            strName = inputDlg.getName();
            strQueryName = inputDlg.getQueryName();
            strSQL = inputDlg.getSQL();
            strOutput = strOutput +  
                        MessageFormat.format(strAddWherePortion,
                            new String[]{strName, strQueryName, strSQL}) + 
                        strProcException;
            bean.addWherePortion( strName,strQueryName,strSQL); 
            inputDlg.dispose();
        }
        else
        {
            strOutput = "";
        }
    }

    public void modifyWherePortion() throws JRCatalogException
    {
        InputWherePortionDialog inputDlg = new InputWherePortionDialog(this, "Input WHERE Portion");
        String strName = "";
        String strQueryName = "";
        String strSQL = "";
        boolean bIsOK = inputDlg.isOK();
        if (bIsOK)
        {
            strName = inputDlg.getName();
            strQueryName = inputDlg.getQueryName();
            strSQL = inputDlg.getSQL();
            strOutput = strOutput +  
                        MessageFormat.format(strModifyWherePortion,
                            new String[]{strName, strQueryName, strSQL}) + 
                        strProcException;
            bean.modifyWherePortion( strName,strQueryName,strSQL); 
            inputDlg.dispose();
        }
        else
        {
            strOutput = "";
        }
    }

    /**
     * Delete a named WHERE portion.  A existing name must be given.
     */
    public void deleteWherePortion() throws JRCatalogException
    {
        InputNameDialog delDlg = new InputNameDialog(this, "Delete WHERE portion");
        String strName = "";
        boolean bIsOK = delDlg.isOK();
        if (bIsOK)
        {
            strName = delDlg.getName();
            strOutput = strOutput + 
                    MessageFormat.format(strDeleteWherePortion,
                        new String[]{strName}) + 
                    strProcException;
            bean.deleteWherePortion(delDlg.getName());
            delDlg.dispose();
        }
        else
        {
            strOutput = "";
        }
    }

    /**
     * Add a file query into catalog.
     */
    public void addFileQuery() throws JRCatalogException
    {
        AddFileQueryDialog addFileQueryDlg = new AddFileQueryDialog(this, "Add File Query");
        String strName = "";
        String strFileName = "";
        boolean bIsOK = addFileQueryDlg.isOK();
        if (bIsOK)
        {
            strName = addFileQueryDlg.getName();
            strFileName = addFileQueryDlg.getFileName();
            strOutput = strOutput +  
                    MessageFormat.format(strAddFileQuery,
                            new String[]{strName, strFileName}) +
                    strProcException;
            bean.addFileQuery( addFileQueryDlg.getName(), 
                               new File(strFileName));
            addFileQueryDlg.dispose();
        }
        else
        {
            strOutput = "";
        }
    }

    public void deleteFileQuery() throws JRCatalogException
    {
        InputNameDialog delDlg = new InputNameDialog(this, "Delete File Query");
        String strName = "";
        boolean bIsOK = delDlg.isOK();
        if (bIsOK)
        {
            strName = delDlg.getName();
            strOutput = strOutput + 
                    MessageFormat.format(strDeleteFileQuery,
                        new String[]{strName}) + 
                    strProcException;
            bean.deleteFileQuery(strName);
            delDlg.dispose();
        }
        else
        {
            strOutput = "";
        }
    }

    public void getReportHome()
    {
        String strReportHome = bean.getReportHome();
        dataPnl.setOutput(strReportHome);
        strOutput = strOutput +  
                    MessageFormat.format(strGetHomeDir,new String[]{}); 

    }   
    
    public void getCatName()
    {
        String strCatName = bean.getCatName();
        dataPnl.setOutput(strCatName);
        strOutput = strOutput +  
                    MessageFormat.format(strGetCatName,new String[]{}); 
    }

    public void getConnectionDesc() throws JRCatalogException
    {
        ConnectionDesc conDesc = bean.getConnectionDesc();
                
        // display the information in Text area.
        if (conDesc != null)
        {
            dataPnl.setOutput( "Name: " + conDesc.strName + "\n" +
                                "URL: " + conDesc.strURL + "\n" + 
                                "User: " + conDesc.strUser + "\n" +
                                "Password: " + conDesc.strPassword + "\n" +
                                "Driver: " + conDesc.strDriver);
        }
        else
        {
            dataPnl.setOutput("null");    
        }
        strOutput = strOutput +  
                    MessageFormat.format(strGetConnection,new String[]{}); 
    }

    public void getWherePortion() throws JRCatalogException
    {
        InputNameDialog inDlg = new InputNameDialog(this, "Get WHERE Portion");
        String strName = "";
        boolean bIsOK = inDlg.isOK();
        if (bIsOK)
        {
            strName = inDlg.getName();
            strOutput = strOutput +  
            MessageFormat.format(strGetWherePortion,new String[]{strName}); 
            dataPnl.setOutput(bean.getWherePortionsSQL(strName));
            inDlg.dispose();
        }
        else
        {
            strOutput = "";
        }
    }

    public void getFileQuerySQL() throws JRCatalogException
    {
        InputNameDialog inDlg = new InputNameDialog(this, "Get File Query");
        String strName = "";
        boolean bIsOK = inDlg.isOK();
        if (bIsOK)
        {
            strName = inDlg.getName();
            strOutput = strOutput + 
                    MessageFormat.format(strGetFileQuery,new String[]{strName}); 
            dataPnl.setOutput(bean.getFileQuerySQL(strName));
            inDlg.dispose();
        }
        else
        {
            strOutput = "";
        }
    }

    public void clickCode()
    {
        if (codeMenu.getLabel().equals("Hide code output"))
        {
            panel.remove(codePnl);
            if (panel.getComponentCount() > 0)
            {
                this.show();
            }
            codeMenu.setLabel("Show code output");
        }    
        else
        {
            panel.add(codePnl, -1);
            if (panel.getComponentCount() > 0)
            {
                this.show();
            }
            codeMenu.setLabel("Hide code output");
        }
    }

    /**
     * The main method of test program.
     */
	public static void main(String argv[])
	{
		new TestCatalogBean();
	}
}


/*********************** Dialog class ****************************/
/*****************************************************************/

class AddFileQueryDialog extends Dialog implements ActionListener
{
	Frame frame       = null;
	
	// Control definitions
	//--------------------------------------------------------------------------
	Button        btnOK;
	Button        btnCancel;
	Label         IDC_STATIC1;
	TextField     nameFld;
	Label         IDC_STATIC2;
	TextField     fileFld;
	Button        btnBrowse;

    // Data
    String strName = "";
    String strFileName = "";

    boolean bIsOK = false;
	// Constructor
	//--------------------------------------------------------------------------
	public AddFileQueryDialog (Frame frame, String strTitle)
	{
		super(frame, strTitle, true);
        this.frame = frame;
        CreateControls();
        show();
	}

	// Initialization.
	//--------------------------------------------------------------------------
	public void CreateControls()
	{
		setBackground(Color.white);
        setLayout(null);
		addNotify();
        setBounds(100,100,325,140);
        setResizable(false);
            
		// Control creation
		//----------------------------------------------------------------------
		nameFld = new TextField ("");
		add(nameFld);
		nameFld.setBounds(100, 35, 100, TestCatalogBean.txtHeight);

		btnOK = new Button ("OK");
		add(btnOK);
		btnOK.setBounds(260, 35, 50, TestCatalogBean.txtHeight);
        btnOK.addActionListener(this);

		btnCancel = new Button ("Cancel");
		add(btnCancel);
		btnCancel.setBounds(260, 85, 50, TestCatalogBean.txtHeight);
        btnCancel.addActionListener(this);

		IDC_STATIC1 = new Label ("Query Name:", Label.LEFT);
		add(IDC_STATIC1);
		IDC_STATIC1.setBounds(15, 35, 80, TestCatalogBean.txtHeight);

		
		IDC_STATIC2 = new Label ("Query File:", Label.LEFT);
		add(IDC_STATIC2);
		IDC_STATIC2.setBounds(15, 90, 80, TestCatalogBean.txtHeight);

		fileFld = new TextField ("");
		add(fileFld);
		fileFld.setBounds(100, 85, 100, TestCatalogBean.txtHeight);

		btnBrowse = new Button (". . .");
		add(btnBrowse);
		btnBrowse.setBounds(215, 85, 30, TestCatalogBean.txtHeight);
        btnBrowse.addActionListener(this);

    }

    /**
     * Implements the interface: ActionListener.
     */
	public void actionPerformed(ActionEvent e)
	{
		Object source = e.getSource();
		if (source == btnBrowse)
		{
			FileDialog inFileDialog=new FileDialog(frame,"catalog file");
			inFileDialog.show();
			String inFileName = inFileDialog.getFile();
			if (inFileName != null)
			{   
                fileFld.setText(inFileDialog.getDirectory()+inFileName);
            }
        }
        else if (source == btnOK)
        {
            strName = nameFld.getText();
            strFileName = fileFld.getText();
            bIsOK = true;
            setVisible(false);
        }
        else
        {
            dispose();
        }
    }

    public String getName()
    {
        return strName;
    }
    public String getFileName()
    {
        return strFileName;
    }
    public boolean isOK()
    {
        return bIsOK;
    }
    public void dispose()
    {
        btnOK.removeActionListener(this);
        btnCancel.removeActionListener(this);
        super.dispose();
    }
}

class InputNameDialog extends Dialog implements ActionListener
{
	// Control definitions
	//--------------------------------------------------------------------------
	Button        btnOK;
	Button        btnCancel;
	Label         IDC_STATIC1;
	TextField     nameFld;

    boolean bIsOK = false;
    String strName = "";

    
	// Constructor
	//--------------------------------------------------------------------------
	public InputNameDialog (Frame frame, String strTitle)
	{
		super(frame, strTitle, true);
        CreateControls();
        show();
    }

	// Constructor
	//--------------------------------------------------------------------------
	public InputNameDialog (Frame frame, String strTitle, String strName)
	{
		super(frame, strTitle, true);
		this.strName = strName;
        CreateControls();
        show();
    }

	// Initialization.
	//--------------------------------------------------------------------------
	public void CreateControls()
	{
		setBackground(Color.white);
        setLayout(null);
		addNotify();
        setBounds(100,100,300,140);
        setResizable(false);
        
        // Control creation
		//----------------------------------------------------------------------
		nameFld = new TextField (strName);
		add(nameFld);
		nameFld.setBounds(70, 35, 215, TestCatalogBean.txtHeight);
		
		btnOK = new Button ("OK");
		add(btnOK);
		btnOK.setBounds(170, 85, 50, TestCatalogBean.txtHeight);
        btnOK.addActionListener(this);

		btnCancel = new Button ("Cancel");
		add(btnCancel);
		btnCancel.setBounds(235, 85, 50, TestCatalogBean.txtHeight);
        btnCancel.addActionListener(this);

		IDC_STATIC1 = new Label ("name:", Label.LEFT);
		add(IDC_STATIC1);
		IDC_STATIC1.setBounds(15, 35, 50, TestCatalogBean.txtHeight);
    }

    public void actionPerformed(ActionEvent e)
	{
		Object source = e.getSource();
		if (source == btnOK)
		{
			strName = nameFld.getText();
            bIsOK = true;
            setVisible(false);
        }
        else 
        {
            dispose();
        }
    }

    public void dispose()
    {
        btnOK.removeActionListener(this);
        btnCancel.removeActionListener(this);
        super.dispose();
    }
    public String getName()
    {
        return strName;
    }

    public boolean isOK()
    {
        return bIsOK;
    }
    
}

class InputConnectionDialog extends Dialog implements ActionListener
{
	// Control definitions
	//--------------------------------------------------------------------------
	Button        btnOK;
	Button        btnCancel;
	Label         IDC_STATIC1;
	TextField     nameFld;
	Label         IDC_STATIC2;
	TextField     URLFld;
	Label         IDC_STATIC3;
	TextField     userFld;
	Label         IDC_STATIC4;
	TextField     passwordFld;
	Label         IDC_STATIC5;
	TextField     driverFld;

    boolean bIsOK = false;
    ConnectionDesc conDesc = new ConnectionDesc();

    
	// Constructor
	//--------------------------------------------------------------------------
	public InputConnectionDialog (Frame frame, String strTitle)
	{
		super(frame, strTitle, true);
        CreateControls();
    }

	// Constructor
	//--------------------------------------------------------------------------
	public InputConnectionDialog (Frame frame, 
								  String strTitle, 
								  ConnectionDesc conDesc)
	{
		this(frame, strTitle);
		nameFld.setText(conDesc.strName);
        URLFld.setText(conDesc.strURL);
        userFld.setText(conDesc.strUser);
        passwordFld.setText(conDesc.strPassword);
        driverFld.setText(conDesc.strDriver);
	}

	// Initialization.
	//--------------------------------------------------------------------------
	public void CreateControls()
	{
		setBackground(Color.white);
        setLayout(null);
		addNotify();
        setBounds(100,100,300,310);
        setResizable(false);

		// Control creation
		//----------------------------------------------------------------------
		nameFld = new TextField ("");
		add(nameFld);
		nameFld.setBounds(100, 35, 100, TestCatalogBean.txtHeight);
		
		btnOK = new Button ("OK");
		add(btnOK);
		btnOK.setBounds(230, 35, 50, TestCatalogBean.txtHeight);
        btnOK.addActionListener(this);

		btnCancel = new Button ("Cancel");
		add(btnCancel);
		btnCancel.setBounds(230, 85, 50, TestCatalogBean.txtHeight);
        btnCancel.addActionListener(this);

		IDC_STATIC1 = new Label ("Name:", Label.LEFT);
		add(IDC_STATIC1);
		IDC_STATIC1.setBounds(15, 35, 80, TestCatalogBean.txtHeight);

		IDC_STATIC2 = new Label ("URL:", Label.LEFT);
		add(IDC_STATIC2);
		IDC_STATIC2.setBounds(15, 90, 80, TestCatalogBean.txtHeight);

		URLFld = new TextField ("");
		add(URLFld);
		URLFld.setBounds(100, 90, 100, TestCatalogBean.txtHeight);

		IDC_STATIC4 = new Label ("User Name:", Label.LEFT);
		add(IDC_STATIC4);
		IDC_STATIC4.setBounds(15, 145, 80, TestCatalogBean.txtHeight);

		userFld = new TextField ("");
		add(userFld);
		userFld.setBounds(100, 145, 100, TestCatalogBean.txtHeight);

        IDC_STATIC3 = new Label ("Password:", Label.LEFT);
		add(IDC_STATIC3);
		IDC_STATIC3.setBounds(15, 200, 80, TestCatalogBean.txtHeight);

		passwordFld = new TextField ("");
		add(passwordFld);
		passwordFld.setBounds(100, 200, 100, TestCatalogBean.txtHeight);
		passwordFld.setEchoChar('*');

		IDC_STATIC5 = new Label ("Driver:", Label.LEFT);
		add(IDC_STATIC5);
		IDC_STATIC5.setBounds(15, 255, 80, TestCatalogBean.txtHeight);

		driverFld = new TextField ("");
		add(driverFld);
		driverFld.setBounds(100, 255, 100, TestCatalogBean.txtHeight);
    }

    public void actionPerformed(ActionEvent e)
	{
		Object source = e.getSource();
		if (source == btnOK)
		{
            conDesc.strName = nameFld.getText();
            conDesc.strURL = URLFld.getText();
            conDesc.strUser = userFld.getText();
            conDesc.strPassword = passwordFld.getText();
            conDesc.strDriver = driverFld.getText();
            bIsOK = true;
            setVisible(false);
        }
        else 
        {
            dispose();
        }
    }

    public void dispose()
    {
        btnOK.removeActionListener(this);
        btnCancel.removeActionListener(this);
        super.dispose();
    }

    public ConnectionDesc getConnectionDesc()
    {
        return conDesc;
    }

    public boolean isOK()
    {
        return bIsOK;
    }
}

class AddTablesDialog extends Dialog implements ActionListener
{
	// Control definitions
	//--------------------------------------------------------------------------
	Button        btnOK;
	Button        btnCancel;
	Label         IDC_STATIC1;
	TextField     catalogFld;
	Label         IDC_STATIC2;
	TextField     schemaFld;
	Label         IDC_STATIC3;
	TextField     tableFld;
	Label         IDC_STATIC4;
	Checkbox	  chkTable;
	Checkbox	  chkView;	

    boolean bIsOK = false;
    ConnectionDesc conDesc = new ConnectionDesc();

    
	// Constructor
	//--------------------------------------------------------------------------
	public AddTablesDialog (Frame frame, String strTitle)
	{
		super(frame, strTitle, true);
        CreateControls();
    }

	// Initialization.
	//--------------------------------------------------------------------------
	public void CreateControls()
	{
		setBackground(Color.white);
        setLayout(null);
		addNotify();
        setBounds(100,100,340,250);
        setResizable(false);

		// Control creation
		//----------------------------------------------------------------------
		catalogFld = new TextField ("");
		add(catalogFld);
		catalogFld.setBounds(140, 35, 100, TestCatalogBean.txtHeight);

		btnOK = new Button ("OK");
		add(btnOK);
		btnOK.setBounds(270, 35, 50, TestCatalogBean.txtHeight);
        btnOK.addActionListener(this);

		btnCancel = new Button ("Cancel");
		add(btnCancel);
		btnCancel.setBounds(270, 85, 50, TestCatalogBean.txtHeight);
        btnCancel.addActionListener(this);

		IDC_STATIC1 = new Label ("Catalog Name:", Label.LEFT);
		add(IDC_STATIC1);
		IDC_STATIC1.setBounds(15, 35, 120, TestCatalogBean.txtHeight);

		IDC_STATIC2 = new Label ("Schema Pattern:", Label.LEFT);
		add(IDC_STATIC2);
		IDC_STATIC2.setBounds(15, 90, 120, TestCatalogBean.txtHeight);

		schemaFld = new TextField ("");
		add(schemaFld);
		schemaFld.setBounds(140, 90, 100, TestCatalogBean.txtHeight);

		IDC_STATIC4 = new Label ("Table Name Pattern:", Label.LEFT);
		add(IDC_STATIC4);
		IDC_STATIC4.setBounds(15, 145, 120, TestCatalogBean.txtHeight);

		tableFld = new TextField ("");
		add(tableFld);
		tableFld.setBounds(140, 145, 100, TestCatalogBean.txtHeight);

        chkTable = new Checkbox("Table", true);
		chkView = new Checkbox("View", true);

		add(chkTable);
		add(chkView);

		chkTable.setBounds(15, 200, 80, TestCatalogBean.txtHeight);
		chkView.setBounds(100, 200, 80, TestCatalogBean.txtHeight);
    }

    public void actionPerformed(ActionEvent e)
	{
		Object source = e.getSource();
		if (source == btnOK)
		{
			bIsOK = true;
            setVisible(false);
        }
        else 
        {
            dispose();
        }
    }

    public void dispose()
    {
        btnOK.removeActionListener(this);
        btnCancel.removeActionListener(this);
        super.dispose();
    }

    public boolean isOK()
    {
        return bIsOK;
    }

	public String getCatalogName()
	{
		return catalogFld.getText().trim().length() == 0?null:catalogFld.getText();
	}

	public String getSchemaPattern()
	{
		return schemaFld.getText().trim().length() == 0?null:schemaFld.getText();
	}

	public String getTablePattern()
	{
		return tableFld.getText().trim().length() == 0?"%":tableFld.getText();
	}

	public int getTableType()
	{
		int iRetType = 0;
		if (chkTable.getState())
		{
			iRetType += JetUUniverse.TYPE_TABLE;
		}

		if (chkView.getState())
		{
			iRetType += JetUUniverse.TYPE_VIEW;
		}
		
		return iRetType;
	}
}

class InputWherePortionDialog extends Dialog implements ActionListener
{
	// Control definitions
	//--------------------------------------------------------------------------
	Button        btnOK;
	Button        btnCancel;
	Label         IDC_STATIC1;
	TextField     nameFld;
	Label         IDC_STATIC2;
	TextField     SQLFld;
    TextField queryNameFld;

    String strName = "";
    String strSQL = "";
    String strQueryName = "";
    
    boolean bIsOK = false;

    
	// Constructor
	//--------------------------------------------------------------------------
	public InputWherePortionDialog (Frame frame, String strTitle)
	{
		super(frame, strTitle, true);
        CreateControls();
        show();
	}

	// Initialization.
	//--------------------------------------------------------------------------
	public void CreateControls()
	{
		setBackground(Color.white);
        setLayout(null);
		addNotify();
        setBounds(100,100,310,255);
        setResizable(false);
        
        // Control creation
		//----------------------------------------------------------------------
		nameFld = new TextField ("");
		add(nameFld);
		nameFld.setBounds(195, 35, 100, TestCatalogBean.txtHeight);

		btnOK = new Button ("OK");
		add(btnOK);
		btnOK.setBounds(180, 200, 50, TestCatalogBean.txtHeight);
        btnOK.addActionListener(this);

		btnCancel = new Button ("Cancel");
		add(btnCancel);
		btnCancel.setBounds(245, 200, 50, TestCatalogBean.txtHeight);
        btnCancel.addActionListener(this);

        // WHERE portion mame. 
		IDC_STATIC1 = new Label ("WHERE portion name:", Label.LEFT);
		add(IDC_STATIC1);
		IDC_STATIC1.setBounds(15, 35, 130, TestCatalogBean.txtHeight);


        // WHERE portion query name.
        Label IDC_STATIC3 = new Label ("WHERE portion query name:", Label.LEFT);
		add(IDC_STATIC3);
		IDC_STATIC3.setBounds(15, 90, 160, TestCatalogBean.txtHeight);

		queryNameFld = new TextField ("");
		add(queryNameFld);
		queryNameFld.setBounds(195, 90, 100, TestCatalogBean.txtHeight);

        // WHERE portion string.
		IDC_STATIC2 = new Label ("WHERE portion string:", Label.LEFT);
		add(IDC_STATIC2);
		IDC_STATIC2.setBounds(15, 145, 130, TestCatalogBean.txtHeight);

		SQLFld = new TextField ("");
		add(SQLFld);
		SQLFld.setBounds(160, 145, 135, TestCatalogBean.txtHeight);
    }

    public void actionPerformed(ActionEvent e)
	{
		Object source = e.getSource();
		if (source == btnOK)
		{
			strName = nameFld.getText();
            strQueryName = queryNameFld.getText();
            strSQL = SQLFld.getText();
            bIsOK = true;
            setVisible(false);
        }
        else 
        {
            dispose();
        }
    }

    public String getName()
    {
        return strName;
    }

    public String getSQL()
    {
        return strSQL;
    }

    public String getQueryName()
    {
        return strQueryName;
    }

    public boolean isOK()
    {
        return bIsOK;
    }
    public void dispose()
    {
        btnOK.removeActionListener(this);
        btnCancel.removeActionListener(this);
        super.dispose();
    }
}

class InputDataSourceDialog extends Dialog implements ActionListener
{
	// Control definitions
	//--------------------------------------------------------------------------
	Button        btnOK;
	Button        btnCancel;
	TextField     nameFld;
	TextField     classFld;
    TextField controllerFld;
	Checkbox  chkIsCollection;

    String strName = "";
    String strClassName = "";
    String strControllerName = "";
	boolean bIsCollection = true;
    
    boolean bIsOK = false;

    
	// Constructor
	//--------------------------------------------------------------------------
	public InputDataSourceDialog (Frame frame, String strTitle)
	{
		super(frame, strTitle, true);
        CreateControls();
        show();
	}

	// Initialization.
	//--------------------------------------------------------------------------
	public void CreateControls()
	{
		setBackground(Color.white);
		setLayout(new BorderLayout());
		addNotify();
        setBounds(100,100,310,255);
        
        // Control creation
		//----------------------------------------------------------------------
		Panel p1 = new Panel();
		p1.setLayout(new GridLayout(1,2));
		
		nameFld = new TextField (strName);
		p1.add(new Label("DataSource Name:"));
		p1.add(nameFld);

		Panel p2 = new Panel();
		p2.setLayout(new GridLayout(1,2));
		
		classFld = new TextField (strClassName);
		p2.add(new Label("DataSource ClassName:"));
		p2.add(classFld);

		Panel p3 = new Panel();
		p3.setLayout(new GridLayout(1,2));
		
		controllerFld = new TextField (strControllerName);
		p3.add(new Label("Controller Name:"));
		p3.add(controllerFld);

		Panel p4 = new Panel();
		p4.setLayout(new GridLayout(1,1));
		
		chkIsCollection = new Checkbox("Root Is Collection", bIsCollection);
		p4.add(chkIsCollection);

		Panel p5 = new Panel();
		p5.setLayout(new GridLayout(1, 2));
		
		btnOK = new Button ("OK");
		p5.add(btnOK);
		btnOK.addActionListener(this);

		btnCancel = new Button ("Cancel");
		p5.add(btnCancel);
		btnCancel.addActionListener(this);

		Panel p = new Panel();
		p.setLayout(new GridLayout(4, 1, 20, 20));

		p.add(p1);
		p.add(p2);
		p.add(p3);
		p.add(p4);
		
		add(new Panel(), "North");
		add(new Panel(), "West");
		add(new Panel(), "East");
		add(p, "Center");
		add(p5, "South");
    }

    public void actionPerformed(ActionEvent e)
	{
		Object source = e.getSource();
		if (source == btnOK)
		{
			strName = nameFld.getText();
            strClassName = classFld.getText();
            strControllerName = controllerFld.getText();
			bIsCollection = chkIsCollection.getState();
            bIsOK = true;
            setVisible(false);
        }
        else 
        {
            dispose();
        }
    }

    public String getName()
    {
        return strName;
    }

    public String getClassName()
    {
        return strClassName;
    }

    public String getControllerName()
    {
        return strControllerName;
    }

	public boolean isCollection()
	{
		return bIsCollection;
	}

    public boolean isOK()
    {
        return bIsOK;
    }
    public void dispose()
    {
        btnOK.removeActionListener(this);
        btnCancel.removeActionListener(this);
        super.dispose();
    }
}

class SubPanel extends Panel
{
    /**
     * Panel that show the Panel title.  It contains a Label.
     */
    Panel titlePnl = new Panel();

    /**
     * The CENTER component of BorderLayout.
     */
    TextArea outputTxt = new TextArea();

    /**
     * The SOUTH component of BorderLayout.
     */
    Panel buttonPnl = new Panel();

    /**
     * The title of this panel.
     */
    Label titleLab;

    /**
     * Text displayed in the TextArea.
     */
    StringBuffer strOutput = new StringBuffer();
    
    /** 
     * The title of panel.
     */
    String strTitle;

    /**
     * The background color of this panel.
     */
    Color color;

    /**
     * A CheckBox that is used to show if it should concatenate the output.
     */
    Checkbox ifConChk;

    
    /**
     * Constructor.
     */
    public SubPanel(String strTitle, Color color)
    {
        super();
        this.strTitle = strTitle;
        this.color = color;
        initControls();
    }

    void initControls()
    {
        BorderLayout myLayout = new BorderLayout();
        setLayout(myLayout);
        setBackground(color);

        // Initial the title panel.
        titleLab = new Label(strTitle);
        titlePnl.setLayout(new FlowLayout(FlowLayout.LEFT,2,2));
        
        titlePnl.add(titleLab);
        add(titlePnl,BorderLayout.NORTH);
        

        // Initial the output Area.
        add(outputTxt,BorderLayout.CENTER);
        
        // Initial the Button panel.
        ifConChk = new Checkbox("Concatenate");
        buttonPnl.setLayout(new FlowLayout(FlowLayout.CENTER,2,2));
        buttonPnl.add(ifConChk);
        add(buttonPnl,BorderLayout.SOUTH);
    }

    /**
     * Set the output String.
     */
    public void setOutput(String strDisplay)
    {
        String strNew = escString(strDisplay);
        if (ifConChk.getState())
        {
            // Concatenate the strings.
            strOutput.append(strNew);
        }
        else
        {
            // Display a new string.
            strOutput = new StringBuffer(strNew);
        }
        
        outputTxt.setText(strOutput.toString());
        int length = strOutput.length();
        if (length > 0)
        {
            // Display the latest string.
            outputTxt.setCaretPosition(length);
        }
    }

    public String escString(String strIn)
    {
        StringBuffer strInput = new StringBuffer(strIn);
        int i = 0;
        char ch;
		while (i < strInput.length())
		{
			ch = strInput.charAt(i);
			if (ch == '\\' )
            {
				strInput = strInput.insert(i, '\\');
				i++;
			}
			i++;
		}
		return strInput.toString();
	}
}