25
0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 1 Vidyalankar T.Y. Diploma : Sem. VI [CO/CM/IF] Advanced Java Programming Prelim Question Paper Solution (i) FontMetric Given that the size of each font may differ and that fonts may be changed while your program is executing, there must be some way to determine the dimensions and various other attributes of the currently selected font. For example, to write one line of text after another implies that you have some way of knowing how tall the font is and how many pixels are needed between lines. To fill this need, the AWT includes the FontMetrics class, which encapsulates various information about a font. Table 1 : Some Methods Defined by FontMetrics Method Description int bytesWidth(byte b[ ], int start, int numBytes) Returns the width of numBytes characters held in array b, beginning at start. int chrWidth(char c[ ], int start, int numChars) Returns the width of numChars characters held in array c, beginning at start. int charWidth(char c) Returns the width of c. int charWidth(int c) Returns the width of c. int getAscent( ) Returns the ascent of the font. (ii) Use of URL class URL is the abbreviation of Unified Resource Locator. The web is a loose collection of higher-level protocols and file formats, all unified in a web browser. The main aspects of the web is that Tim Berners-Lee devised a scaleable way to locate all of the resources of the net. Once you can reliably name anything and everything, it becomes a very powerful paradigm. The Uniform Resource Locator perform this task. The URL provides a reasonable intelligible form to uniquely or identify or address information on the internet. URLs are ubiquitous, every browser uses them to identify information on the web. Web is really just that same old internet with all of its resources addressed as URLs plus HTML. Within Java’s network class library, the URL class provides a simple, conuse API to access information across the internet using URLs. The two constructors are : URL (string protocolName, String hostname, int port, String path) URL (String protocolName, String hostname, String path) 1. (a) 1. (a) Vidyalankar

Advanced Java Programming Vidyalankarvidyalankar.org/file/diploma/semvi_classroom_paper/...Advanced Java Programming Prelim Question Paper Solution (i) FontMetric Given that the size

Embed Size (px)

Citation preview

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 1

Vidyalankar T.Y. Diploma : Sem. VI [CO/CM/IF]

Advanced Java Programming Prelim Question Paper Solution

(i) FontMetric Given that the size of each font may differ and that fonts may be changed

while your program is executing, there must be some way to determine the dimensions and various other attributes of the currently selected font. For example, to write one line of text after another implies that you have some way of knowing how tall the font is and how many pixels are needed between lines. To fill this need, the AWT includes the FontMetrics class, which encapsulates various information about a font.

Table 1 : Some Methods Defined by FontMetrics

Method Description int bytesWidth(byte b[ ], int start, int numBytes)

Returns the width of numBytes characters held in array b, beginning at start.

int chrWidth(char c[ ], int start, int numChars)

Returns the width of numChars characters held in array c, beginning at start.

int charWidth(char c) Returns the width of c. int charWidth(int c) Returns the width of c. int getAscent( ) Returns the ascent of the font.

(ii) Use of URL class URL is the abbreviation of Unified Resource Locator. The web is a loose collection of higher-level protocols and file formats, all

unified in a web browser. The main aspects of the web is that Tim Berners-Lee devised a

scaleable way to locate all of the resources of the net. Once you can reliably name anything and everything, it becomes a very

powerful paradigm. The Uniform Resource Locator perform this task. The URL provides a reasonable intelligible form to uniquely or identify or

address information on the internet. URLs are ubiquitous, every browser uses them to identify information on

the web. Web is really just that same old internet with all of its resources

addressed as URLs plus HTML. Within Java’s network class library, the URL class provides a simple,

conuse API to access information across the internet using URLs. The two constructors are : URL (string protocolName, String hostname, int port, String path) URL (String protocolName, String hostname, String path)

1. (a)

1. (a)

Vidyala

nkar

Vidyalankar : T.Y. Diploma AJP

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 2

(iii) (1) JDBCODBC Bridge Driver JDBC bridge is used to access the ODBC drivers on the client side. The target database which is represented by the DSN is configured

by ODBC. Most database support ODBC access.

(2) JDBC-Native API In this type, JDBC API calls get converted into native C or C++ API

cable. These calls are unique and important to the database. It is necessary to install the vendor specific driver on each client

machine. Example Oracle Call Interface (OCI).

(3) JDBC Net pure Java The JDBC clients use standard network sockets to get connected

with middleware application server. The middleware application server translates the socket information

in call format required by DBMS and then forwards it to the database server.

This driver is very flexible as it does not need code installation on the client machine.

(4) 100% pure Java In this type, a pure java based driver communicates directly with the

vendors database through socket connection. This driver is used in two-tier architecture of java as it directly gets

connected to the database through the socket. Example : Mysor’s connector / J driver. (iv) The Transient and Volatile Modifiers Java defines two interesting type modifiers : transient and volatile. These

modifiers are used to handle somewhat specialized situations. When an instance variable to declared as transient, then its value need not

persist when an object is stored. For example : class T { transient int a; / / will not persist int b; / / will persist }

Here, if an object of type T is written to a persistent storage area, the

contents of a would not be saved, but the contents of b would. The volatile modifier tells the compiler that the variable modified by volatile

can be changed unexpected by other parts of your program. One of these situations involves multithreaded programs. In a multithreaded program, sometimes, two or more threads share the same instance variable. For efficiency considerations, each thread can keep its own, private coppy of

1. (a)

1. (a)

Vidyala

nkar

Prelim Question Paper Solution

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 3

such a shared variable. The real (or master) copy of the variable is updated at various times, such as when a synchronized method is entered. While this approach works fine, it may be inefficient at times. In some cases, all that really matters is that the master copy of a variable always reflects its current state. To ensure this, simply specify the variable as volatile, which tells the compiler that it must always use the master copy of a volatile variable (or, at least, always keep any private copies up to date with the master copy, and vice versa).

(i) Session tracking is the technique for maintaining particular session by which client communicate with server. a) A session can be created via the getSession( ) method of

HttpServletRequest. An HttpSession object is returned. This object can store a set of bindings that associate names with objects. The setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of HttpSession manage these bindings. It is important to note that session state is shared among all the servlets that are associated with a particular client.

b) HTTP is a stateless protocol. Each request is independent of the previous one. However, in some applications, it is necessary to save state information so that information can be collected from several interactions between a browser and a server. Sessions provide such a mechanism.

c) The following servlet illustrate how to use session state. The getSession ( ) method gets the current session. A new session is created if one does not already exist. The getAttribute( ) method is called to obtain the object that is bound to the name “date”. That object is a Date object that enscapsulates the date and time when this page was last accessed. (Of course, there is no such binding when the page is first accessed.) A Date object encapsulating the current date and time is then created. The setAttribute( ) method is called to bind the name “date” to this object.

Example

import java . io . * ; import java . util . * ; import java . servlet . * ; import javax.servlet.http.*; public class DateServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { / / Get the HttpSession object . HttpSession hs = request . getSession(true) ; / / Get writer. response . setContentType(“text/html”) ; PrintWriter pw = response . getWriter ( );

1. (b)

Vidyala

nkar

Vidyalankar : T.Y. Diploma AJP

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 4

pw.print(“<B>”) ; / / Display date/time of last access . Date date = (Date)hs.getAttribute (“date”) ; if (date ! = null) { pw.print(“Last access : ” + date + “<br>”) ; } / / Display current date/time . date = new Date ( ) ; hs . setAttribute(“date”, date) ; pw.println (“Current date: ” + date) ; } }

(ii) import java.net.*; class URLDemo {

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

URL hp = new URL (“http://www.msbte.com”); System.out.print\n(“port :” + hp.getPort( )); System.out.print\n(“Host :” + hp.getHost( ));

} }

import java.awt * ; import java.awt.event. * ; import java.applet.* ; public class [CMDemo extends Applet implement ActionListener [TextFields n1, n2, n3, LCM; Button btn_LCM Public void init ( ) { Label num1 = new Label (“Num1:” Label.RIGHT) ; Label num2 = new Label (“Num2:” Label.RIGHT) ; Label num3 = new Label (“Num3:” Label.RIGHT) ; n1 = new Textfield (2) ; n2 = new Textfield (2) ; n3 = new Textfield (2) ; LCM = new Textfield (8) ;

btn_LCM = new Button (FIND LCM”) ; add (num1) ; add (n1) ; add (num2) ; add (n2) ; add (num3) ; add (n3) ; add (btn_LCM) ; add (LCM) ;

1. (b)

2. (a)

Vidyala

nkar

Prelim Question Paper Solution

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 5

} Public void actionPerformed (ActionEvent ae) { find_LCM( ) ; } public void find_LCM ( ) { int n1, n2, n3, X, Y, Z, q ; try { n1 = Integer.ParseInt(n1.getText( )) ; n2 = Integer.ParseInt(n2.getText( )) ; n3 = Integer.ParseInt(n3.getText( )) ; } Catch(NumberFormatException X) { System.out.println (“Error : ” * getmessage( ) ) } if (n1 50 && n2 50 && n3 50) { X = n1; Y = n2 while (X! = Y) { if (X > Y) x = X Y ; else y = Y X ; } Z = (n1 * n2) / n1 . q = n3 ; while (Z! = q) { if (Z > q) Z = Z q ; else q = q Z ; } LCM . setText(Z) ; } else { system.out.println (“Enter no. below than 50”) ; } } } import java.sql.*; public class AccessDatabases {

public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test", "root", "root");

2. (b) Vidy

alank

ar

Vidyalankar : T.Y. Diploma AJP

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 6

Statement st = con.createStatement(); DatabaseMetaData meta = con.getMetaData(); ResultSet rs = meta.getTables(null, null, "%", null); String tableNames = ""; while (rs.next()) { tableNames = rs.getString(3); System.out.println(tableNames); } } catch (Exception e) { } }

}

WAP to demonstrate use of checkbox and checkboxGroup class // Demonstrate checkbox group import java.awt.*; import java.awt.event.*; import java.applet.*; /* < applet code = “CBGroup” width = 250 height = 200> </applet> */ public class CBGroup extends Applet implements ItemListener { String msg = “ ”; Checkbox win98, winNT, solaris, mac; CheckboxGroup cbg; public void int ( ) cbg = new checkboxGroup ( ); win98 = new checkbox (“windows 98/xp”, cbg, true); winNT = new checkbox (“Windows NT/2000”, cbg, false) solaris = new checkbox (“solaris”, cbg, false); mac = new checkbox (“Macos”, cbg, false); add(win 98); add(win NT); add(solaris); add(mac); win98 . addItemListener (this); winNT. addItemListener (this); solaris . addItemListener (this); mac . addItemListener (this); } public void itanstate Changed (ItemEvent i.e.) {

2. (c)

Vidyala

nkar

Prelim Question Paper Solution

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 7

repaint ( ); } // Display current state of the check boxes

public void paint (Graphics g) { msg = “current selection:”; msg + = cbg.getSelected Checkbox ( ). getLable ~; g drawstring (msg, b, 100); }

}

Frame Frame encapsulates what is commonly throught of as a “window”. It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners. Create a Frame Creating a new frame window from within an applet is actually quite easy. First, create a subclass of Frame. Next, override any of the standard window methods, such as init( ), start( ), stop( ), and paint( ). Finally, implement the windowClosing( ) method of the WindowListener interface, calling setVisible(false) when the window is closed. Once you have defined a Frame subclass, you can create an object of that class. This causes a frame window to come into existence, but it will not be initially visible. You make it visible by calling setVisible( ). When created, the window is given a default height and width. You can set the size of the window explicitly by calling the setSize( ) method. Example / / Create a child frame window from within an applet. import java.awt. * ; import java.awt.event.* ; import java.applet.* ; / * <applet code=“AppletFrame” width=300 height=50> </applet> */ / / Create a subclass of Frame class SampleFrame extends Frame { SampleFrame (String title) { super(title) ; / / create an object to handle window events MyWindowAdapter adapter = new MyWindowAdapter (this) ; / / register it to receive those events addWindowListener (adapter) ; } public void paint (Graphics g) {

3. (a)

Vidyala

nkar

Vidyalankar : T.Y. Diploma AJP

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 8

g.drawString(“This is in frame window”, 10, 40) ; } } Class MyWindowAdapter extends WindowAdapter { SampleFrame sampleFrame ; public MyWindowAdapter (SampleFrame sampleframe) { this.sampleFrame = sampleFrame ; } public void windowClosing (WindowEvent we) { sampleFrame.setVisible (false) ; } } / / Create frame window. public class AppletFrame extends Applet { Frame f ; public void init ( ) { f = new SampleFrame (“A Frame Window”) ; f.setSize (250, 250) ; f.setVisible (true) ; } public void start ( ){ f.setVisible (true) ; } public void stop ( ) { f.setVisible (false) ; } public void paint (Graphics g) { g.drawString (“This is in applet window”, 10, 20) ; } } Proxy Servers A proxy server speaks the client side of a protocol to another server. Purpose i) This is often required when clients have certain restrictions on which servers

they can connect to. Thus, a client would connect to a proxy server, which did not have such restrictions, and the proxy server would in turn communicate for the client.

ii) A proxy server has the additional ability to filter certain requests or cache the results of those requests for future user.

iii) A caching proxy HTTP server can help reduce the bandwidth demands on a local network’s connection to the Internet.

iv) When a popular web site is being hit by hundreds of users, a proxy server can get the contents of the web server’s popular pages once, saving expensive internetwork transfers while providing faster access to those pages to the clients.

3. (b)

Vidyala

nkar

Prelim Question Paper Solution

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 9

Client Sockets use i) The creation of a Socket object implicitly establishes a connection between

the client and server. ii) Once the Socket object has been created, it can also be examined to gain

access to the input and output streams associated with it. Each of these methods can throw an IOException if the sockets have been invalidated by a loss of connection on the Net.

Server Sockets i) When you create a ServerSocket, it will register itself with the system as

having an interest in client connections. ii) The constructors for ServerSocket reflect the port number that you wish to

accept connections on and, optionally, how long you want the queue for said port to be. The queue length tells the system how many client connections it can leave pending before it should simply refuse connections.

iii) ServerSocket has a method called accept( ), which is a blocking call that will wait for a client to initiate communications, and then return with a normal Socket that is then used for communications with the client.

Steps required for establish communication between client and server sockets

Server Client Listens to port 80 Connects to port 80 Accepts the connection. Writes “GET/index.html

HTTP/1.0\n\n.” Reads up until the second end-of-line (\n). Sees that GET is a known command and that HTTP/1.0 is a valid protocol version.

Reads a local file called.index.html. Writes “HTTP/1.0 200 ok \n\n. “200” means “here comes the

file”. Copies the contents of the file. Into the socket. Hangs up.

Reads the contents of the file and displays it. Hangs up.

Difference between AWT and Swing

AWT Swing 1. AWT use Applet for running GUI

applications. Swing uses JApplet for running GUI applications.

2. AWT has use collection of classes and interfaces.

Swing is a bigger collection of classes and interfaces than AWT.

3. AWT provides less features and components than swings.

Swings has variety of component and features which are not present in AWT.

4. This is platform dependent code. This is platform independent code.

3. (c)

3. (d) Vidy

alank

ar

Vidyalankar : T.Y. Diploma AJP

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 10

5. AWT has predefined formats of appearance and behaviour of element.

Swings provides a facility of different appearance and behaviour of the same element.

Internet Addressing Every computer on the Internet has an address. An Internet address is a number that uniquely identifies each computer on the Net. Originally, all Internet addresses consisted of 32-bit values. This address type was specified by IPv4 (Internet Protocol, version 4). However, a new addressing scheme, called IPv6 (Internet Protocol, version 6) has come into play. IPv6 uses a 128-bit value to represent an address. Although there are several reasons for and advantages to IPv6, the main one is that it supports a much larger address space than does IPv4. Fortunately, IPv6 is downwardly compatible with IPv4. Currently, IPv4 is by.far the most widely used scheme, but this situation is likely to change over time. Because of the emerging importance of IPv6, Java 2, version 1.4 has begun to add support for it. However, at the time of this writing, IPv6 is not supported by all environments Furthermore, for the next few years, IPv4 will continue to be the dominant form of addressing. For these reasons, the form of Internet addresses discussed here, and used in this chapter, are the IPv4 form. As mentioned, IPv4 is, loosely, a subset of IPv6, and the material contained in this chapter is largely applicable to both forms of addressing. There are 32 bits in an IPv4 IP address, and we often refer to them as a sequence of four numbers between 0 and 255 separated by dots (.). This makes them easier to remember, because they are not randomly assigned—they are hierarchically assigned. The first few bits define which class of network, lettered A, B, C, D, or E, the address represents. Most Internet users are on a class C network, since there are over two million networks in class C. The first byte of a class C network is between 192 and 224, with the last byte actually identifying an individual computer among the 256 allowed on a single class C network. This scheme allows for half a billion devices to live on class C networks. (i) boolean execute(String SQL) : Returns a boolean value of true if a

ResultSet object can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL.

int executeUpdate(String SQL) : Returns the numbers of rows affected

by the execution of the SQL statement. Use this method to execute SQL statements for which you expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE statement.

ResultSet executeQuery(String SQL) : Returns a ResultSet object.

Use this method when you expect to get a result set, as you would with a SELECT statement.

(ii) (a) getItemCount ( ) : Used to obtain the number of items in the list.

(b) getItem (int index) :

3. (e)

4. (a)

4. (a)

Vidyala

nkar

Prelim Question Paper Solution

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 11

Given an index, you can obtain the name associated with the item at that index.

(c) add (sring name, int index) : It is overloaded method and used to add items into the list, name indicate

the item and index indicate the location in the list where it will be added. You can specify 1 to add the item to the end of the list.

(d) select (int index) : Used to set the currently selected item.

(iii) Navigation Methods (a) boolean first ( ) Takes the control to the first row of the ResultSet. Returns true if the

valid row. (b) boolean previous ( ) Takes the control to the last row of the ResultSet. Returns true if the

current row is first row of ResultSet. (c) boolean isLast ( ) Returns true if the current row is first row of ResultSet. (d) boolean isFirst ( ) Returns true if the current row is first row of ResultSet.

(iv) Program

import java.io.*; import javax.servlet.*; import javax.servlet.http.* ; public class ColorGetServlet extends HttpServlet { public void doGet (HttpservletRequest request, HttpServletResponse response) throws ServletException, IOException { String color = request.getParameter(“color”) ; response.setContentType (“text/html”) ; PrintWriter pw = response.getWriter ( ) ; pw.println(“<B>The selected color is: ”) ; pw.println (color) ; pw.close ( ) ; } }

(i) Program import javax.swing.JButton; import javax.swing.JFrame; import java.awt.Color; import java.awt.Container;

4. (a)

4. (a)

4. (b)

Vidyala

nkar

Vidyalankar : T.Y. Diploma AJP

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 12

import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.Graphics; import java.awt.Image; import javax.swing.ImageIcon; import javax.swing.JApplet; import java.awt.*; public class new2 extends JFrame implements ActionListener { private boolean b1,b2; Container contentPane= getContentPane(); JButton awar=new JButton("@war"); JButton arrow=new JButton("arrow"); private Image image1,image2; public new2() { setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); contentPane.setLayout(new FlowLayout()); awar.addActionListener(this); contentPane.add(awar).setVisible(true); arrow.addActionListener(this); contentPane.add(arrow).setVisible(true); } public void init() { image1=Toolkit.getDefaultToolkit().getImage("@war.jpeg"); image2=Toolkit.getDefaultToolkit().getImage("arrow.gif"); } public void paint(Graphics g) { if(b1==true) { g.drawImage(image1,0,0,this); } else if(b2==true) {

Vidyala

nkar

Prelim Question Paper Solution

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 13

g.drawImage(image2,0,0,this); } } public void actionPerformed(ActionEvent event) { String actionCommand = event.getActionCommand(); if(actionCommand.equals("@war")) { b1=true; } else if(actionCommand.equals("arrow")) { b2=true; } repaint(); } public static void main(String args[]) { new2 m=new new2(); m.setVisible(true); } (ii) Two constructor for JTree A tree is a component that presents a hierarchical view of data. A user has

the ability to expand or collapse individual subtrees in this display. Trees are implemented in Swing by the JTree class, which extends JComponent.

JTree(Hashtable ht) JTree(Object obj[ ]) JTree(TreeNode tn) JTree(Vector v)

Here are steps that you should follow to use a tree in an applet (a) Create a JTree object. (b) Create a Jscrollpane object (The arguments to the constructor specify

the tree and the policies for vertical and horizontal scrollbars). (c) Add the tree to the scrollpane. (d) Add the scrollpane to the content pane of the applet.

Chained Exceptions The chained exception feature allows you to associate another exception with an exception. This second exception describes the cause of the first exception. For example, imagine a situation in which a method throws an ArithmeticException because of an attempt to divide by zero. However, the actual cause of the problem was that an I/O error occurred, which caused the divisor to be set improperly. Although the method must certainly throw an ArithmeticException, since that is the error that occurred, you might also want to let the calling code

4. (b)

5. (a) Vidy

alank

ar

Vidyalankar : T.Y. Diploma AJP

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 14

know that the underlying cause was an I/O error. Chained exceptions let you handle this, and any other situation in which layers of exceptions exist. Example

class ChainExcDemo { static void demoproc ( ) { / / create an exception NullPointerException e = new NullPointerException (“top layer”) ; / / add a cause e.initCause (new ArithmeticException(“cause”) ) ; throw e ; } public static void main (String args [ ]) { try { demoproc ( ) ; } catch (NullPointerException e) { / / display top level exception System.out.println (“Caught : ” + e) ; / / display cause exception System.out.println(“Original causes : ” + e.getCause ( ) ) ; } }

}

Program // Demonstrate Choice lists import java.awt. * ; import java.awt . event . * ; import java . applet . * ; /* applet code = “ChoiceDemo” width = 300 height = 180 > < / applet> * / public class ChoiceDemo extends Applet implements ItemListener { Choice os ; String msg = “ ” ; public void init ( ) { os = new Choice ( ) ; / / add items to os list os.add (“mouse”) ; os.add (“keyboard”) ;

5. (b)

Vidyala

nkar

Prelim Question Paper Solution

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 15

os.add (“battery”) ; os.add (“UPS”) ; os.add (“Stabilizer”) ; add (os) ; / / register to receive item events os . addItemListener (this) ; } public void itemStateChanged (ItemEvent ie) { repaint ( ) ; } / / Display current selections . public void paint (Graphics g) { msg = “Currentitem : ” ; msg += browser.getSelectedItem ( ) ; g.drawString (msg, 6, 140) ; } } Default Mutable TreeNode The TreeNode interface declares methods that obtain information about a tree node. For example, it is possible to obtain a reference to the parent node or an enumeration of the child nodes. The MutableTreeNode interface extends TreeNode. It declares methods that can insert and remove child nodes or change the parent node. The DefaultMutableTreeNode class implements the MutableTreeNode interface. It represents a node in a tree. One of its constructors is shown here : DefaultMutableTreeNode(Object obj) Here, obj is the object to be enclosed in this tree node. The new tree node doesn’t have a parent or children. To create a hierarchy of tree nodes, the add( ) method of DefaultMutableTreeNode can be used. Its signature is shown here : void add(MutableTreeNode child) Here, child is a mutable tree node that is to be added as a child to the current mode. The Life Cycle of a Servlet Three methods are central to the life cycle of servlet. These are init( ), service( ), and destroy( ). They are implemented by every servlet and are invoked at specific times by the server. Let us consider a typical user scenario to understand when these methods are called.

5. (c)

5. (d)

Vidyala

nkar

Vidyalankar : T.Y. Diploma AJP

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 16

First, assume that a user enters a Uniform Resource Locator (URL) to a Web browser. The browser then generates an HTTP request for this URL. This request is then sent to the appropriate server. Second, this HTTP request is received by the Web server. The server maps this request to a particular servlet. The servlet is dynamically retrieved and loaded into the address space of the server. Third, the server invokes the init( ) method of the servlet. This method is invoked only when the servlet is first loaded into memory. It is possible to pass initialization parameters to the servlet so it may configure itself. Fourth, the server invokes the service( ) method of the servlet. This method is called to process the HTTP request. You will see that it is possible for the servlet to read data that has been provided in the HTTP request. It may also formulate an HTTP response for the client. The servlet remains in the server’s address space and is available to process any other HTTP requests received from clients. The service( ) method is called for each HTTP request. Finally, the server may decide to unload the servlet from its memory. The algorithms by which this determination is made are specific to each server. The server calls the destroy( ) method to relinguish any resources such as file handles that are allocated for the servlet. Important data may be saved to a persistent store. The memory allocated for the servlet and its objects can then be garbage collected. doGet( ) method : used to override the HTTPGET Requests. doPost( ) method : Used to override the HTTPPOST Requests. Program / / Illustrate menus . import java . awt . * ; import java . awt . event . * ; import java . applet . * ;

/ * <applet code=”MenuDemo” width = 250 height = 250 > </applet> * / / / Create a subclass of Frame class MenuFrame extends Frame { String msg = “ ” ; CheckboxMenuItem debug, test ; MenuFrame (String title) { super (title) ;

5. (e)

Vidyala

nkar

Prelim Question Paper Solution

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 17

/ / create menu bar and add it to frame Menubar mbar = new MenuBar ( ) ; setMenuBar (mbar) ; / / create the menu items Menu file = new Menu (“File”) ; MenuItem item1, item2, item3, item4, item5 ; file.add (item1 = new MenuItem (“New”)) ; file.add (item2 = new MenuItem (“Open”)) ; file.add (item3 = new MenuItem (“Close”)) ; file.add (item4 = new MenuItem (“”)) ; file.add (item5 = new MenuItem (“Quit”)) ; mbar.add (file) ; Menu edit = new Menu (“Edit”) ; MenuItem item6, item7, item8, item9 ; edit.add (item6 = new MenuItem (“Cut”) ) ; edit.add (item7 = new MenuItem (“Copy”) ) ; edit.add (item8 = new MenuItem (“Paste”) ) ; edit.add (item9 = new MenuItem (“”) ) ; Menu sub = new Menu (“Special”) ; MenuItem item10, item11, item12 ; sub.add (item10 = new MenuItem (“First”) ) ; sub.add (item11 = new MenuItem (“Second”) ) ; sub.add (item12 = new MenuItem (“Third”) ) ; edit.add (sub) ; / / these are checkable menu items debug = new CheckboxMenuItem (“Debug”) ; edit.add (debug) ; test = new CheckboxMenuItem (“Testing”) ; edit.add (test) ; mbar.add (edit) ; } public void paint (Graphics g) { g.drawString (msg, 10, 200) ; if (debug.getState ( ) ) g.drawString (“Debug is on.” , 10, 220) ; else g.drawString (“Debug is off.”, 10, 220) ; if(test.getState ( ) ) g.drawString (“Testing is on.”, 10, 240) ; else g.drawString (“Testing is off.”, 10, 240) ; }

Vidyala

nkar

Vidyalankar : T.Y. Diploma AJP

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 18

} / / Create frame window. public class MenuDemo extends Applet { Frame f; public void init ( ) { f = new MenuFrame (“Menu Demo”) ; int width = Integer.parseInt (getParameter (“width”) ) ; int width = Integer.pareseInt (getParameter (“height”) ) ; setSize (new Dimension (width, height) ) ; f.setSize (width, height) ; f.setVisible (true) ; } public void start ( ) { f.setVisible (true) ; } public void stop ( ) { f.setVisible (false) ; } }

JTable class A table is a component that displays rows and columns of data. You can drag the cursor on column boundaries to resize columns. You can also drag a column to a new position. Tables are implemented by the JTable class, which extends JComponent. One of its constructors is shown here:

JTable(Object data[ ][ ], Object colHeads[ ])

Here, data is a two-dimensional array of the information to be presented, and colHeads is a one-dimensional array with the column headings. Here are the steps for using a table in an applet: i) Create a JTable object. ii) Create a JScrollPane object. (The arguments to the constructor specify the

table and the policies for vertical and horizontal scroll bars.) iii) Add the table to the scroll pane. iv) Add the scroll pane to the content pane of the applet. The following example illustrates how to create and use a table. The content pane of the JApplet object is obtained and a border layout is assigned as its layout manager. A one-dimensional array of strings is created for the column headings. This table has three columns. A two-dimensional array of strings is created for the table cells. You can see that each element in the array is an array of three strings. These arrays are passed to the JTable constructor. The table is added to a scroll pane and then the scroll pane is added to the content pane.

import Java.awt.*;

6. (a)

Vidyala

nkar

Prelim Question Paper Solution

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 19

import javax.swing.*; /* <applet code= “JTableDemo” width=400 height=200> </applet> */ public class JTableDemo extends JApplet { public void init( ) { // Get content pane Container contentPane = getContentPane( ); // Set layout manager contentPane.setLayout(new BorderLayout( )); // Initialize column headings final String[] colHeads = {“Name”, “Phone”, “Fax”}; // Initialize data final Object[] [] data = { {“Gail”, “4567”, “8675”}, {“Ken”, “7566”, “5555”}, {“Viviane”, “5634”, “5887”}, {“Melanie”, “7345”, “9222”}, {“Anne”, “1237”, “3333”}, {“John”, “5656”, “3144”}, {“Matt”, “5672”, “2176”}, {“Claire”, “6741”, “4244”}, {“Erwin”, “9023”, “5159”}, {“Ellen”, “1134”, “5332”}, {“Jennifer”, “5689”, “1212”}, {“Ed”, “9030”, “1313”}, {“Helen”, “6751”, “1415”} }; // Create the table JTable table = new JTable(data, colHeads); // Add table to a scroll pane int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp = new JScrollPane(table, v, h); // Add scroll pane to the content pane contentPane.add(jsp, BorderLayout.CENTER); } } (i) JTabbed Panes A tabbed pane is a component that appears as a group of folders in a file

cabinet. Each folder has a title. When a user selects a folder, its contents become visible. Only one of the folders may be selected at a time. Tabbed panes are commonly used for setting configuration options.

Tabbed panes are encapsulated by the JTabbedPane class, which extends JComponent.

6. (b) Vidy

alank

ar

Vidyalankar : T.Y. Diploma AJP

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 20

(ii) JTree A tree is a component that presents a hierarchical view of data. A user has

the ability to expand or collapse individual subtrees in this display. Trees are implemented in Swing by the JTree class, which extends JComponent.

JTree(Hashtable ht) JTree(Object obj[ ]) JTree(TreeNode tn) JTree(Vector v)

(iii) JScrollPanes A scroll pane is a component that presents a rectangular area in which a

component may be viewed. Horizontal and / or vertical scroll bars may be provided if necessary. Scroll panes are implemented in Swing by the JScrollPane class, which extends JComponent.

(iv) JTabbles A table is a component that displays rows and columns of data. You can drag

the cursor on column boundaries to resize columns. You can also drag a column to a new position. Tables are implemented by the JTable class, which extends JComponent.

The javax.servlet Package The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate. The following table summarizes the core interfaces that are provided in this package. The most significant of these is Servlet. All servlets must implement this interface or extend a class that implements the interface. The ServletRequest and ServletResponse interfaces are also very important. Interface Description Servlet Declares life cycle methods for a servlet. ServletConfig Allows servlets to get initialization parameters. ServletContext Enables servlets to log events and access information about their environment. ServletRequest Used to read data from a client request. ServletResponse Used to write data to a client response. SingleThreadModel Indicates that the servlet is thread safe. The Servlet Interface All servlets must implement the Servlet interface. It declares the init( ), service( ), and destroy( ) methods that are called by the server during the life cycle of a servlet. A method is also provided that allows a servlet to obtain any initialization parameters. The methods defined by Servlet are shown in Table 1. Table 1 : The Methods Defined by Servlet Method Description void destroy( ) Called when the servlet is unloaded. ServletConfig getServletConfig( )

Returns a ServletConfig object that contains any initialization parameters.

String getServletInfo( ) Returns a string describing the servlet.

6. (c)

Vidyala

nkar

Prelim Question Paper Solution

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 21

void init(ServletConfig sc) throws ServletException

Called when the servlet is initialized. Initialization parameters for the servlet can be obtained from sc. An UnavailableException should be thrown if the servlet cannot be initialized.

void service(ServletRequest req, ServletResponse res) throws ServletException, IOException

Called to process a request from a client. The request from the client can be read from req. The response to the client can be written to res. An exception is generated if a servlet or IO problem occurs.

Method Description void destroy() Called when the servlet is unloaded. ServletConfig getServletConfig( ) Returns a ServletConfig object that contains any initialization parameters. String getServletInfo( ) Returns a string describing the servlet. void init(ServlelConfig sc) throws ServletException Called when the servlet is initialized. Initialization parameters for the servlet can be obtained from sc. An UnavailableException should be thrown if the servlet cannot be initialized. void service(ServletRequest req, ServletResponse res) throws ServletException, IOException Called to process a request from a client. The request from the client can be read from req. The response to the client can be written to res. An exception is generated if a servlet or iO problem occurs. The init( ), service( ), and destroy( ) methods are the life cycle methods of the servlet. These are invoked by the server. The getServletConfig( ) method is called by the servlet to obtain initialization parameters. A servlet developer overrides the getServletInfo( ) method to provide a string with useful information (for example, author, version, date, copyright). This method is also invoked by the server. The ServletConfig Interface The ServletConfig interface is implemented by the server. It allows a servlet to obtain configuration data when it is loaded. The methods declared by this interface are summarized here: Method Description ServletContext getServletContext( ) Returns the context for this servlet. String getlnitParameter(String param) Returns the value of the initialization parameter named param. Enumeration get!nitParameterNames( ) Returns an enumeration of all initialization parameter names. String getServletName( ) Returns the name of the invoking servlet. The ServletContext Interface The ServletContext interface is implemented by the server. It enables servlets to obtain information about their environment. Several of its methods are summarized in Table 2. Table 2 : The Methods Defined by ServletContext.

Vidyala

nkar

Vidyalankar : T.Y. Diploma AJP

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 22

Method Description Object getAttribute(String attr) Returns the value of the server attribute

named attr. String getMimeType(String file) Returns the MIME type of file. String getRealPath(String vpath) Returns the real path that corresponds to

the virtual path vpath. String getServerInfo( ) Returns information about the server. Servlet getServlet(String sname) throws ServletException

Returns the servlet named sname.

Enumeration getServletNames( ) Returns an enumeration with the names of servlets in the same namespace in the server.

void log(String s) Writes s to the server log. void log(Exception e, String s) Write s and the stack trace for e to the

server log. The ServletRequest Interface The ServletRequest interface is implemented by the server. It enables a servlet to obtain information about a client request. Several of its methods are summarized in Table 3. Table 3 : The Methods Defined by ServletRequest.

Method Description String getAttribute(String attr) Returns the value of the attribute

named attr. String getCharacterEncoding( ) Returns the character encoding of the

request. int getContentLength( ) Returns the size of the request. The

value –1 is returned if the size is not known.

String getContentType( ) Returns the type of the request. A null value is returned if the type cannot be determined.

ServletInputStream getInputStream( ) throws IOException

Returns a ServletInputStream that can be used to read binary data from the request. An IllegalStateException is thrown if getReader( ) has already been invoked for this request.

String getParameter(String pname) Returns the value of the parameter named pname.

Enumeration getParameterNames( ) Returns an enumeration of the parameter names for this request.

String[ ] getParameterValues( ) Returns an enumeration of the parameter values for this request.

String getProtocol( ) Returns a description of the protocol. BufferedReader getReader( ) Returns a buffered reader that can be

Vidyala

nkar

Prelim Question Paper Solution

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 23

throws IOException used to read text from the request. An IllegalStateException is thrown if getInputStream( ) has already been invoked for this request.

String getRealPath(String vpath) Returns the real path corresponding

to the virtual path vpath. String getRemoteAddr( ) Returns the string equivalent of the

client IP address. String getRemoteHost( ) Returns the string equivalent of the

client host name. String getScheme( ) Returns the transmission scheme of

the URL used for the request (e.g. "http", "ftp").

String getServerName( ) Returns the name of the server. int getServerPort( ) Returns the port number.

The ServletResponse Interface The ServletResponse interface is implemented by the server. It enables a servlet to formulate a response for a client. Several of its methods are summarized in Table 4. Table 4 : The Methods Defined by ServletResponse.

Method Description String getCharacterEncoding( ) Returns the character encoding for

the response. ServletOutputStream getOutputStream( ) throws IOException

Returns a ServletOutputStream that can be used to write binary data to the response. An IllegalStateException is thrown if getWriter( ) has already been invoked for this request.

PrintWriter getWriter( ) throws IOException

Returns a PrintWriter that can be used to write character data to the response. An IllegalStateException is thrown if getOutputStream( ) has already been invoked for this request.

void setContentLength(int size) Sets the content length for the response to size.

void setContentType(String type) Sets the content type for the response to type.

The SingleThreadModel Interface This interface is used to indicate that only a single thread will execute the service( ) method of a servlet at a given time. It defines no constants and declares no methods.

Vidyala

nkar

Vidyalankar : T.Y. Diploma AJP

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 24

If a servlet implements this interface, the server has two options. First, it can create several instances of the servlet. When a client request arrives, it is sent to an available instance of the servlet. Second, it can synchronize access to the servlet. isAlive( ) It is used to determine whether the thread is running or not. join( ) This method waits until the thread on which it is called terminates. Its name comes from the concept of the calling thread waiting until the specified thread joins it. Additional forms of join( ) allow you to specify a maximum amount of time that you want to wait for the specified thread to terminate. Program

/ / Using join ( ) to wait for threads to finish. 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 ( ) { try { for (int i = 5; i > 0; i ) { System.out.println (name + “ : ” + i) ; Thread.sleep (1000) ; } } catch (InterruptedException e) { System.out.println (name + “ interrupted.” ) ; } System.out.println (name + “ exiting.” ) ; }

} class DemoJoin { public static void main (String args [ ]) { NewThread ob1 = newThread (“One”) ; NewThread ob2 = newThread (“Two”) ; NewThread ob3 = newThread (“Three”) ;

6. (d)

Vidyala

nkar

Prelim Question Paper Solution

0414/TY/Pre_Pap/2014/CP/Comp/AJP_Soln 25

System.out.println (“Thread One is alive: ” + ob1.t.isAlive ( ) ) ; System.out.println (“Thread Two is alive: ” + ob2.t.isAlive ( ) ) ;

System.out.println (“Thread Three is alive: ” + ob3.t.isAlive ( ) ) ; / / wait for threads to finish try { System.out.println (“Waiting for threads to finish.”) ; ob1.t.join ( ) ; ob2.t.join ( ) ; ob3.t.join ( ) ; } catch (InterruptedException e) { System.out.println (“Main thread interrupted”) ; } System.out.println (“Thread One is alive : ” + ob1.t.isAlive ( ) ) ; System.out.println (“Thread Two is alive : ” + ob2.t.isAlive ( ) ) ; System.out.println (“Thread Three is alive : ” + ob3.t.isAlive ( ) ) ; System.out.println (“Main thread exiting.”) ; } } Use of Prepared statement and Callable statement interface

Interfaces Recommended Use Statement Use for general-purpose access to your database.

Useful when you are using static SQL statements at runtime. The Statement interface cannot accept parameters.

PreparedStatement Use when you plan to use the SQL statements many times. The PreparedStatement interface accepts input parameters at runtime.

CallableStatement Use when you want to access database stored procedures. The CallableStatement interface can also accept runtime input parameters.

6. (e)

Vidyala

nkar