Wednesday, May 29, 2013

What Is The Difference Between Authentication And Authorization?

Authentication

Authentication verifies who you are. For example, you can login into your Unix server using the ssh client, or access your email server using the POP3 and SMTP client. Usually, PAM (Pluggable Authentication Modules) are used as low-level authentication schemes into a high-level application programming interface (API), which allows programs that rely on authentication to be written independently of the underlying authentication scheme.

Authorization

Authorization verifies what you are authorized to do. For example, you are allowed to login into your Unix server via ssh client, but you are not authorized to browser /data2 or any other file system. Authorization occurs after successful authentication. Authorization can be controlled at file system level or using various application level configuration options such as chroot(2).
Usually, the connection attempt must be both authenticated and authorized by the system. You can easily find out why connection attempts are either accepted or denied with the help of these two factors.

Tuesday, May 28, 2013

Difference between JDK1.4.2, JDK1.5.0 and JDK1.6

   Re: Difference between JDK1.4.2, JDK1.5.0 and JDK1.6

        JDK 1.0 (january 23, 1996) oak
        - Initial release


        JDK 1.1 (february 19, 1997)
        - Retooling of the AWT event model
        - Inner classes added to the language
        - JavaBeans
        - JDBC
        - RMI


        J2SE 1.2 (December 8, 1998) playground
        This and subsequent releases through J2SE 5.0 were rebranded retrospectively Java 2 & version name "J2SE"
        (Java 2 Platform, Standard Edition) replaced JDK to distinguish the base Platform from
        J2EE (Java 2 Platform, Enterprise Edition) and J2ME (Java 2 Platform, Micro Edition).

        - Strictfp keyword
        - Reflection
        - Swing api integration into the core classes
        - JVM equipped with a jit compiler
        - Java plug-in
        - Java IDL
        - An IDL implementation for corba interoperability
        - Collections Framework


        J2SE 1.3 (may 8, 2000) KESTREL
        - Hotspot JVM included
        - JavaSound
        - JNDI included in core libraries
        - Java Platform Debugger Architecture (JPDA)
        - RMI was modified to support optional compatibility with corba


        J2SE 1.4 (february 6, 2002) MERLIN
        - assert keyword
        - Regular expressions
        - Exception chaining (allows an exception to encapsulate original lower-level exception)
        - Internet protocol version 6 (IPV6) support
        - Non-blocking nio (new input/output)
        - Logging API
        - Image i/o api for reading and writing images in formats like jpeg and png
        - Integrated XML parser and XSLT processor (JAXP)
        - Integrated security and cryptography extensions (JCE, JSSE, JAAS)
        - Java Web Start


        J2SE 5.0 (september 30, 2004) tiger [originally numbered 1.5]
        - Generics: provides compile-time (static) type safety for collections and eliminates the need for most typecasts (type conversion).
        - Metadata: also called annotations; allows language constructs such as classes and methods to be tagged with additional data, which can then be processed by metadata-aware utilities.
        - Autoboxing/unboxing: automatic conversions between primitive types (such as int) and primitive wrapper classes (such as integer).
        - Enumerations: the enum keyword creates a typesafe, ordered list of values (such as day.monday, day.tuesday, etc.). Previously this could only be achieved by non-typesafe constant integers or manually constructed classes (typesafe enum pattern).
        - Swing: new skinnable look and feel, called synth.
        - Var args: the last parameter of a method can now be declared using a type name followed by three dots (e.g. Void drawtext(string... Lines)). In the calling code any number of parameters of that type can be used and they are then placed in an array to be passed to the method, or alternatively the calling code can pass an array of that type.
        - Enhanced for each loop: the for loop syntax is extended with special syntax for iterating over each member of either an array or any iterable, such as the standard collection classesfix the previously broken semantics of the java memory model, which defines how threads interact through memory.
        - Automatic stub generation for rmi objects.
        - Static imports concurrency utilities in package java.util.concurrent.
        - Scanner class for parsing data from various input streams and buffers.
        - Assertions
        - StringBuilder class (in java.lang package)
        - Annotations



        Java SE 6 (december 11, 2006) mustang
        sun replaced the name "J2SE" with java se and dropped the ".0" from the version number.
        Beta versions were released in february and june 2006, leading up to a final release that occurred on december 11, 2006.
        The current revision is update 14 which was released in may 2009.

        - Support for older win9x versions dropped.
        - Scripting lang support: Generic API for integration with scripting languages, & built-in mozilla javascript rhino integration
        - Dramatic performance improvements for the core platform, and swing.
        - Improved web service support through JAX-WS JDBC 4.0 support
        - Java compiler API: an API allowing a java program to select and invoke a java compiler programmatically.
        - Upgrade of JAXB to version 2.0: including integration of a stax parser.
        - Support for pluggable annotations
        - Many GUI improvements, such as integration of swingworker in the API, table sorting and filtering, and true swing double-buffering (eliminating the gray-area effect).


        Java se 6 update 10
        A major enhancement in terms of end-user usability.
        - Java Deployment Toolkit, a set of javascript functions to ease the deployment of applets and java web start applications.
        - Java Kernel, a small installer including only the most commonly used jre classes. Enhanced updater.
        - Enhanced versioning and pack200 support: server-side support is no longer required.
        - Java quick starter, to improve cold start-up time.
        - Improved performance of java2D graphics primitives on windows, using direct3D and hardware acceleration.
        - A new Swing look and feel called NIMBUS and based on synth.
        - Next-generation java plug-in: applets now run in a separate process and support many features of web start applications.


        Java se 6 update 12
        This release includes the highly anticipated 64-bit java plug-in (for 64-bit browsers only), windows server 2008 support,
        and performance improvements of java and JAVAFX applications.

Disable URLRewriting In Tomcat 6

1. 'disableURLRewriting' attribute

In Tomcat 6, you can disable URL rewriting by setting 'disableURLRewriting' attribute to true in your context.xml.

<?xml version='1.0' encoding='utf-8'?>
<Context docBase="PATH_TO_WEBAPP" path="/CONTEXT" disableURLRewriting="true">
</Context>

For This You Have To Make Sure That Attribute "cookies" In Not Set To False. This Is The Default.

Attribute "cookies"
    Set to true if you want cookies to be used for session identifier communication if supported by the client (this is the default). Set to false if you want to disable the use of cookies for session identifier communication, and rely only on URL rewriting by the application.
Attribute "disableURLRewriting"
    Set to true to disable support for using URL rewriting to track session IDs for clients of this Context. URL rewriting is an optional component of the servlet 2.5 specification but disabling URL rewriting will result in non-compliant behaviour since the specification requires that there must be a way to retain sessions if the client doesn't allow session cookies. If not specified, the specification compliant default value of false will be used.

2. "Servlet Filter"

You can use a servlet filter such as Tuckey which allow you to rewrite URLs before they get to your code.
3. Switch to Tomcat 7 !

The Servlet 3.0 standard gives you two ways to disable URL session rewriting. This works in Tomcat 7, Glassfish v3, and any other Servlet 3.0-compliant servlet container. First, you can add this to your web.xml webapp config:

<session-config>
     <tracking-mode>COOKIE</tracking-mode>
</session-config>


Or programmatically, you can use:

servletContext.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE));

Saturday, May 25, 2013

Timdiff

/* Formatted On 2012/02/04 16:30 (Formatter Plus V4.8.8) */
Create Or Replace Function Timdiff(Date1 In Varchar,Time1 In Varchar, Time2 In Varchar)
   Return Varchar
Is
   Diff Varchar(30);
Begin
   If Time1 Is Null Then
      Dbms_Output.Put_Line ('Time1 Null Case This is Time1:'||Time1);
      Return '--';
   End If;
   If Time2 Is Null Then
      Dbms_Output.Put_Line ('Time2  Null Case This is Time2:'||Time2);
      Return '--';
   End If;                  
   If Time1 Is Not Null And Time2 Is Not Null
   Then
      Begin
      Dbms_Output.Put_Line(' Not Null Case :This is Time1:'||Time1||' & This is Time1:'||Time2||' And Date1:'||Date1);
         Select Distinct To_Char(Round(To_Number((To_Date(Decode(to_date(Date1),'', Sysdate,Date1) || ' '  || '' || Time1 || '','DD-mon-yyyy HH24MI')
                                                 -To_Date(Decode(to_date(Date1),'', Sysdate,Date1) || ' '  || '' || Time2 || '','DD-mon-yyyy HH24MI')
                                           )  * 1440
                                         )
                               )) Dos
         Into Diff From Dual;
         Dbms_Output.Put_Line('Times Difference in Mins : '||Diff);
         Return Diff;
      End;
     
   End If;
    Exception
       When No_Data_Found Then
       Raise_Application_Error (-2021,'manager not a valid employee');
End;
/

DB2Excel

 /*********************************************************************/
 /*(c) Copyright IBM Corp. 2003  All rights reserved.                 */
 /*                                                                   */
 /*This sample program is owned by International Business Machines    */
 /*Corporation or one of its subsidiaries ("IBM") and is copyrighted  */
 /*and licensed, not sold.                                            */
 /*                                                                   */
 /*You may copy, modify, and distribute this sample program in any    */
 /*form without payment to IBM,  for any purpose including developing,*/
 /*using, marketing or distributing programs that include or are      */
 /*derivative works of the sample program.                            */
 /*                                                                   */
 /*The sample program is provided to you on an "AS IS" basis, without */
 /*warranty of any kind.  IBM HEREBY  EXPRESSLY DISCLAIMS ALL         */
 /*WARRANTIES EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO*/
 /*THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTIC-*/
 /*ULAR PURPOSE. Some jurisdictions do not allow for the exclusion or */
 /*limitation of implied warranties, so the above limitations or      */
 /*exclusions may not apply to you.  IBM shall not be liable for any  */
 /*damages you suffer as a result of using, modifying or distributing */
 /*the sample program or its derivatives.                             */
 /*                                                                   */
 /*Each copy of any portion of this sample program or any derivative  */
 /*work,  must include a the above copyright notice and disclaimer of */
 /*warranty.                                                          */
 /*                                                                   */
 /*********************************************************************/

package com.ibm.DB2Excel;

  /******************************************************************/
  /* Main class of the DB2Excel application                      */
  /******************************************************************/


import javax.swing.*;
import javax.swing.filechooser.*;
import java.io.File;
import java.awt.*;
import java.awt.event.*;
import java.sql.SQLException;


/**
 *  Main class of the DB2Excel application.
 */

public class DB2Excel extends JFrame implements LoginService {


    /**
     * name of the table being viewed
     */
    private String tableName;


    /**
     * TableModel for the JTable
     */
    private ResultSetTableModel tableModel;


    /**
     * JTable that is used to represent a database table.
     */
    private JTable table;


    /**
     *   Simple facade that hides the details of executing JDBC commands
     */
    private SQLFacade sqlFacade;


    /**
     *    ExcelFileGenerator to create Excel Spreadsheets
     */

    private ExcelFileGenerator generator;
    /**
    *    Filters files of type XLS in the file chooser
    */
   
    private boolean tableLoaded = false;

    public class Utils
    {

        // Extension for Excel files
        public final static String EXCEL = "xls";


        /*
         * Get the extension of a file.
         */ 
        public String getExtension(File f)
        {
             String ext = null;
            String s = f.getName();
            int i = s.lastIndexOf('.');


            if (i > 0 &&  i < s.length() - 1)
            {
                ext = s.substring(i+1).toLowerCase();
            }
            return ext;
        }
    }




    public class CustomFileFilter extends FileFilter
    {
        public boolean accept (File f)
        {
            Utils dummyUtils = new Utils();
            String extension = dummyUtils.getExtension(f);
               if ((extension!=null) && (extension.equals(Utils.EXCEL))) return true;
            else return false;
           
        }


        public String getDescription()
        {
            return ("Microsoft Excel Files");
        }
    }

    /**
     * Centers the dialog box to appear in the middle of the screen
     */
      private void centerDialog() {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();


        int x = ((int) screenSize.getWidth() - (int) (screenSize.getWidth() / 2)) - (int) (getWidth() / 2);
        int y = ((int) screenSize.getHeight() - (int) (screenSize.getHeight() / 2)) - (int) (getHeight() / 2);


        setLocation(x, y);
    }

    // class constructor  - sets up the application
    public DB2Excel() {
        super("DB2 -> Excel");

        // file chooser, restricted to Excel files
        final JFileChooser fc = new JFileChooser();
        CustomFileFilter xlFilter = new CustomFileFilter();
        fc.setFileFilter(xlFilter);


        // build and show the login dialog
        JFrame loginFrame = new JFrame();
        LoginDialog ld = new LoginDialog(loginFrame, "DB2 -> Excel", this);
        ld.show();
        if (ld.isCancelled())
            System.exit(0);


        JPanel topPanel = new JPanel();
        topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS));
        topPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));


        Object[] tableArray = null;
        try {
            // grab the tables of the current database
            tableArray = sqlFacade.getTablesFromDb();
        } catch (SQLException se) {
            MessageBox.showErrorMessageDialog(se, "Error accessing tables in database");
            se.printStackTrace();
        }
        // combo box for choosing a table
        JComboBox tables = new JComboBox(tableArray);
        tables.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JComboBox cb = (JComboBox) e.getSource();
                tableName = (String) cb.getSelectedItem();
            }
        });

        ImageIcon saveIcon = new ImageIcon("c:\\save.gif");
        JButton create = new JButton("Create My Spreadsheet", saveIcon);
        //listener for the Create button
        create.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                try
                {
                    // System.out.println("Call to Create Spreadsheet of " + tableName);
                    // show the file save dialog
                    File destFile;           
                    Exception exc = null;
                     // make sure a source table is specified
                       if ((tableName==null) ||    (tableName.equals(SQLFacade.NO_TABLE)) )
                    {
                        exc = new Exception("A source table must be specified and loaded.");
                        throw exc;
                    }               
                    if (!tableLoaded)
                    {
                        exc = new Exception("A source table must be loaded before creating a spreadsheet.");
                        throw exc;
                    }
                    int returnVal = fc.showSaveDialog(DB2Excel.this);
                    if (returnVal == JFileChooser.APPROVE_OPTION)
                    {
                            destFile = fc.getSelectedFile();
                       
                           // create the excel file for the chosen table
                          
                           generator = new ExcelFileGenerator(destFile.getPath(),tableName,tableModel);
                       
                    }
                }
                catch(Exception ex)
                {
                    MessageBox.showErrorMessageDialog(ex,"An Error Has Occurred.");               
                    ex.printStackTrace();
                }
            }
        });

        ImageIcon loadIcon = new ImageIcon("c:\\open.gif");
        JButton load = new JButton("Load Table",loadIcon);
        // listener for the Go Button
        load.addActionListener(new ActionListener() {
            /**
             * When the load button is hit, the table model is refreshed using the tableName that is selected
             * in the drop down menu.
             */
            public void actionPerformed(ActionEvent e)
            {
                setCursor(Cursor.WAIT_CURSOR);
                try
                {
                    // make sure a table is chosen
                    if ((tableName==null) ||    (tableName.equals(SQLFacade.NO_TABLE)) )
                   {
                        Exception excep = new Exception("Please specify a table.");
                        throw excep;
                   }
                   // load the table & preview it to the user
                   tableModel.reloadTableModel(tableName);
                   for (int i = 0; i < tableModel.getColumnCount(); i++)
                   {
                           table.getColumnModel().getColumn(i).setCellRenderer(new CustomCellRenderer());
                   }
                   tableLoaded=true;
                }
                catch (Exception exc)
                {
                    MessageBox.showErrorMessageDialog(exc, "An Error Has Occured");
                }
                setCursor(Cursor.DEFAULT_CURSOR);
            }
        });


        topPanel.add(new JLabel("Current Table: "));
        topPanel.add(Box.createRigidArea(new Dimension(5, 0)));
        topPanel.add(tables);
        topPanel.add(Box.createRigidArea(new Dimension(5, 0)));
        topPanel.add(load);
        topPanel.add(Box.createHorizontalGlue());
        topPanel.add(create);

        // load the table
        tableModel = new ResultSetTableModel(sqlFacade);
        table = new JTable(tableModel);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(topPanel, BorderLayout.NORTH);
        getContentPane().add(scrollPane, BorderLayout.CENTER);
           Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int x = ((int) screenSize.getWidth() - (int) (screenSize.getWidth() / 2)) - (int) (getWidth() / 2);
        int y = ((int) screenSize.getHeight() - (int) (screenSize.getHeight() / 2)) - (int) (getHeight() / 2);
        getContentPane().setLocation(x, y);
    }




    /**
     * Implementation of the LoginService interface.
     * Connects to a database with the given username and password
     *
     * @return true if connection was made to the database. false if connection failed
     */
    public boolean login(String username, String password, String database, String port) {
        try {
            sqlFacade = new SQLFacade(username, password, database, port);
        } catch (SQLException se) {
            MessageBox.showErrorMessageDialog(se, "Error connecting to database");
            return false;
        } catch (ClassNotFoundException ce) {
            MessageBox.showErrorMessageDialog(ce, "Error connecting to database");
            return false;
        }
        return true;
    }




    static {
        try {
            UIManager.setLookAndFeel(
                    // set the look and feel to metal
                    UIManager.getCrossPlatformLookAndFeelClassName());
        } catch (Exception e) {
            MessageBox.showErrorMessageDialog(e, "Error intializing application");
        }
    }


    /**
     * Inner class used to render edited cells in JTable in a different color.
     */
    class CustomCellRenderer extends javax.swing.table.DefaultTableCellRenderer {




        public Component getTableCellRendererComponent(JTable table, Object value,
                                                       boolean isSelected, boolean hasFocus, int row, int column) {
            if (isSelected)
            {
                return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            }
            Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            c.setForeground(table.getForeground());
            return c;
        }
    }


    public static void main(String[] args) throws Exception {

        // instantiate an instance of the program
        final DB2Excel progInstance = new DB2Excel();
        progInstance.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        progInstance.pack();
        progInstance.centerDialog();
        progInstance.setVisible(true);
    }




}

ResultSetTableModel

 /*********************************************************************/
 /*(c) Copyright IBM Corp. 2003  All rights reserved.                 */
 /*                                                                   */
 /*This sample program is owned by International Business Machines    */
 /*Corporation or one of its subsidiaries ("IBM") and is copyrighted  */
 /*and licensed, not sold.                                            */
 /*                                                                   */
 /*You may copy, modify, and distribute this sample program in any    */
 /*form without payment to IBM,  for any purpose including developing,*/
 /*using, marketing or distributing programs that include or are      */
 /*derivative works of the sample program.                            */
 /*                                                                   */
 /*The sample program is provided to you on an "AS IS" basis, without */
 /*warranty of any kind.  IBM HEREBY  EXPRESSLY DISCLAIMS ALL         */
 /*WARRANTIES EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO*/
 /*THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTIC-*/
 /*ULAR PURPOSE. Some jurisdictions do not allow for the exclusion or */
 /*limitation of implied warranties, so the above limitations or      */
 /*exclusions may not apply to you.  IBM shall not be liable for any  */
 /*damages you suffer as a result of using, modifying or distributing */
 /*the sample program or its derivatives.                             */
 /*                                                                   */
 /*Each copy of any portion of this sample program or any derivative  */
 /*work,  must include a the above copyright notice and disclaimer of */
 /*warranty.                                                          */
 /*                                                                   */
 /*********************************************************************/

package com.ibm.DB2Excel;

/*********************************************************************/
  /******************************************************************/
  /* Stores the contents of a database table                         */
  /******************************************************************/
 import javax.swing.table.AbstractTableModel;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.*;
/**
 * Implements the TableModel interface so that a JTable can display the contents of ResultSet.
 **/
 public class ResultSetTableModel extends AbstractTableModel
{
    /**
     * number of rows in the ResultSet
     */
    private int rowCount;
     /**
     * number of columns in ResultSet
     */
    private int colCount;
     /**
     * Simple facade that hides the details of executing JDBC commands
     */
    private SQLFacade sqlFacade;
     /**
     * The names of the columns in the ResultSet
     */
    private List columnNames = new ArrayList();
     /**
     *  The class types of the columns being displayed.
     */
    private List columnTypes = new ArrayList();
     /**
     *  Transcribes the data in the ResultSet into a List of lists
     */
    private List result = new ArrayList();
     /**
     * Name of the database table being displayed
     */
    private String tableName;
     public ResultSetTableModel(SQLFacade facade) {
        this.sqlFacade = facade;
    }
 // ----------------------------------------------------------------------------------------- //
// methods of javax.swing.table.TableModel interface
// ----------------------------------------------------------------------------------------- //
    public int getRowCount() {
        return rowCount;
    }
     public int getColumnCount() {
        if(rowCount > 0)
            return colCount+1;
        else
            return 0;
    }
     public Object getValueAt(int rowIndex, int columnIndex) {
        if(columnIndex == 0)
            return new Integer(rowIndex);
        else
            return ((ArrayList) result.get(rowIndex)).get(columnIndex-1);
    }
     public String getColumnName(int colIndex) {
        if(colIndex == 0)
            return "Row";
        else
            return (String) columnNames.get(colIndex-1);
    }
     /**
     * returns the list of column names
     */
    public List getColumnNames() {
        return columnNames;
    }
     /**
     *  reloads the TableModel with the contents of specified tableName
     * @param tableName table with which to reload the TableModel
     * @exception SQLException if a database error occurs
     * @exception ClassNotFoundException
     */
    public void reloadTableModel(String tableName) throws SQLException, ClassNotFoundException {
        ResultSet rs = null;
        this.tableName = tableName;
        try {
            rs = sqlFacade.executeQuery("SELECT * from " + tableName);
            clearAll();
            updateColumnModel(rs.getMetaData());
            while (rs.next()) {
                ArrayList list = new ArrayList();
                for (int i = 1; i <= colCount; i++) {
                    Object o = rs.getObject(i);
                    list.add(o);
                }
                result.add(list);
                rowCount++;
            }
             fireTableStructureChanged();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException se) {
                }
            }
        }
    }
     private void updateColumnModel(ResultSetMetaData metaData) throws SQLException, ClassNotFoundException {
        colCount = metaData.getColumnCount();
        for (int i = 1; i <= colCount; i++) {
            String colName = metaData.getColumnLabel(i);
            String colClass = metaData.getColumnClassName(i);
            columnTypes.add(Class.forName(colClass));
            columnNames.add(colName);
        }
    }
     /**
     * clears the TableModel
     */
    private void clearAll() {
        for (int i = 0; i < result.size(); i++) {
            ArrayList list = (ArrayList) result.get(i);
            list.clear();
        }
        result.clear();
        columnNames.clear();
        columnTypes.clear();
        colCount = 0;
        rowCount = 0;
    }
     public List getRow(int i) {
        return (List) result.get(i);
    }
 }

Simple facade for making calls to a database

 /*********************************************************************/
 /*(c) Copyright IBM Corp. 2003  All rights reserved.                 */
 /*                                                                   */
 /*This sample program is owned by International Business Machines    */
 /*Corporation or one of its subsidiaries ("IBM") and is copyrighted  */
 /*and licensed, not sold.                                            */
 /*                                                                   */
 /*You may copy, modify, and distribute this sample program in any    */
 /*form without payment to IBM,  for any purpose including developing,*/
 /*using, marketing or distributing programs that include or are      */
 /*derivative works of the sample program.                            */
 /*                                                                   */
 /*The sample program is provided to you on an "AS IS" basis, without */
 /*warranty of any kind.  IBM HEREBY  EXPRESSLY DISCLAIMS ALL         */
 /*WARRANTIES EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO*/
 /*THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTIC-*/
 /*ULAR PURPOSE. Some jurisdictions do not allow for the exclusion or */
 /*limitation of implied warranties, so the above limitations or      */
 /*exclusions may not apply to you.  IBM shall not be liable for any  */
 /*damages you suffer as a result of using, modifying or distributing */
 /*the sample program or its derivatives.                             */
 /*                                                                   */
 /*Each copy of any portion of this sample program or any derivative  */
 /*work,  must include a the above copyright notice and disclaimer of */
 /*warranty.                                                          */
 /*                                                                   */
 /*********************************************************************/


package com.ibm.DB2Excel;
 /*********************************************************************/
  /******************************************************************/
  /* Simple facade for making calls to a database                   */
  /******************************************************************/
 import java.sql.*;
import java.util.ArrayList;
import java.util.List;
 /**
 * Simple facade that hides the details of using the JDBC API such as loading the JDBC driver etc.
 */
public class SQLFacade {
     static final String NO_TABLE = "----------------------";
     /**
     * the name of IBM DB2 JDBC driver
     */
    private static final String jdbcDriver = "COM.ibm.db2.jdbc.app.DB2Driver";
     /**
     *
     */
    private static final String jdbcURL = "jdbc:db2:";
     /**
     * Connection to a database
     */
    private Connection connection;
     /**
     * Creates a connection to a database
     * @param username username to connect to the database with. Can be null.
     * @param password password. Can be null.
     * @param database name of the database to which we connect. Cannot be null.
     * @param port port on which to connect to database
     *
     * @exception SQLException if a database error occurs
     * @exception ClassNotFoundException if a error occurs when loading the JDBC driver
     *
     */
    public SQLFacade(String username, String password, String database, String port) throws SQLException, ClassNotFoundException {
         Class.forName(jdbcDriver);
        String dbURL = jdbcURL + database;
         if (!port.equals("")) {
            System.out.println("Need to add port");
        }
         if (!username.equals("")) {
            connection = DriverManager.getConnection(dbURL, username, password);
        } else {
            connection = DriverManager.getConnection(dbURL);
        }
    }
     /**
     * Execute the SQL query
     * @param query SQL query to execute
     * @return ResultSet
     * @exception SQLException if a database error occurs
     */
    public ResultSet executeQuery(String query) throws SQLException {
        PreparedStatement st = connection.prepareStatement(query);
        return st.executeQuery();
    }
     /**
     *  Queries the database for the tables created by the user
     */
    public Object[] getTablesFromDb() throws SQLException {
        DatabaseMetaData md = connection.getMetaData();
        String types[] = {"TABLE"};
        ResultSet set = md.getTables(null, null, null, types);
        List list = new ArrayList();

        list.add(NO_TABLE);
         while (set.next()) {
            list.add(set.getObject(3));
        }
        set.close();
        if (list.size() > 0)
            return list.toArray();
        else
            return null;
    }

    /**
     * Close connection to database
     */
    public void close() {
        try {
            connection.close();
        } catch (SQLException se) {
            connection = null;
        }
    }
     protected void finalize() {
        close();
    }
}