AJP

782 views

Published on

Published in: Engineering, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
782
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
8
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

AJP

  1. 1. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 1 of 38 Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in themodel answer scheme. 2) The model answer and the answer written by candidate may vary but the examiner may tryto assess the understanding level of the candidate. 3) The language errors such as grammatical, spelling errors should not be given moreImportance (Not applicable for subject English and Communication Skills). 4) While assessing figures, examiner may give credit for principal components indicated in thefigure. The figures drawn by candidate and model answer may vary. The examiner may givecredit for anyequivalent figure drawn. 5) Credits may be given step wise for numerical problems. In some cases, the assumed constantvalues may vary and there may be some difference in the candidate’s answers and model answer. 6) In case of some questions credit may be given by judgement on part of examiner of relevantanswer based on candidate’s understanding. 7) For programming language papers, credit may be given to any other program based on equivalentconcept. 1. A) Attempt any three of the following: Marks 12 a) List any eight controls from java. awt package. 4 (Each ½ Mark any Eight) Ans: 1. Label 2. Button 3. Checkbox 4. Choice list 5. List 6. Scrollbar 7. Text Field 8. Text Area 9. Menu and Menubar 10. Canvas
  2. 2. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 2 of 38 b) Explain use of button control in AWT with example. 4 (Defination-1 Mark, Methods-1 Mark, Example-2 Marks) Ans: A button is a component that contains a label and that generates an event when it is pressed. buttons are object of type Button. Button defines Button() Button(String str) After a button has been created,you can set its label by calling setLabel(). You can retrieve its label by calling getLabel() Void setLabel(String str) String getLabel() Example: import java.awt.*; import java.applet.*; /*<applet code=”MyButtonDemo” width=250 Height=150> </applet> public class mybuttondemo extends Applet { Button ok,cancel,apply; public void init() { ok= new Button(“ok”); cancel= new Button(“cancel”); apply= new Button(“apply”); add(ok); add(cancel); add(apply); } }
  3. 3. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 3 of 38 c) List four differences between TCP and UDP. 4 (Any four Points -1 Mark each) Ans: TCP UDP It is connection Oriented It is connectionless It gives acknowledgement It does not give acknowledgement It is reliable It is unreliable It is use to transfer for large amount of data It is use to transfer for small amont of data Transmission seed is low Transmission seed is High TCP header size is 20 bytes UDP Header size is 8 bytes TCP does error checking UDP does error checking, but no recovery options d) Write three factory method of InetAddress class. 4 (Three method- 4 Marks) Ans: The Inet class has no invisible constructor. To create an Inet address object,you have to use one of the available factory methods. Factory methods are merely aconvention whereby static methods in a class returns an instance of that class. Three commonly used InetAddress factory methods are 1) static InetAddress getLocalHost() throws unKnownHostException This method simply returns the InetAddress object that represents the local host. 2) static InetAddress getByName(String hostname) throws unKnownHostException This method simply returns the InetAddress for a host name passed to it. 3) static InetAddress[] getAllByName(String hostname) throws unKnownHostException which takes an IPaddress and returns an InetAddress object.
  4. 4. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 4 of 38 B) Attempt any one of the following: Marks 6 a) List various types of JDBC drives. Explain JDBC-ODBC bridge driver. (Types-2 Marks, Bridge driver diagram - 1 Marks, Discription-3 Marks) Ans: Type 1: JDBC-ODBC bridge Type 2: JDBC-native API Type 3:100% pure java, JDBC network Type 4:100% java JDBC-ODBC bridge
  5. 5. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 5 of 38 This category works with ODBC drivers supplied by your database vendor or a third party. To use the bridge, you must first have an ODBC driver specifically for you database and additional software that you need for connectivity. Using ODBC also requires configuring on your system a DNS that represents the target database. Advantages 1) It offers the ability to connect to almost all databases on almost all platforms. 2) It may be the only way to gain access to some low and desktop database and application Disadvantages 1) ODBC driver must also be loaded on the target machine. 2) Translation between JDBC and ODBC affects performance. b) Write a program to demonstrate the use of JScrollpane in swing. (Any 1 program- Applet tag-2mark, correct logic-4 Marks, Synatax-2 Marks) Ans: import java.awt.*; import javax.swing.*; /*<applet code=”JScrollPaneDemo” width=350 Height=250> </applet> */ Public class JscrollPaneDemo extends JApplet Public void init() { Container contentPane= get ContentPane(); contentPane.setLayout(new BorderLayout()); JPanel jp = new JPanel(); jp.setLayout(new GridLayout(20,20)); int b=0; for(int i=0;i<20;i++){ jp.add(new JButton(“Button”+b);
  6. 6. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 6 of 38 ++b; } } int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h= ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp= new JScrollPane(jp,v,h); contentPane.add(jsp,BorderLayout.CENTER); } } 2. Attempt any two of the following: Marks 16 a) Write an application program making use of menu and menu bar class. 8 (Applet tag – 1Mark, correct logic to add menu and menubar - 5 Marks, Synatax-2 Marks) Ans: import java.awt.*; import java.awt.event.*; import java.applet.*; /*<applet code=” MenuFrame” width=350 Height=250> </applet> */ class MenuFrame extends Frame implements ActionListener { String msg=””; MenuFrame(String title) { super(title); MenuBar mbar= new menuBar(); setMentBar(mbar); Menu file=new Menu(“File”); MenuItem item1,item2,item3,item4,item5;
  7. 7. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 7 of 38 item1= new MenuItem (“New”); item2= new MenuItem (“open”); item3= new MenuItem (“close”); item4= new MenuItem (“-”); item5= new MenuItem (“Quit”); file.add(item1); file.add(item2); file.add(item3); file.add(item4); file.add(item5); mbar.add(file); MenuItem item6,item7,item8,item9; item6= new MenuItem (“cut”); item7= new MenuItem (“copy”); item8= new MenuItem (“paste”); item9= new MenuItem (“-”); edit.add(item6); edit.add(item7); edit.add(item8); edit.add(item9); mbar.add(edit); item1.addActionListener(this); item2.addActionListener(this); item3.addActionListener(this); item4.addActionListener(this);
  8. 8. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 8 of 38 item5.addActionListener(this); item6.addActionListener(this); item7.addActionListener(this); item8.addActionListener(this); item9.addActionListener(this); } Public void paint(Graphics g) { g.drawString(msg,10,200); } public void actionPerformed(ActionEvent e) { msg= “You have selected ”+ e.getActionCommand(); repaint(); } public static void main(String args[]) { MenuFrame m=new MenuFrame(“MyMenu”); m.setVisible(true); m.setSize(100,200); } }
  9. 9. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 9 of 38 b) Give the use of Server Socket and Socket class. Describe the steps that are 8 required to establish communication between client and server sockets. (Use-2 Marks each class, Steps-4 Marks) Ans: Server socket: A Server Socket handles the requests and sends back an appropriate reply. The actual tasks that a server socket must accomplish are implemented by an internal SocketImpl instance. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester. The actual work of the server socket is performed by an instance of the SocketImpl class. An application can change the socket factory that creates the socket implementation to configure itself to create sockets appropriate to the local firewall. Client socket: we have used the class named ClientSocketInformation.java that implement the constructor of the Socket class passing two arguments as hostName and TIME_PORT. This program throws an IOException for the exception handling. This exception is thrown to indicate an I/O problem of some sort occurred. Here, we are going to explore a method to retrieve the host name of the local system in a very simple way. In this way we find out the Local address, Local host information, reuseAddress, and address of the local system in a very simple manner. Steps to connect Using TCP, socket provides the communication mechanism between two computers. A client program creates a socket at its end of the communication and attempts to connect that socket to a server. The following is the lists of sequential steps which occur when establishing a TCP connection between client socket and server socket. 1. The server initiates a Server Socket object and mentions which port number communication is to occur on. 2. The server invokes the accept () method of the ServerSocket class. This method does the wait till a client gets connected to the server on the given port.
  10. 10. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 10 of 38 After the waiting stages of server, a client instantiates a Socket object. It also specifies the server name and port number to which it gets connected. 3. The constructor of the Socket class tries to connect the client to the specified server and port number. If the communication is established, the client has a Socket object which is capable of communicating with the server. 4. On server side, the accept () method returns a reference to a new socket on the server that is connected to the client’s socket. Once the connection are established, communication occur using I/O streams. Each socket has both an Outputstream and InputStreams As we know that the TCP is a two way communication protocol. So data can be sent across both streams at the same time Two constructors used to create client socket: Socket (String hostname,int port) Creates a socket connection the localhost to name host and port. Socket(InetAddress ipAddress,int port) Creates a socket using pre existing InetAddress object and a port. A socket can be examined at any time for the address and port information associated with it. InetAddress getInetAddress() Int getPort() Int getLocalPort() Once the socket object has been created, it can be examined to gain access to i/p and o/p streams associated with it. Example : (optional) import java.net.*; import java.io.*; class abc{ public static void main(String args[])throws Exception{
  11. 11. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 11 of 38 int c; Socket s=new socket(“interic.net”,43); InputStream in=s.getInputStream(); OutputStream out=s.getOutputStream(); String str=(args.length==0?”Osborne.com”); byte buf[]=str.getBytes();out.write(buf); while((c=in.read())!=-1){ System.out.println({char)c); } s.close(); } } c) Give sequential steps to use JTabbedPane in an Applet with example. (Steps- 4Marks, any one Example- 4Marks) Ans: The general procedure to use a tabbed pane in an applet is 1) Create a JtabbedPane object. 2) Call addTab() to add to the pane. 3) Repeat step 2 for each tab. 4) Add the tabbed pane to the content pane of the applet. Example: import javax.swing.*; /*<applet code=”JTabbedPaneDemo” width=350 Height=250> </applet> */ public class JTabbedPaneDemo extends JApplet {
  12. 12. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 12 of 38 public void init() { JTabbedPane jtp= new JTabbedPane(); jtp.addTab(“cities”,new citiesPanel()); jtp.addTab(“colors”,new colorsPanel()); jtp.addTab(“Flavour”,new flavourPanel()); getContentPane().add(jtp); } } class citiespanel extends JPanel { Public citiesPanel() { JButton b1=new Button(“New York”); add(b1); JButton b2=new Button(“london”); add(b2); } } class colorpanel extends JPanel { Public colorPanel() { JCheckBox cb1=new JCheckBox(“red”); add(cb1); JCheckBox cb2=new JCheckBox (“green”); add(cb2); } } class flavourpanel extends JPanel {
  13. 13. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 13 of 38 public flavourPanel() { JComboBox b=new JComboBox(); jcb.addItem(“vanilla”); jcb.addItem(“chocolate”); add(jcb); } } 3. Attempt any four of the following: Marks 16 a) Example the use of prepared statement with example. 4 (Explanation-2 Marks, Example-2 Marks) Ans: PrepareStatement () The preparedStatement() method creates a PreparedStatement object and returns it as a return value. The Prepared statement object is used to execute dynamic SQL statement against the database.A dynamic SQL statement is a statement in which some of the parameters in the statement are unknown when the statement is created. The parameter is placed into the SQL statement as they are determined by the application. When all the parameters are specified for the SQL statement, the dynamic SQL statement will be executed just as a static statement is executed. To create a dynamic SQL statement that takes a first name and last name as parameters, use the following code: try { String sql=”Select * from temployee” + “where Firstname=?” + “and Lastname=?”; PreparedStatement p=connection.preparedStatement(sql); } Catch(SQLException e) { }
  14. 14. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 14 of 38 b) List any four differences between AWT and swing. 4 (Any four points – 1 Mark each) Ans: Swing AWT It uses javax.swing package. It uses java.applet package. It uses JApplet class It uses Applet class Swing is light weight component AWT is heavy weight component It does not have add() method to add control. It has add() method to add control. AWT provides less features than swing Swing has variety of component & features which is not in AWT Awt has huge collection of classes & interfaces Swing has bigger collection of classes & interfaces than AWT AWT has predefined formats of appearance & behavior of component Swing provides a facility of different appearance & behavior of the same component c) List four interfaces in javax.servlet package. 4 (Any four points – 1 Mark each) Ans: Following are the interfaces in javax.servlet package: 1. Servlet: 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. 2. ServletConfig: The ServletContextinterface is implemented by the server. It enables servlets to obtain information about their environment. 3. ServletContext: The ServletContextinterface is implemented by the server. It enables servlets to obtain information about their environment. 4. ServletRequest: The ServletRequestinterface is implemented by the server. It enables a servlet to obtain information about a client request. 5. ServletResponse : The ServletResponseinterface is implemented by the server. It enables a servlet to formulate a response for a client. 6. SingleThreadModel: 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.
  15. 15. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 15 of 38 d) Give the use of ImageIcon class with example. 4 (Explanation – 2 Marks, Example- 2 Marks) Ans: In Swing, icons are encapsulated by the ImageIconclass, which paints an icon from an image. Two of its constructors are shown here: ImageIcon(String filename) ImageIcon(URL url) The first form uses the image in the file named filename. The second form uses the image in the resource identified by url. The ImageIconclass implements the Icon interface that declares the methods As follows: Method Description intgetIconHeight( ) Returns the height of the iconin pixels. intgetIconWidth( ) Returns the width of the iconin pixels. voidpaintIcon(Component comp, Graphics g,intx, inty)Paints the icon at position x, y onthe graphics context g. Additionalinformation about the paintoperation can be provided in comp. Example: import java.awt.*; import javax.swing.*; <applet code="JLabelDemo" width=250 height=150> </applet> */ public class JLabelDemo extends JApplet { public void init() { // Get content pane Container contentPane = getContentPane(); // Create an icon ImageIcon ii = new ImageIcon("france.gif"); // Create a label JLabeljl = new JLabel("France", ii, JLabel.CENTER); // Add label to the content pane contentPane.add(jl);
  16. 16. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 16 of 38 } } e) Give the use of URL class along with syntax of constructors of URL class. 4 (Use - 2 Marks, Any two Constructor - 1 Mark each) Ans: The URL provides a reasonably intelligible form to uniquely identify or address information on the Internet. URLs are ubiquitous; every browser uses them to identify information on the Web. In fact, the Web is really just that same old Internet with all of its resources addressed as URLs plus HTML Java's URL class has several constructors. One commonly used form specifies the URL with a string that is identical to what you see displayed in a browser: 1. URL(String urlSpecifier) The next two forms of the constructor allow you to break up the URL into its componentparts: 2. URL(String protocolName, String hostName, intport, String path) 3. URL(String protocolName, String hostName, String path) Another frequently used constructor allows you to use an existing URL as a referencecontext and then create a new URL from that context. Although this sounds a littlecontorted, it's really quite easy and useful. 4. URL(URL urlObj, String urlSpecifier) 4. A) Attempt any three of the following: Marks 12 a) Give the use of following methods of statement interface : 4 i) executeQuery( ) ii) execute Update ( ) (Each method – 2 Marks) Ans: i) executeQuery() The executeQuery() method of the statement object enables you to send SQL select statement to the database and to receive result from the database. Executing a query in effect sends a SQL select statement to the database and returns the appropriate results back in the Resultset object. The executeQuery() method takes a SQL select statement as a parameter and returns a ResultSet object that contains all the records that match the select statements criteria. ii) executeUpdate()
  17. 17. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 17 of 38 The executeUpdate() method of the Statement object enables you to execute SQL update statements such as delete, insert and update. The method takes a String containing the SQL update statement and returns an integers that determines how many records were affected by the SQL statement. b) Define Layout Manager. Describe the use of GridLayout Manager. 4 (Layout manager- 2 Marks, Use-2 Marks) Ans: Each Container object has a layout manager associated with it. A layout manager is an instance of any class that implements the LayoutManagerinterface. The layout manager is set by the setLayout( ) method. If no call to setLayout( ) is made, then the default layout manager is used. Whenever a container is resized (or sized for the first time), the layout manager is used to position each of the components within it. The setLayout( ) method has the following general form: voidsetLayout(LayoutManagerlayoutObj) GridLayoutManager: GridLayout lays out components in a two-dimensional grid. When you instantiate a GridLayout, you define the number of rows and columns. The constructors supported by GridLayoutare shown here: GridLayout( ) GridLayout(intnumRows, intnumColumns) GridLayout(intnumRows, intnumColumns, inthorz, intvert) c) Explain the use of cookies with example. 4 (Explanation - 2 Marks, Example - 2 Marks any one) Ans: Cookie is a small piece of information that is passed back and forth in the HTTP request and response. Even though a cookie can be created on the client side using some scripting language such as JavaScript, it is usually created by the server resource, such as a Servlet. The Cookies sent by the server when the client requests another page from the same application. In Servlet programming a cookie is represented by a Cookie class in the javax.servlet.http package. You can create a cookie by calling the Cookie class constructor and passing two string objects: the name
  18. 18. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 18 of 38 and value of the cookie. For instance, the following code creates a cookie object called c1.The cookie has the name “myCookie” and value of ”secret”: Cookie c1=new Cookie(“myCookie”,”secret”); You then can add the cookie to the http response using addCookie method of the HTTPServletResponse interface:Response.addCookie(c1); Program for Add cookies import java.io.*; importjavax.servlet.*; importjavax.servlet.http.*; public class AddCookieServlet extends HttpServlet { public void doPost(HttpServletRequest request,HttpServletResponse response) throwsServletException, IOException { // Get parameter from HTTP request. String data = request.getParameter("data"); // Create cookie. Cookie cookie = new Cookie("MyCookie", data); // Add cookie to HTTP response. response.addCookie(cookie); // Write output to browser. response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>MyCookie has been set to"); pw.println(data);
  19. 19. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 19 of 38 pw.close(); } } OR Program for Get Cookies import java.io.*; importjavax.servlet.*; importjavax.servlet.http.*; public class GetCookiesServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throwsServletException, IOException { // Get cookies from header of HTTP request. Cookie[] cookies = request.getCookies(); // Display these cookies. response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>"); for(inti = 0; i<cookies.length; i++) { String name = cookies[i].getName(); String value = cookies[i].getValue(); pw.println("name = " + name + "; value = " + value); }
  20. 20. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 20 of 38 pw.close(); } } d) Give steps to create simple servlet with example. 4 (Steps- 2 Marks, Any one Example – 2 Marks) Ans: Steps 1) Write a java servet code; Steps 2) Compile Servet by setting classpath with servlet-api library. Step 3) Copy the .class servlet file in web apps classpath directory. Steps 4) Open the web.xml, open it and add servlet tag and sevlet mapping tag. Steps 5) Start web server(apche tomcat); Steps 6) Browse servlet using java compatible browser like IE . Example shows to start, create a file named WelcomeServlet.java that contains the following program. import java.io.*; importjavax.servlet.*; public class WelcomeServletDemo extends GenericServlet { public void service(ServletRequestrequest,ServletResponse response) throws ServletException,IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>Welcome to Servlet"); pw.close(); } }
  21. 21. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 21 of 38 B) Attempt any one of the following: Marks 6 a) Describe the two –tier and three –tier database design of JDBC API with neat diagram. (Explanation of Two-tier-2 Marks and Three-tier-2 Marks, Diagram – 1 Mark each) Ans: Two Tier Architecture: In a two tier model a java application is designed to interact directly with the database. Application functionality is divided into these two layers: 1) Application Layer: Including the JDBC driver, business logic and user interface 2) Database Layer: including RDBMS The interface to the database is handled by the Java Database Connectivity(JDBC) Driver appropriate to the particularly database management system being accessed. The JDBC Driver passes SQL statements to the database and returns the results of those statements to the application. A client/server configuration is the special case of the two tier model where the database is located on another machine referred to as the server. The application runs on the client machine which is connected to the server over a network. Commonly the network is an Intranet using dedicated database servers to support multiple clients but it can just as easily be the internet. Three Tier Architecture:- In the three tier model, the client typically sends requests to an application server, forming the middle tier. The application server interprets these requests and formats the necessary SQL statement to fulfill
  22. 22. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 22 of 38 These requests, and sends them to the database. The database process the SQL statements and sends result back to the application server, which then sends them to the client. Following are some advantages of Three-tier architecture: 1. Performance can be improved by separating the application server and database server 2. Business logic is clearly separated from the database. 3. Client application can use a simple protocol such as CGI to access services. The three-tier model show in following fig is a common in web application. In this scenario, the client tier is frequently implemented in a browse on a client machine, the middle tier is implemented in a web server with a Servlet engine and the database management system runs on a dedicated database server. Following are the main components of three tier architecture 1. Client Tier: - Typically, this is thin presentation layer that may be implemented using a web browser 2. Middle Tier :- This tier handles the business or application logic . This may be implemented using a Servlet engine such as Tomcat or an application server such as JBOSS. The JDBC driver also resides in this layer. 3. Data source layer: This component includes the RDBMS
  23. 23. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 23 of 38 b) Write servlet which shows how many times user has visited the page in session. (Any Correct Logic –4 Marks, Syntax – 2 Marks) Ans: import java.io.*: import javax.servlet.*; import javax.servlet.http.*; public class Session Travker extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType(“text/html”); PrintWriter out = res.getWriter(); HttpSession session = req.getSession(true); Integer count= (Integer)session.getValue(“tracker.count”); if(count== null) count=new Interger(1); else count = new Interger(count intValue() +1); session.putValue(“tracker.count”,count); out.println(“<HTML><HEAD><TITLE>Session Tracker</TITLE></HEAD>”); out.println(“<BODY><H1>Session Tracking Demo</H1>”); out.println(“You have visited this page” +count +((count.intValue() == 1)?”time.” : “times.”));out.prinln(<P>”); out.println(“<H2>Sesssion data:</H2>”); String[] names = session.getValueNames(); for(int i=0; i< names.length; i++) {
  24. 24. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 24 of 38 out.println(names[i] + “ : ” + session.getvalue(names[i])+ “<BR>”); } out.println(“<BODY></HTML>”); } } 5. Attempt any two of the following: Marks 16 a) Write a program to display all records from Employee table from database using JDBC. (Assume suitable data for table- Load driver, create connection, execute Query - 1 Mark each, Display data- 3 Marks, Syntax – 2 Marks) Ans: import java.sql.*; import java.sql.Statement; import java.applet.*; import java.awt.*; public class DisplayTable { public static void main( String args[]) { RsultSet rs; Connection conn; try { String s1; Class.forName("sun .jdbc.odbc.JdbcOdbcDriver"); System.out.println("Connecting to a selected database..."); String url=”jdbc:odbc:abc”; conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully...");
  25. 25. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 25 of 38 System.out.println("Creating statement..."); stmt = conn.createStatement(); sql = "SELECT * FROM Employee"; ResultSet rs = stmt.executeQuery(sql); // Tables fields assumed are id, first, last, age while(rs.next()){ int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("first"); String last = rs.getString("last"); System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); } rs.close(); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) conn.close(); }catch(SQLException se){ }
  26. 26. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 26 of 38 } } } b) Define the term: i) Reserved socket ii) proxy server iii) Datagram iv) URL connection 4 (Each term- 2 Marks) Ans: i) Reserved socket A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and a server program. Reserved socket : The socket which are reserved for specific protocols for communication purpose are known as reseved sockets. TCP/IP uses or reserves the lower 1024 ports for specific protocols. Example: port number 23 is for Telnet ,25 is for smtp, 21 is for ftp, 13 for daytime, 110 for pop3 and so on. Protocol decides how a client should interact with the port. ii) Proxy server A proxy server is a computer that offers a computer network service to allow clients to make indirect network connections to other network services. A client connects to the proxy server, then requests a connection, file, or other resource available on a different server. The proxy provides the resource either by connecting to the specified server or by serving it from a cache. In some cases, the proxy may alter the client's request or the server's response for various purposes. Purposes of the proxy servers: To keep machines behind it anonymous, mainly for security. To speed up access to resources (using caching). Web proxies are commonly used to cache web pages from a web server. To prevent downloading the same content multiple times (and save bandwidth). To log / audit usage, e.g. to provide company employee Internet usage reporting.
  27. 27. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 27 of 38 To scan transmitted content for malware before delivery. To scan outbound content, e.g., for data loss prevention iii) Datagram Datagrams are bundles of information passed between machines. They are somewhat like a hard throw from a well-trained but blindfolded catcher to the third baseman. Once the datagram has been released to its intended target, there is no assurance that it will arrive or even that someone will be there to catch it. Likewise, when the datagram is received, there is no assurance that it hasn’t been damaged in transit or that whoever sent it is still there to receive a response. Java implements datagrams on top of the UDP protocol by using two classes: The DatagramPacket object is the data container, while the DatagramSocket is the mechanism used to send or receive the DatagramPackets. iv) URL connection URLConnection is a general-purpose class for accessing the attributes of a remote resource. Once you make a connection to a remote server, you can use URLConnection to inspect the Properties of the remote object before actually transporting it locally. These attributes are exposed by the HTTP protocol specification and, as such, only make sense for URL objects that are using the HTTP protocol. URLConnection defines several methods int getContentLength( ) String getContentType( ) long getDate( ) long getExpiration( ) String getHeaderField(int idx) long getLastModified( )
  28. 28. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 28 of 38 c) Write a program to display three text fields and a button below to all an Applet. Insert the integer valuer from three text fields. After pressing the button the background colour of applet will be changed as per the RGB combination of the values given in the text field. (Correct logic - 6 Marks, Syntax - 2 Marks) 4 Ans: import java.awt.*; import java.awt.event.*; import java.applet.*; /*<applet code=”Clr.class” width=250 heigth=250><applet>*/ public class Clrextends Applet implements ActionListener { int r, g, b; TextField t1,t2,t3; Button b1; Color c1; public void init() { t1= new TextField(5); t2= new TextField(8); t3= new TextField(11); b1 = new Button(“ Set Color”);
  29. 29. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 29 of 38 add(t1); add(t2); add(t3); add(b1); b1.addActionListener(this); } public void void paint( ) { setBackground(c1); } public void actionPerformed(ActionEvent ae) { r=Integer.parseInt(t1.getText()); g=Integer.parseInt(t2.getText()); b=Integer.parseInt(t3.getText()); c1= new Color(r,g,b); repaint(); } }
  30. 30. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 30 of 38 6) Attempt any four of the following: Marks 16 a) How to check, how many fonts are available in the computer system? 4 Explain with example. (Explanation -2 Marks, Example-2 Marks) Ans: When working with fonts, often you need to know which fonts are available on your machine. To ontain this information, you can use the getAvailableFontFamilyNames() method defined by the GraphicsEnvironment class.It is shown here: String[ ] getAvailableFontFamilyNames( ) This method returns an array of string that contains the names of the available font families. Since, this methods is members of GraphicsEnvironment, you need a GraphicsEnvironment reference to call it.You can obtain this reference by using the getlocalGrahicsEnvironmet() static method, which is derfined by GraphicsEnvironment.It is shown here: static GraphicsEnvironment getLocalGraphicsEnvironment( ) Here, is an applet that shown how to obtain the names of the available font families. /* <applet code=”AllFonts” width=500 height=100> </applet> */ import java.applet.*; import java.awt.*; public class AllFonts extends Applet { public void paint(Graphics g) { string fonts= “ ”; stirng allFontsList[];
  31. 31. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 31 of 38 GraphicsEnvironment t = GraphicsEnvironment.getLocalGraphicsEnvironment(); allFontList = t.getAvailableFontFamilyNames(); for(int i= 0; i< allFontsList.length; i++) fonts= fonts + allFontList[i] + “ ”; g.drawString(msg,4,16); } } b) Explain following check box class methods with appropriate example. 4 i) Void setLable (String str) ii) Boolean getState ( ) (Explanation of each method-1 Marks, Example-2 Marks) Ans: i) void setLable(String str) This method is used to set the label of check box ii) Boolean getState() This method is used to retrieve the current state of a check box. It returns the value either true or false depends on check box is selected or not. Example: // Demonstrate check boxes. import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="CheckboxDemo" width=250 height=200> </applet> */ public class CheckboxDemo extends Applet implements ItemListener { String msg = "";
  32. 32. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 32 of 38 Checkbox winXP, winVista, solaris, mac; public void init() { winXP = new Checkbox("Windows XP", null, true); mac = new Checkbox(); mac.setLable(“Mac OS”); add(winXP); add(mac); winXP.addItemListener(this); mac.addItemListener(this); } public void itemStateChanged(ItemEvent ie) { repaint(); } // Display current state of the check boxes. public void paint(Graphics g) { msg = "Current state: "; g.drawString(msg, 6, 80); msg = " Windows XP: " + winXP.getState(); g.drawString(msg, 6, 100); msg = " Mac OS: " + mac.getState(); g.drawString(msg, 6, 120); } }
  33. 33. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 33 of 38 c) Explain the techniques of session tracking /management. (Any four techniques with explanation- 1 Mark each) Ans: Session tracking Techniques: 1. User Authorization Users can be authorized to use the web application in different ways. Basic concept is that the user will provide username and password to login to the application. Based on that the user can be identified and the session can be maintained. 2. Hidden Fields <INPUT TYPE=”hidden” NAME=”technology” VALUE=”servlet”> Hidden fields like the above can be inserted in the webpages and information can be sent to the server for session tracking. These fields are not visible directly to the user, but can be viewed using view source option from the browsers. This type doesn’t need any special configuration from the browser of server and by default available to use for session tracking. This cannot be used for session tracking when the conversation included static resources lik html pages. 3. URL Rewriting Original URL: http://server:port/servlet/ServletName ewritten URL: http://server:port/servlet/ServletName?sessionid=7456 When a request is made, additional parameter is appended with the url. In general added additional parameter will be sessionid or sometimes the userid. It will suffice to track the session. This type of session tracking doesn’t need any special support from the browser. Disadvantage is, implementing this type of session tracking is tedious. We need to keep track of the parameter as a chain link until the conversation completes and also should make sure that, the parameter doesn’t clash with other application parameters.
  34. 34. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 34 of 38 4. Cookies Cookies are the mostly used technology for session tracking. Cookie is a key value pair of information, sent by the server to the browser. This should be saved by the browser in its space in the client computer. Whenever the browser sends a request to that server it sends the cookie along with it. Then the server can identify the client using the cookie. In java, following is the source code snippet to create a cookie: Cookie cookie = new Cookie (“userID”, “7456″); res.addCookie(cookie); 5. Session tracking API Session tracking API is built on top of the first four methods. This is inorder to help the developer to minimize the overhead of session tracking. This type of session tracking is provided by the underlying technology. Lets take the java servlet example. Then, the servlet container manages the session tracking task and the user need not do it explicitly using the java servlets. This is the best of all methods, because all the management and errors related to session tracking will be taken care of by the container itself. d) Give sequential steps for JTree in swing with example. (Steps- 2 Marks, any small Example- 2 Marks) Ans: Steps for JTree: Atree is a component that presents a hierarchical view of data. The user has the ability to expand or collapse individual subtrees in this display. Trees are implemented in Swing by the JTree class. Here are the steps to follow to use a tree: 1. Create an instance of JTree. 2. Create a JScrollPane and specify the tree as the object to be scrolled. 3. Add the tree to the scroll pane. 4. Add the scroll pane to the content pane.
  35. 35. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 35 of 38 Example: // Demonstrate JTree. import java.awt.*; import javax.swing.event.*; import javax.swing.*; import javax.swing.tree.*; /* <applet code="JTreeDemo" width=400 height=200> </applet> */ public class JTreeDemo extends JApplet { JTree tree; JLabel jlab; public void init() { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { makeGUI(); } } ); } catch (Exception exc) { System.out.println("Can't create because of " + exc); } } private void makeGUI() { // Create top node of tree. DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options"); // Create subtree of "A".
  36. 36. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 36 of 38 DefaultMutableTreeNode a = new DefaultMutableTreeNode("A"); top.add(a); DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1"); a.add(a1); DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2"); a.add(a2); // Create subtree of "B". DefaultMutableTreeNode b = new DefaultMutableTreeNode("B"); top.add(b); DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1"); b.add(b1); DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2"); b.add(b2); DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3"); b.add(b3); // Create the tree. tree = new JTree(top); // Add the tree to a scroll pane. JScrollPane jsp = new JScrollPane(tree); // Add the scroll pane to the content pane. add(jsp); // Add the label to the content pane. jlab = new JLabel(); add(jlab, BorderLayout.SOUTH); // Handle tree selection events. tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent tse) { jlab.setText("Selection is " + tse.getPath()); } } }
  37. 37. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 37 of 38 } e) Draw and explain the life cycle of servlet. (Explanation – 3 Marks, Diagram -1 Marks) Ans: Three methods are central to the life cycle of a 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. 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 relinquish 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. A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet The servlet is initialized by calling the init () method.
  38. 38. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER – 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 38 of 38 The servlet calls service() method to process a client's request. The servlet is terminated by calling the destroy() method. Finally, servlet is garbage collected by the garbage collector of the JVM. Initialization (Load Resources) Services (Accept Requests) Destruction (Unload Resources) Servlet Request Response

×