20
OPAC SYSTEM USING EVENT DRIVEN AND CONCURRENT PROGRAMMING Aim: Develop a simple OPAC system for library using even-driven and concurrent programming paradigms of Java. Use JDBC to connect to a back-end database. Algorithm: 1. Create a OPAC library system application using swing and provide a actionListener 2. Create two search categories such as searching by author or book name 3. Also provide methods to edit,update,add and delete records 4. Display the table of contents using JDBC connectivity of an existing database 5. Provide a text field to enter the search items 6. Using the resultset obtain the contents of the database as per the search key 7. Invoke the application by calling the Library class PROGRAM CODING: import java.awt.*; import java.awt.event.*; import java.sql.*; import java.applet.*; import javax.swing.*; //////////////Creates the main window with top Menu toolbar. /////////////This is also the class for the main declaration public class Library extends Frame { public Library() { initComponents(); } public void initComponents() { //Creates menu bar and add it to frame menubar = new MenuBar(); setMenuBar(menubar); //Create File menu with Items Menu file = new Menu("File"); MenuItem item1; file.add(item1 = new MenuItem("Exit")); menubar.add(file);

Opac System Using Event Driven and Concurrent Programming

Embed Size (px)

Citation preview

Page 1: Opac System Using Event Driven and Concurrent Programming

OPAC SYSTEM USING EVENT DRIVEN AND CONCURRENT PROGRAMMINGAim:Develop a simple OPAC system for library using even-driven and concurrentprogramming paradigms of Java. Use JDBC to connect to a back-end database.Algorithm:

1. Create a OPAC library system application using swing and provide a actionListener 2. Create two search categories such as searching by author or book name3. Also provide methods to edit,update,add and delete records4. Display the table of contents using JDBC connectivity of an existing database5. Provide a text field to enter the search items6. Using the resultset obtain the contents of the database as per the search key7. Invoke the application by calling the Library class

PROGRAM CODING:import java.awt.*;import java.awt.event.*;import java.sql.*;import java.applet.*;import javax.swing.*;//////////////Creates the main window with top Menu toolbar./////////////This is also the class for the main declarationpublic class Library extends Frame {public Library(){ initComponents(); }public void initComponents() {//Creates menu bar and add it to framemenubar = new MenuBar();setMenuBar(menubar);//Create File menu with ItemsMenu file = new Menu("File");MenuItem item1;file.add(item1 = new MenuItem("Exit"));menubar.add(file);//Creates Records menu with itemsMenu names = new Menu("Records");MenuItem item2,item3,item4,item5;names.add(item2 = new MenuItem("Add..."));names.add(item3 = new MenuItem("Edit..."));names.add(item4 = new MenuItem("Delete..."));names.add(item5 = new MenuItem("Search..."));menubar.add(names);//Create an object to handle window eventsmyWindowAdapter adapter = new myWindowAdapter(this);addWindowListener(adapter);//Create an object to handle action and item eventsmyMenuHandler handler = new myMenuHandler(this);

Page 2: Opac System Using Event Driven and Concurrent Programming

//register it to receive eventsitem1.addActionListener(handler);item2.addActionListener(handler);item3.addActionListener(handler);item4.addActionListener(handler);item5.addActionListener(handler);}//Variable declarationprivate Menu menu;private MenuBar menubar;/////////// This is the main declarationpublic static void main(String args[]){//Creates main window, sets Title, Height and Width and VisibilityLibrary appBook = new Library();appBook.setTitle("A OPAC LIBRARY SYSTEM");appBook.setSize(400, 300);appBook.setBackground(Color.WHITE);appBook.setVisible(true);

} }//////////This Class handles the event for closing the main program windowclass myWindowAdapter extends WindowAdapter {Library appbook;public myWindowAdapter(Library appbook) {this.appbook = appbook;}public void windowClosing(WindowEvent we) {appbook.setVisible(false);appbook.dispose();} }////////////This creates the Add New Book Dialog for entering new data into the database.class AddDlg extends Dialog implements ActionListener {TextField Name1,Bookno1,Author1,Publication1;Button BtnOK,BtnCn;public AddDlg(Library parent, String title) {//Sets the way that the Dialog will look on screensuper(parent, title, true);setLayout(new GridLayout(5,3,10,20));setSize(300,250);setResizable(false);//Creates new Labels to describe the text boxes.Label Name,Bookno,Author,Publication;

Page 3: Opac System Using Event Driven and Concurrent Programming

Name = new Label("Name: ");Bookno = new Label("Bookno: ");Author = new Label("Author: ");Publication = new Label("Publication: ");//Creates TextBoxes for the user to enter data intoName1 = new TextField(10);Bookno1 = new TextField(10);Author1 = new TextField(20);Publication1 = new TextField(10);BtnOK = new Button("OK");BtnCn = new Button("Cancel");//Creates Listeners for ButtonsBtnOK.addActionListener(this);BtnCn.addActionListener(this);//Creates spacer labels for the GridLayoutLabel space1,space2,space3,space4,space5;space1 = new Label(" ");space2 = new Label(" ");space3 = new Label(" ");space4 = new Label(" ");space5 = new Label(" ");//Adds new Labels, Textboxes and Buttonadd(Name);add(Name1);add(space1);add(Bookno);add(Bookno1);add(space2);add(Author);add(Author1);add(space3);add(Publication);add(Publication1);add(space4);add(space5);add(BtnOK);add(BtnCn);}//////////////This method hales all the events that take place on the dialogpublic void actionPerformed(ActionEvent e) {String str = e.getActionCommand();if (str.equals("OK")){ToDataBase();}if (str.equals("Cancel")) {

Page 4: Opac System Using Event Driven and Concurrent Programming

dispose();} }///////////////Open a connection to the LibraryBook database and update it with the data that the user has entered into the textfields.public void ToDataBase() {//Retrieve info from the Textfields in die Dialog.String Name = Name1.getText();String Bookno = Bookno1.getText();String Author = Author1.getText();String Publication = Publication1.getText();//Parameters for the creation of the database.String dbuser = "";String dbpasswd = "";String DriverPrefix = "jdbc:odbc:";String DataSource ="Library";//The SQL StringString SQLString = "INSERT INTO Book(Name,Bookno,Author,Publication)VALUES('" +Name+ "','"+Bookno+"','"+Author+"','"+Publication+"')";//Loads JDBC/ODBC drivertry {Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");} catch(Exception e) {//Uses the JFC Swing to display warning message in Option Pane with//relevant information about the error.JOptionPane.showMessageDialog(null,""+e.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE);return;}Statement stmt = null;Connection con = null;//Creates connection to databasetry {con = DriverManager.getConnection(DriverPrefix+DataSource,dbuser, dbpasswd);stmt = con.createStatement();} catch (Exception e) {JOptionPane.showMessageDialog(null,""+e.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE);}//Updates the database with datatry {stmt.executeUpdate(SQLString);con.close();this.dispose();}catch (Exception e) {

Page 5: Opac System Using Event Driven and Concurrent Programming

JOptionPane.showMessageDialog(null,"Check that all TextFields have been completed.\n"+e.getMessage(),"Communication Error",JOptionPane.WARNING_MESSAGE);} } }////////////////This class will create a Dialog fo the editing of existing records.class EditDlg extends Dialog implements ActionListener, ItemListener {//Sets the textfields that goes to the Dialog boxTextField BooknoField, AuthorField, PublicationField;//Creates the pop uplist on the dialogChoice NameList;public EditDlg(Library parent, String title) {//Sets the dimensions for the Edit dialog box.super(parent, title, true);setLayout (new GridLayout(5,3,10,20));setSize(300, 250);setResizable(false);//Sets the labels that goes onto the Dialog boxLabel Name, Bookno, Author, Publication;Name = new Label("Name: ");Bookno = new Label("Bookno: ");Author = new Label ("Author: ");Publication = new Label("Publication: ");//Adds a pop up list to the dialog with names from the databaseNameList = new Choice();//Sets the sizes of the textfieldsBooknoField = new TextField(10);AuthorField = new TextField(20);PublicationField = new TextField(10);//Creates the buttons on the dialog boxButton BtnUpdate, BtnCn;BtnUpdate = new Button("Update");BtnCn = new Button("Cancel");//Adds listeners to the buttonsBtnUpdate.addActionListener(this);BtnCn.addActionListener(this);NameList.addItemListener(this);//Creates space labels to fill up the space in the GridLayoutLabel space1, space2, space3, space4, space5;space1 = new Label(" ");space2 = new Label(" ");space3 = new Label(" ");space4 = new Label(" ");space5 = new Label(" ");//Add all the controls to the Dialog.add(Name);add(NameList);add(space1);

Page 6: Opac System Using Event Driven and Concurrent Programming

add(Bookno);add(BooknoField);add(space2);add(Author);add(AuthorField);add(space3);add(Publication);add(PublicationField);add(space4);add(space5);add(BtnUpdate);add(BtnCn);GetData();}///////////////////Handles all the events happeing on the dialog boxpublic void actionPerformed(ActionEvent e) {String str = e.getActionCommand();if (str.equals("Update")){DataUpdate();}if (str.equals("Cancel")) {dispose();} }/////////////This method handles the Event action that take place on the Choide Drop Down Listpublic void itemStateChanged(ItemEvent ie) {String dbuser = " ";String dbpasswd = " ";String DriverPrefix = "jdbc:odbc:";String DataSource = "Library";//This will hold the currently selected name in the list in myChoiceString myChoice = NameList.getSelectedItem();String SQL = "SELECT Name,Bookno,Author,Publication FROM Book WHERE Name ='" +myChoice+ "'";try {Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");} catch (Exception e) {JOptionPane.showMessageDialog(null,""+e.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE);}Statement stmt = null;Connection con = null;try {con = DriverManager.getConnection(DriverPrefix+DataSource,dbuser,dbpasswd);stmt = con.createStatement();} catch (Exception e) {

Page 7: Opac System Using Event Driven and Concurrent Programming

JOptionPane.showMessageDialog(null,""+e.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE);}ResultSet rs = null;try {rs = stmt.executeQuery(SQL);rs.next();BooknoField.setText(rs.getString(2));AuthorField.setText(rs.getString(3));PublicationField.setText(rs.getString(4));con.close();} catch (Exception e) {JOptionPane.showMessageDialog(null,""+e.getMessage(),"Communication Error",JOptionPane.WARNING_MESSAGE);} }//This method will populate the pop up list with names from the database.public void GetData() {String dbuser = " ";String dbpasswd = " ";String DriverPrefix = "jdbc:odbc:";String DataSource = "Library";String SQL = "SELECT Name FROM Book" ;try {Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");} catch (Exception e) {JOptionPane.showMessageDialog(null,""+e.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE);}Statement stmt = null;Connection con = null;try {con = DriverManager.getConnection(DriverPrefix+DataSource,dbuser,dbpasswd);stmt = con.createStatement();} catch (Exception e) {JOptionPane.showMessageDialog(null,""+e.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE);}ResultSet rs = null;try {rs = stmt.executeQuery(SQL);//This will populate the drop down list with all the names of people entered into the database.while (rs.next()) {NameList.add(rs.getString("Name"));}} catch(Exception e) {

Page 8: Opac System Using Event Driven and Concurrent Programming

JOptionPane.showMessageDialog(null,""+e.getMessage(),"Communication Error",JOptionPane.WARNING_MESSAGE);}//This try - catch sequence will close the database after the drop down list has been populatedtry {con.close();} catch (Exception e) {JOptionPane.showMessageDialog(null,""+e.getMessage(),"Warning",JOptionPane.WARNING_MESSAGE);} }////This will update the change data from the TextFields to the database.public void DataUpdate() {String dbuser = " ";String dbpasswd = " ";String DriverPrefix = "jdbc:odbc:";String DataSource = "Library";//Loads the database drivertry {Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");} catch (Exception e) {JOptionPane.showMessageDialog(null,""+e.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE);}Statement stmt = null;Connection con = null;//Creates connection to databasetry {con = DriverManager.getConnection(DriverPrefix+DataSource,dbuser,dbpasswd);stmt = con.createStatement();} catch (Exception e) {JOptionPane.showMessageDialog(null,""+e.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE);}//These String variables will hold the updated data retrieved from the TextFields.String upBookno = BooknoField.getText();String upAuthor = AuthorField.getText();String upPublication = PublicationField.getText();//This is the SQL String that updates the data from the TextFields to the databaseString SQL = "UPDATE Author SET Bookno = '"+upBookno+"', Author = '"+upAuthor+"', Publication = '"+upPublication+"' WHERE Name = '"+NameList.getSelectedItem()+"'";//Communicates with databasetry {stmt.executeUpdate(SQL);con.close();dispose();

Page 9: Opac System Using Event Driven and Concurrent Programming

} catch (Exception e) {JOptionPane.showMessageDialog(null,""+e.getMessage(),"Communication Error",JOptionPane.WARNING_MESSAGE);} } }//This class will delete data from the databaseclass DelRec extends Dialog implements ActionListener, ItemListener {//Declaration of TextFieldsTextField BooknoField, AuthorField, PublicationField;//Declaration of drop down listChoice NameList;public DelRec (Library parent, String title) {super (parent, title, true);setLayout(new GridLayout(5,3,10,20));setSize(300, 250);setResizable(false);//Declaration of labels that will describe the TextFieldsLabel Name, Bookno, Author, Publication;//Creates the LabelsName = new Label("Name");Bookno = new Label("Bookno");Author = new Label("Author");Publication = new Label("Publication");//Declaration of labels that will be used as spacers in the GridLayoutLabel space1, space2, space3, space4, space5;//Creates the spacer labels.space1 = new Label(" ");space2 = new Label(" ");space3 = new Label(" ");space4 = new Label(" ");space5 = new Label(" ");//Creates the button on the dialogButton BtnDel = new Button("Delete");Button BtnCn = new Button("Cancel");//Creates the drop down listNameList = new Choice();//Adds listeners to buttons and drop down listBtnDel.addActionListener(this);BtnCn.addActionListener(this);NameList.addItemListener(this);//Creates the TextFieldsBooknoField = new TextField(10);AuthorField = new TextField(20);PublicationField = new TextField(10);//Adds the components to the dialogadd(Name);add(NameList);

Page 10: Opac System Using Event Driven and Concurrent Programming

add(space1);add(Bookno);add(BooknoField);add(space2);add(Author);add(AuthorField);add(space3);add(Publication);add(PublicationField);add(space4);add(space5);add(BtnDel);add(BtnCn);GetData();}//This method handles all the action events from the Delete and Cancel buttons.public void actionPerformed(ActionEvent e) {String str = e.getActionCommand();if (str.equals("Delete")) {DelCurRec();}if (str.equals("Cancel")) {dispose();} }//Updates the TextFields with the rest of the data when selection is made.public void itemStateChanged(ItemEvent e) {String dbuser = " ";String dbpasswd = " ";String DriverPrefix = "jdbc:odbc:";String DataSource = "Library";//This will hold the currently selected name in the list in myChoiceString myChoice = NameList.getSelectedItem();//This is the SQL query for extracting data from the database.String SQL = "SELECT Name,Bookno,Author,Publication FROM Book WHERE Name ='" +myChoice+ "'";//Loads the driver for communicating with databasetry {Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");} catch (Exception ex) {JOptionPane.showMessageDialog(null,""+ex.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE);}Statement stmt = null;Connection con = null;//Creates a connection to the databasetry {

Page 11: Opac System Using Event Driven and Concurrent Programming

con = DriverManager.getConnection(DriverPrefix+DataSource,dbuser,dbpasswd);stmt = con.createStatement();} catch (Exception ex) {JOptionPane.showMessageDialog(null,""+ex.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE);}ResultSet rs = null;//Executes the Sl query on the database.try {rs = stmt.executeQuery(SQL);rs.next();BooknoField.setText(rs.getString(2));AuthorField.setText(rs.getString(3));PublicationField.setText(rs.getString(4));con.close();} catch (Exception ex) {JOptionPane.showMessageDialog(null,""+ex.getMessage(),"Communication Error",JOptionPane.WARNING_MESSAGE);} }//This method will populate the drop downlist with data from the database.public void GetData() {String dbuser = " ";String dbpasswd = " ";String DriverPrefix = "jdbc:odbc:";String DataSource = "Library";String SQL = "SELECT Name FROM Book";try {Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");} catch (Exception e) {JOptionPane.showMessageDialog(null,""+e.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE);}Statement stmt = null;Connection con = null;try {con = DriverManager.getConnection(DriverPrefix+DataSource,dbuser, dbpasswd);stmt = con.createStatement();} catch (Exception e) {JOptionPane.showMessageDialog(null,""+e.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE);}ResultSet rs = null;try {rs = stmt.executeQuery(SQL);while (rs.next()) {NameList.add(rs.getString("name"));

Page 12: Opac System Using Event Driven and Concurrent Programming

}} catch (Exception e) {JOptionPane.showMessageDialog(null,""+e.getMessage(),"Communication Problem",JOptionPane.WARNING_MESSAGE);} }//This method wil delete the currently selected record.public void DelCurRec() {String dbuser = " ";String dbpasswd = " ";String DriverPrefix = "jdbc:odbc:";String DataSource = "Library";//MyChoice will hold the value for the currently selected itemString myChoice = NameList.getSelectedItem();//This is the SQL stringString SQL = "DELETE FROM Book WHERE Name = '" +myChoice+ "'";try {Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");} catch (Exception e) {JOptionPane.showMessageDialog(null,""+e.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE);}Statement stmt = null;Connection con = null;//Creates connection to databasetry {con = DriverManager.getConnection(DriverPrefix+DataSource,dbuser,dbpasswd);stmt = con.createStatement();} catch (Exception e) {JOptionPane.showMessageDialog(null,""+e.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE);}//Execute the SQL statment for deleting recordstry {stmt.executeUpdate(SQL);//This closes the connection to the databasecon.close();//This closes the dialogdispose();} catch (Exception e) {JOptionPane.showMessageDialog(null,""+e.getMessage(),"Communication Error",JOptionPane.WARNING_MESSAGE);} } }/////////This class will create the Search Dialog.class SearchDlg extends Dialog implements ActionListener, ItemListener {//This declares a TextField that will be put on the dialogTextField Name;

Page 13: Opac System Using Event Driven and Concurrent Programming

//This creates a Search and Cancel button on the dialogButton BtnGo, BtnCn;//This creates checkboxes for different search queriesCheckbox option1 = new Checkbox("By Name");public SearchDlg (Library parent, String title) {super(parent,title,false);setSize(300, 100);setLayout(new GridLayout(3,2,8,5));setResizable(false);setLocation(300,50);//This creates a label for the search dialog describing the TextFieldLabel Srch = new Label("Search For :");//This creates a Textfield for the user inputName = new TextField(10);//Creates button for Search and Cancel on the dialogBtnGo = new Button("Search");BtnCn = new Button("Cancel");//Disables the Search button unitl a selection is made from the CheckBoxesBtnGo.setEnabled(false);//Adds event listeners to the Button.BtnGo.addActionListener(this);BtnCn.addActionListener(this);//Adds Item Listeners to the checkboxesoption1.addItemListener(this);//This will create spacer labels for the GridLayoutLabel space1, space2, space3;space1 = new Label(" ");space2 = new Label(" ");space3 = new Label(" ");//Add Controls to the dialog.add(Srch);add(Name);add(space1);add(option1);add(space2);add(space3);add(BtnGo);add(BtnCn);}//////This method handles all the events that take place on the dialogpublic void actionPerformed(ActionEvent e) {String str = e.getActionCommand();if (str.equals("Search")) {GoSrch();}if (str.equals("Cancel")) {

Page 14: Opac System Using Event Driven and Concurrent Programming

dispose();} }////////This will handle the events from clicking the ChecBoxes on the dialog the Search button will also be enable when a selection is made.public void itemStateChanged(ItemEvent e) {if (option1.getState() == true) {BtnGo.setEnabled(true);} }///////This method will search for the selected record in the databasepublic void GoSrch() {if (option1.getState() == true) {Srch1();} }/////This method will search the database by the name that is input into the TextFieldpublic void Srch1() {String dbuser = " ";String dbpasswd = " ";String DriverPrefix = "jdbc:odbc:";String DataSource = "Library";String mySearch = Name.getText();//This is the SQL String for retrieving data by name from the database.String SQL = "SELECT Name,Bookno,Author,Publication FROM Book WHERE Name = '" +mySearch+"'";//This loads the driver for the databasetry {Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");} catch (Exception e) {JOptionPane.showMessageDialog(null,""+e.getMessage(),"Database Driver Error", JOptionPane.WARNING_MESSAGE);}Statement stmt = null;Connection con = null;//Creates connection to the database.try {con = DriverManager.getConnection(DriverPrefix+DataSource,dbuser, dbpasswd);stmt = con.createStatement();} catch (Exception e) {JOptionPane.showMessageDialog(null, " "+e.getMessage(),"Cannot Connect to Database",JOptionPane.WARNING_MESSAGE);}ResultSet rs = null;//Executes the SQL query on the database and displays the result in a JFC OptionPanetry {rs = stmt.executeQuery(SQL);rs.next();

Page 15: Opac System Using Event Driven and Concurrent Programming

String Result = rs.getString(1) + " " + rs.getString(2) + "\n" + rs.getString(3) + "\n" + rs.getString(4);//Makes use of a swing OptionPane to display information of the successful search.JOptionPane.showMessageDialog(null,Result,"Record Found", JOptionPane.INFORMATION_MESSAGE);//Close the connection to the database.con.close();this.dispose();} catch (Exception e) {//Makes use of the JFC Swing OptionPane to display error messageJOptionPane.showMessageDialog(null ,"Record not Found","Warning", JOptionPane.INFORMATION_MESSAGE);} } }//////////////This class handles the menubar eventsclass myMenuHandler implements ActionListener {Library appbook;public myMenuHandler(Library appbook) {this.appbook = appbook;}//This code will display an Dialog Boxes for the different Menu Selectionspublic void actionPerformed(ActionEvent ae) {String arg = (String)ae.getActionCommand();//This code executed when Exit is selected on the Menu Barif (arg.equals("Exit")) {appbook.dispose();}//This will start the creation of the Add Dialogif (arg.equals("Add...")) {AddDlg Adlg = new AddDlg(appbook, "Add New Book");Adlg.setVisible(true);}//This will start the creation of the Edit Dialogif (arg.equals("Edit...")) {EditDlg Edlg = new EditDlg(appbook, "Edit Records");Edlg.setVisible(true);}//This will start the creation of the Delete Dialogif (arg.equals("Delete...")) {DelRec dlg = new DelRec(appbook, "Delete Records");dlg.setVisible(true);}//This will start the creation of the Search Dialogif (arg.equals("Search...")) {SearchDlg schDlg = new SearchDlg(appbook, "Search Records");schDlg.setVisible(true);} } }

Page 16: Opac System Using Event Driven and Concurrent Programming