INTERNAL ASSESSMENT TEST 2 Date : 28-09-15 Max Marks :50 Subject & Code : JAVA&J2EE(10IS753) Section: VII A&B Name of faculty : Mr.Sreenath M V Time : 11.30-1.00 PM Note: Answer any five questions 1) a) Explain the reader- writer problem with a program. 06 class Reader implements Runnable { Q q; Reader(Q q) { this.q = q; new Thread(this, "Reader").start(); public void run() { while(true) { q.read(); class Writer implements Runnable { Q q; Writer(Q q) { this.q = q; new Thread(this, "Writer").start(); public void run() { int i = 0; while(true) { q.write(i++);
class Q { int n; boolean valueset = false; synchronized int read() { if(!valueset) wait(); catch(interruptedexception e) { System.out.println("InterruptedException caught"); System.out.println("read: " + n); valueset = false; notify(); return n; synchronized void write(int n) { if(valueset) wait(); catch(interruptedexception e) { System.out.println("InterruptedException caught"); this.n = n; valueset = true; System.out.println("write: " + n); notify();
class WR { public static void main(string args[]) { Q q = new Q(); new Writer(q); new Reader(q); System.out.println("Press Control-C to stop."); b) What is an adapter class? Demonstrate, with an example. (04M) An adapter class provides an empty implementation of all methods in an event listener interface. Each adapter class implements the corresponding interface with a series of do-nothing methods. For example, MouseListener declares these five methods: public abstract void mouseclicked(mouseevent evt) public abstract void mousepressed(mouseevent evt) public abstract void mousereleased(mouseevent evt) public abstract void mouseentered(mouseevent evt) public abstract void mouseexited(mouseevent evt) Therefore, MouseAdapter looks like this: package java.awt.event; import java.awt.*; import java.awt.event.*; public class MouseAdapter implements MouseListener { public void mouseclicked(mouseevent evt) { public void mousepressed(mouseevent evt) { public void mousereleased(mouseevent evt) { public void mouseentered(mouseevent evt) {
public void mouseexited(mouseevent evt) { By subclassing MouseAdapter rather than implementing MouseListener directly, we can avoid having to write the methods you don't actually need. You only override those that you plan to actually implement. 2) What is transaction processing? Write a program to execute a database transaction. 10 A database transaction consists of a set of SQL statements, each of which must be successfully completed for the transaction to be completed. If one fails, SQL statements that executed successfully up to that point in the transaction must be rolled back. A database transaction isn t completed until the J2EE component calls the commit () method of the Connection object. All SQL statements executed prior to the call to the commit() method can be rolled back. However, once the commit() method is called, none of the SQL statements can be rolled back. The DBMS has an AutoCommit feature that is by default set to true and hence it is not absolutely necessary for any JEE component to call the commit() method. An example //Executing a database transaction String url = "jdbc:odbc:customerinformation"; String userid = "jim"; String password = "keogh"; Statement DataRequest1, DataRequest2; Connection Database; Class.forName ("sun.jdbc.odbc.jdbcodbcdriver"); Database = DriverManager.getConnection (url, userid, password); catch (ClassNotFoundException error) { System.err.println ("Unable to load the JDBC/ODBC bridge." + error);
System.exit (1); catch (SQLException error) { System.err.println ("Cannot connect to the database." + error); System.exit (2); Database.setAutoCommit (false); String query1 = UPDATE Customers SET Street = 5 Main Street + WHERE FirstName = Bob "; String query2 = UPDATE Customers SET Street = 10 Main Street + WHERE FirstName = Tim "; DataRequest1 = Database.createStatement (); DataRequest2 = Database.createStatement (); DataRequest1.executeUpdate (query1); DataRequest2.executeUpdate (query2); Database.commit (); DataRequest1.close(); DataRequest2.close(); Database.close(); catch (SQLException ex) { System.err.println ( SQLException: + ex.getmessage ()); if (Database!= null) { System.err.println ( Transaction is being rolled back ); Database.rollback (); catch (SQLException excep) { System.err.print ( SQLException: ); System.err.println (excep.getmessage ());
3) Explain the scrollable resultset with an example. 10 An example // Using a scrollable virtual cursor String url = "jdbc:odbc:customerinformation"; String userid = "jim"; String password = "keogh"; String printrow; String FirstName; String LastName; Statement DataRequest; ResultSet Results; Connection Db; Class.forName ("sun.jdbc.odbc.jdbcodbcdriver"); Db = DriverManager.getConnection (url, userid, password);
catch (ClassNotFoundException error) { System.err.println ("Unable to load the JDBC/ODBC bridge." + error); System.exit (1); catch (SQLException error) { System.err.println ("Cannot connect to the database." + error); System.exit (2); String query = "SELECT FirstName,LastName FROM Customers"; DataRequest = Db.createStatement (TYPE_SCROLL_INSENSITIVE); Results = DataRequest.executeQuery (query); catch (SQLException error) { System.err.println ("SQL error." + error); System.exit (3); boolean Records = Results.next ();
if (!Records) { System.out.println ("No data returned"); System.exit (4); do { Results.first (); Results.last (); Results.previous (); Results.absolute (10); Results.relative (-2); Results.relative (2); FirstName = Results.getString (1); LastName = Results.getString (2); printrow = FirstName + " " + LastName; System.out.println (printrow); while (Results.next ()); DataRequest.close ();
catch (SQLException error) { System.err.println Data display error." + error); System.exit (5); 4) Explain the mechanism of event delegation model. Give an example for using keyboard event. 10 The Delegation Event model This model defines standard and consistent mechanisms to generate and process events. 1. A source generates an event and sends it to one or more listeners. 2. The listener simply waits until it receives an event. 3. Once an event is received, the listener processes the event and then returns. 4. The advantage of this design is that the application logic that processes events is cleanly separated from the user interface logic that generates those events. 5. A user interface element is able to delegate the processing of an event to a separate piece of code. Using the Delegation Event Model Just follow these steps: 1. Implement the appropriate interface in the listener so that it will receive the type of event desired. 2. Implement the code to register and unregister (if necessary) the listener as a recipient for the event notifications.
Remember that a source may generate several types of events. Each event must be registered separately. Also, an object may register to receive several types of events, but it must implement all of the interfaces that are required to receive these events. // Demonstrate the key event handlers import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="simplekey" width=300 height=100> </applet> */ public class SimpleKey extends Applet implements KeyListener { String msg = ""; int X = 10, Y = 20; // output coordinates public void init () { addkeylistener (this); public void keypressed (KeyEvent ke) { showstatus ("Key Down");
public void keyreleased (KeyEvent ke) { showstatus("key Up"); public void keytyped (KeyEvent ke) { msg += ke.getkeychar (); repaint (); // Display keystrokes public void paint (Graphics g) { g.drawstring (msg, X, Y); 5) Describe the various steps of JDBC process with code snippets. The JDBC process 1. Load the driver 2. Define the connection URL 3. Establish the connection 4. Create a Statement object 5. Execute a query 6. Process the results 7. Close the connection Loading the JDBC driver Before a connection to a database can be established, the JDBC driver for that database must be loaded. Drivers automatically register themselves with the JDBC system when loaded. There are two ways to load a JDBC driver. The first is to specify the driver or colon-separated list of drivers on the command line: 10 > java -Djdbc.drivers=com.company1.Driver:com.company2.Driver MyApp
The second, and recommended method, is to call Class.forName() within the code: // Load the JDBC driver String drivername = "org.gjt.mm.mysql.driver"; Class.forName(driverName); catch (ClassNotFoundException e) { // Could not find the driver Connecting to the DBMS Once our driver is loaded, we can connect to the database. We'll connect via the driver manager class, which selects the appropriate driver for the database we specify. The java.sql.drivermanager class is the highest class in the java.sql hierarchy and is responsible for managing driver information. We identify our database through a URL. No, we're not doing anything on the web in this example - a URL just helps to identify our database. A JDBC URL starts with "jdbc:" This indicates the protocol (JDBC). We also specify our database in the URL. As an example, here's the URL for an ODBC datasource called 'demo'. Our final URL looks like this : jdbc:odbc:demo To connect to the database, we create a string representation of the database. We take the name of the datasource from the command line, and attempt to connect as user "dba", whose password is "sql". // Create a URL that identifies database String url = "jdbc:odbc:" + args[0]; // Now attempt to create a database connection Connection db_connection = DriverManager.getConnection (url, "dba", "sql"); The DriverManager.getConnection() method returns a Connection interface that is used throughout the process to reference the database.
Create and Execute database queries In JDBC, we use a statement object to execute queries. A statement object is responsible for sending the SQL statement, and returning a set of results, if needed, from the query. Statement objects support two main types of statements - an update statement that is normally used for operations which don't generate a response, and a query statement that returns data. // Create a statement to send SQL Statement db_statement = db_connection.createstatement(); Once you have an instance of a statement object, you can call its executeupdate and executequery methods. To illustrate the executeupdate command, we'll create a table that stores information about employees. We'll keep things simple and limit it to name and employee ID. // Create a simple table, which stores an employee ID and name db_statement.executeupdate ("create table employee { int id, char(50) name ;"); // Insert an employee, so the table contains data db_statement.executeupdate ("insert into employee values (1, 'John Doe');"); // Commit changes db_connection.commit(); Now that there's data in the table, we can execute queries. The response to a query will be returned by the executequery method as a ResultSet object. ResultSet objects store the last response to a query for a given statement object. Instances of ResultSet have methods following the pattern of getxx where XX is the name of a data type. Such data types include numbers (bytes, ints, shorts, longs, doubles, big-decimals), as well as strings, booleans, timestamps and binary data. // Execute query ResultSet result = db_statement.executequery ("select * from employee"); // While more rows exist, print them while (result.next() ) { // Use the getint method to obtain emp. id
System.out.println ("ID : " + result.getint("id")); // Use the getstring method to obtain emp. name System.out.println ("Name : " + result.getstring("name")); System.out.println (); Terminate the connection to the DBMS The connection to the DBMS is terminated by using the close() method of the Connection object once the J2EE component is finished accessing the DBMS. 6) What is multithreading? Write a program to create multiple threads in JAVA. // Create multiple threads. class NewThread implements Runnable { String name; // name of thread Thread t; NewThread(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("New thread: " + t); t.start(); // Start the thread // This is the entry point for thread. public void run() { for(int i = 5; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(1000); catch (InterruptedException e) { 10
System.out.println(name + "Interrupted"); System.out.println(name + " exiting."); class MultiThreadDemo { public static void main(string args[]) { new NewThread("One"); // start threads new NewThread("Two"); new NewThread("Three"); // wait for other threads to end Thread.sleep(10000); catch (InterruptedException e) { System.out.println("Main thread Interrupted"); System.out.println("Main thread exiting."); * * * * * *