You are on page 1of 23

-1-

Question 1-Write an online student registration application using JSP/servlet and JDBC. Use the following table to store student information. Ans STUDENT_REG
ENR-ID,SNAME,REG-YEAR,ADDRESS <html> <body bgcolor="#999966"> <form action="/userregister/Registration " method=post> <table cellpadding=4 cellspacing=2 border=0> <th bgcolor="#999966" colspan=2> <font size=5>REGISTRATION</font> <br><font size=1><sup></sup></font><hr> </th><tr bgcolor="#999966"><td valign=top> <b>Enrolment Id<sup>*</sup></b> <br><input type="text" name="enrid" value="" size=15 maxlength=20> </td><td valign=top><b>Student Name<sup>*</sup></b> <br><input type="text" name="sname" value="" size=15 maxlength=20></td> </tr><tr bgcolor="#999966"> <td valign=top><b> Registration Year <sup>*</sup></b> <br><input type="text" name="regyear " value="" size=25 maxlength=125><br></td><td valign=top> <b>Address<sup>*</sup></b> <br> <input type="text" name="address" value="" size=5 maxlength=6></td> </tr><tr bgcolor="#999966"><td valign=top colspan=2> <td align=left colspan=2><hr> <input type="submit" value="Submit"></td></tr> </table></center> </form> </body> </html> Registration .java package myservlets; import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class Registration extends HttpServlet{ public void init(ServletConfig config) throws ServletException{ super.init(config); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ String connectionURL = "jdbc:mysql://localhost/jsp"; Connection connection=null;

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

-2ResultSet rs; res.setContentType("text/html"); PrintWriter out = res.getWriter(); String uId = req.getParameter("enrid"); String fname = req.getParameter("sname"); String sname = req.getParameter("regyear"); String address1 = req.getParameter("address"); try { Class.forName("org.gjt.mm.mysql.Driver"); connection = DriverManager.getConnection(connectionURL, "root", "root"); String sql = "insert into userprofile values (?,?,?,?,?,?,?,?)"; PreparedStatement pst = connection.prepareStatement(sql); pst.setString(1, enrid); pst.setString(2, sname); pst.setString(3, regyear); pst.setString(4, address); int numRowsChanged = pst.executeUpdate(); out.println(" Welcome : "); out.println(" '"+fname+"'"); pst.close(); } catch(ClassNotFoundException e){ out.println("Couldn't load database driver: " + e.getMessage()); } catch(SQLException e){ out.println("SQLException caught: " + e.getMessage()); } catch (Exception e){ out.println(e); } finally { try { if (connection != null) connection.close(); } catch (SQLException ignored){ out.println(ignored); } } } } web.xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

-3xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd" version="2.5"> <description> User Registration and Login Example. </description> <display-name>User Registration and Login Example</display-name> <servlet> <servlet-name>Registration</servlet-name> <servlet-class>myservlets.Registration</servlet-class> </servlet> <servlet-mapping> <servlet-name>Registration</servlet-name> <url-pattern>/Registration</url-pattern> </servlet-mapping> </web-app>

Question 2-What is a custom tag in JSP? Create a custom tag that will accept a full name and convert into initials. For example Surendra Kumar Sharma should be displayed as S.K. Sharma. Please use proper error handling feature.
Ans: The standard JSP tags for invoking operations on JavaBeans components and performing request dispatching simplify JSP page development and maintenance. JSP technology also provides a mechanism for encapsulating other types of dynamic functionality in custom tags, which are extensions to the JSP language. Custom tags are usually distributed in the form of a tag library, which defines a set of related custom tags and contains the objects that implement the tags. Some examples of tasks that can be performed by custom tags include operations on implicit objects, processing forms, accessing databases and other enterprise services such as e-mail and directories, and performing flow control. JSP tag libraries are created by developers who are proficient at the Java programming language and expert in accessing data and other services, and are used by Web application designers who can focus on presentation issues rather than being concerned with how to access enterprise services. As well as encouraging division of labor between library developers and library users, custom tags increase productivity by encapsulating recurring tasks so that they can be reused across more than one application. String name ="Surendra Kumar Sharma"; String[] nameParts = name.split(" "); int len = nameParts.length; String initials = ""; for(int i = 0; i < len-1; i++) { initials = initials + nameParts[i].substring(0,1).toUpperCase() + ". "; } initials = initials + nameParts[len-1];

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

-4-

System.out.println ("Initials Are " + initials);

Question-3 What is Servlet Collaboration? Explain two ways used for Servlet Collaboration through an example. Ans :Servlet collaboration is all about sharing information among the servlets. Collaborating servlets is
to pass the common information that is to be shared directly by one servlet to another through various invocations of the methods. To perform these operations, each servlet need to know the other servlet with which it is collaborated. The collaboration can be done by redirecting a servlet from another or loading the servlets from the ServletContext access methods. This can also be achieved by the methods forward() and include() of RequestDispatcher or by sendRedirect() method. Two ways used for Servlet Collaboration Collaboration Through the System Properties List One simple way for servlets to share information is by using Java's system-wide Properties list, found in the java.lang.System class. This Properties list holds the standard system properties, such as java.version and path.separator, but it can also hold application-specific properties. Servlets can use the properties list to hold the information they need to share. A servlet can add (or change) a property by calling: System.getProperties().put("key", "value"); That servlet, or another servlet running in the same JVM, can later get the value of the property by calling: String value = System.getProperty("key"); The property can be removed by calling: System.getProperties().remove("key"); It's best if the key for a property includes a prefix that contains the name of the servlet's package and the name of the collaboration group. For example, "com.oreilly.servlet.ShoppingCart". The Properties class is intended to be String based, meaning that each key and value is supposed to be a String. This limitation, though, isn't commonly enforced and can (although it's quite a hack) be ignored by servlets that want to store and retrieve non-String objects. Such servlets can take advantage of the fact that the Properties class extends the Hashtable class, so the Properties list can (quite rudely) be treated as a Hashtable when storing keys and values. For example, a servlet can add or change a property object by calling: System.getProperties().put(keyObject, valueObject); // hack It can retrieve the property object by calling: SomeObject valueObject = (SomeObject)System.getProperties().get(keyObject); It can remove the property object by calling: System.getProperties().remove(keyObject); This misuse of the Properties list causes the getProperty(), list() and save() methods of the Properties class to throw ClassCastException objects when they naturally--but erroneouslyassume each key and value to be a String. For this reason, if there's any chance these methods might be called, you should instead use one of the techniques for servlet collaboration we describe later in the chapter. Also, remember the class files for keyObject and valueObject should be found in the server's classpath, not in the default servlet directory where they would be loaded, and perhaps reloaded, by the special servlet class loaders.

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

-5There are three more caveats to using the system Properties list for servlet collaboration: the information isn't naturally persistent between server restarts, the information can be viewed (and modified or deleted) by other classes executing in the servlet's JVM, and some servlet security managers may not grant servlets access to the system property list. Collaboration Through Inheritance Perhaps the easiest technique for servlet collaboration is through inheritance. Each servlet interested in collaborating can extend the same class and inherit the same shared information. This simplifies the code for the collaborating servlets and limits access to the shared information to the proper subclasses. The common superclass can hold a reference to the shared information, or it can hold the shared information itself. Inheriting a shared reference A common superclass can hold any number of references to shared business objects that are easily made available to its subclasses. Example 11 shows such a superclass, usable for our burrito inventory example. Example A superclass holding a reference to shared information import javax.servlet.*; import javax.servlet.http.*; public class BurritoInventorySuperclass extends HttpServlet { protected static BurritoInventory inventory = new BurritoInventory(); } This BurritoInventorySuperclass creates a new BurritoInventory instance. BurritoInventoryProducer and BurritoInventoryConsumer can then subclass BurritoInventorySuperclass and inherit a reference to this instance. The code for the revised BurritoInventoryConsumer is shown in Example 12 to clarify. Example 12. Using an inherited business object import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class BurritoInventoryConsumer extends BurritoInventorySuperclass { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<HTML>"); out.println("<HEAD><TITLE>Burrito Inventory Consumer</TITLE></HEAD>"); out.println("<BODY><BIG>"); if (inventory.makeBurrito()) { out.println("Your burrito will be ready in 3 minutes."); } else { out.println("We're low on ingredients.<BR>"); out.println("Looks like you're gonna starve."); } out.println("</BIG></BODY></HTML>");

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

-6} } The BurritoInventory class doesn't have to be a singleton anymore. The subclasses naturally inherit the same instance. Again, the class file for BurritoInventorySuperclass should be put in the server's classpath to keep it from being reloaded. Inheriting the shared information In addition to holding shared references, a common superclass can hold shared information itself and optionally make it available through inherited business logic methods. Example 13 shows BurritoInventorySuperclass rewritten using this technique. It's essentially an alternate form of BurritoInventoryServlet. Example 13 A superclass holding its own shared information public class BurritoInventorySuperclass extends HttpServlet { // How many "servings" of each item do we have? private static int cheese = 0; private static int rice = 0; private static int beans = 0; private static int chicken = 0; // Add to the inventory as more servings are prepared. protected static void addCheese(int added) { cheese += added; } protected static void addRice(int added) { rice += added; } protected static void addBeans(int added) { beans += added; } protected static void addChicken(int added) { chicken += added; } // Called when it's time to make a burrito. // Returns true if there are enough ingredients to make the burrito, // false if not. Decrements the ingredient count when there are enough. synchronized static protected boolean makeBurrito() { // ...etc... } // ...The rest matches BurritoInventoryServlet... There are only two differences between this servlet superclass and BurritoInventoryServlet. First, all the variables and methods are now static. This guarantees that there's just one inventory kept for all the subclasses. Second, all the methods are now protected. This makes them available only to subclasses. By inheriting from a superclass that contains the shared information, BurritoInventoryProducer and BurritoInventoryConsumer can call the inventory methods directly. For example,BurritoInventoryProducer can add items to the inventory with this code: // Add the items to the inventory addCheese(cheese); addRice(rice); addBeans(beans); addChicken(chicken);

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

-7-

Question 4-Write a MDB (Message Driven Bean) for news agency that has to capture the data from various news sources. The newly written MDB should accept the XML format of the news. The XML data needs to be parsed and stored in the database. The news format is as follows:
Ans : <news_id> </ news_id> <sources> </source> <date> </date> <type_of_news> </type_of_news> <priority> <priority> <news_content> </news_content> Solution<%@page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage=""%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html > <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> <style type="text/css"> <!-.style1 { font-family:"Times New Roman", Times, serif; color: #99CC00;} .style2 { font-family:"Times New Roman", Times, serif; color: #99CC00; } .style3 { color: #FFFFFF;} .style4 { font-size:14px; color: #0099FF; } .style5 { color: #0099FF;} .style6 { font-size:14px; color: #00CCFF;} .style7 { color: #00CCFF; } body { background-color:#FFFFFF;} </style> </head> <body> <h1 class="style1">Daily News</h1> <form name="form1" method="post" action=""> <span class="style2">News Id.:</span> <input type="text" name="textfield"> </form> <form name="form2" method="post" action=""> <p><span class="style4">Source:</span><span class="style5"></span><span class="style3">aa</span> <input type="text" name="textfield3"> </p> <p><span class="style5">Date:<span class="style3">:</span></span><span class="style3">aaaa</span> <input type="text" name="textfield2">

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

-8</p> </form> <form name="form3" method="post" action=""> <span class="style6">Type of news</span> <input type="text" name="textfield4"> </form> <form name="form4" method="post" action=""> <p class="style7">News content</p> <p> <textarea name="textarea" rows="4"></textarea> </p> </form> <p>&nbps;</p> </body> </html>

Question- 5: Write an application to create a XML document from a telephone directory database. The XML document should contain the name of a customer, address, telephone number and the last twelve months bill payment summary. Ans :<?xml version="1.0" ?>
<?xml version="1.0" encoding="ISO-8859-1" ?> <!-- customer - customer.xml --> <!-- Storing the customer details in XML document --> <customer> <customer.name> <fname>Shyam</fname> <mname>Narendra</mname> <lname>Patel</lname> </ customer.name> < customer.add> <city>Vadodara</city> <state>Gujarat</state> <zip>390 001</zip> </employee.add> <customer.phone> <number>079-65254789</number> </customer.phone> <summary>We found Mr. Patel is a good customer he paid all the bills on time.</summary> </customer>

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

-9-

Question 6 Create a mini bank application, where the new bank customer can register and opt for different bank accounts.

(A Diagram is here please see it from assignment questions)


The application should capture the customer details and depending upon the type of the account, it should ask about their employment details (e.g. for saving account, there should be salary details and for commercial account, there should be business turnover). Put the necessary validation also. You are required to use Servelet, JSP and JDBC. Ans : newACRequestPage.jsp
<html> <head> <title>New AC Request-Indian Bank</title> <script LANGUAGE="JavaScript"> function validateForm() { if(document.newACRequest.fname.value.length == 0) { alert("Enter First Name!"); document.newACRequest.fname.focus(); return false; } if(document.newACRequest.lname.value.length == 0) { alert("Enter last name!"); document.newACRequest.lname.focus(); return false; } if(document.newACRequest.caddress.value.length == 0) { alert ("Enter Current address!"); document.newACRequest.caddress.focus(); return false; } if(document.newACRequest.paddress.value.length == 0) { alert ("Enter permanant address!"); document.newACRequest.paddress.focus(); return false; } if((document.newACRequest.mobile.value.length == 0) || (document.newACRequest.mobile.value.length < 10)) { alert("Enter 10 digit mobile number");

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

- 10 document.newACRequest.mobile.focus(); return false; } if((document.newACRequest.empstatus.value == "yes") && (document.newACRequest.empyer.value.length == 0)) { alert ("If employment status is -YES-, please enter Employer."); document.newACRequest.empyer.focus(); return false; } if((document.newACRequest.empstatus.value == "yes") && (document.newACRequest.ctc.value.length == 0)) { alert ("If employment status is -YES-, please enter Employer."); document.newACRequest.ctc.focus(); return false; } if(document.newACRequest.actype.value == "1") { alert ("Select type of account."); document.newACRequest.actype.focus(); return false; } if(document.newACRequest.bto.value.length == 0) { alert ("Enter Business turn over"); document.newACRequest.bto.focus(); return false; } return true; } </SCRIPT> </head> <body><br><br> <center><B><U>Indian Bank</U></B></center><br> <center><B><U>New AC Request Window</U></B></center><br> <form name="newACRequest" action="newACRequest" method="post" onsubmit="return validateForm();"> Personal Details: <hr size=2> <table align="left" border="0"> <tr> <td>First Name</td> <td><input type="text" name="fname" class="input" maxlength="5" size="25" ></td> </tr>

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

- 11 <tr> <td>Middle Name</td><td> <input type="text" name="mname"class="input" maxlength="5" size="25" ></td> </tr> <tr> <td>Last Name</td> <td><input type="text" name="lname" class="input" maxlength="10" size="25"></td> </tr> <tr> <td>Current Address</td> <td><textarea name="caddress" class="input" cols="21" rows="3"></textarea></td> </tr> <tr> <td>Permanant Address</td> <td><textarea name="paddress" class="input" cols="21" rows="3"></textarea></td> </tr> <tr> <td>Mobile Number</td> <td><input type="text" name="mobile" class="input" maxlength="10" size="25"></td> </tr> </table><br><br><br><br><br><br><br><br><br><br><br><br><br><br> Employment Details: <hr size=2> <table align="left" border="0"> <tr> <td>Employment Status::</td> <td><input type="radio" name="empstatus" value="yes">Yes&nbsp;&nbsp;<input type="radio" name="empstatus" value="no" checked>No</td> </tr> <tr> <td>Employer</td> <td><input type="text" name="empyer" class="input" maxlength="10" size="25"></td> </tr> <tr> <td>CTC</td> <td><input type="text" name="ctc" class="input" maxlength="10" size="25"></td> </tr> </table><br><br><br><br><br><br> New AC Details: <hr size=2> <table align="left" border="0"> <tr> <td>Select Type of Account</td> <td><select name="actype"><option value="1">--Select--</option><option value="commercial">Commercial</option><option value="Savings">Savings</option><option value="Current">Current</option></select></td>

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

- 12 </tr> <tr> <td>Business Turn Over (in INR)</td> <td><input type="text" name="bto" class="input" maxlength="10" size="25"></td> </tr> </table><br><br><br><br><br><br> <input type="submit" value="Register" class="button">&nbsp;<input type="reset" value="Reset" class="button"> </form> </body> </html> newACRequest servlet import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; public class login extends HttpServlet { protected void processRequest(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter printwriter = response.getWriter(); HttpSession session=request.getSession(true); Connection connection = null; Statement statement = null; ResultSet resultset = null; String fname = request.getParameter("fname"); String mname = request.getParameter("mname"); String lname = request.getParameter("lname"); String caddress = request.getParameter("caddress"); String paddress = request.getParameter("paddress"); String mobile = request.getParameter("mobile"); String empstatus = request.getParameter("empstatus"); String empyer = request.getParameter("empyer"); String ctc = request.getParameter("ctc"); String actype = request.getParameter("actype"); String bto = request.getParameter("bto"); try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); connection = DriverManager.getConnection("jdbc:odbc:MYDSN","scott","tiger"); statement = connection.createStatement(); PreparedStatement preparedstatement = connection.prepareStatement("insert into

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

- 13 new_request(FNAME,MNAME,LNAME,CADDRESS,PADDRESS,MOBILE,EMPSTATUS,EMPLOY ER,CTC,AC_TYPE,BTO) values (?,?,?,?,?,?,?,?,?,?,?)"); preparedstatement.setString(1, fname); preparedstatement.setString(2, mname); preparedstatement.setString(3, lname); preparedstatement.setString(4, caddress ); preparedstatement.setString(5, paddress); preparedstatement.setString(6, mobile); preparedstatement.setString(7, empstatus); preparedstatement.setString(8, empyer); preparedstatement.setString(9, ctc ); preparedstatement.setString(10, actype); preparedstatement.setString(11, bto); preparedstatement.execute(); printwriter.println("<center>New Request updated successfully! Thanks for visiting Indian Bank!</center>); catch(Exception exception) { printwriter.println(exception.getMessage()); } } /** Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** Returns a short description of the servlet. */ public String getServletInfo() {

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

- 14 return "Short description"; } }

Question 7- (i) Describe the use of SSL authentication in java clients with the help of suitable code. Ans : How to write various types of SSL clients. Examples of the following types of SSL clients are
provided: SSL Client Sample SSL Client License Requirement: Any stand-alone Java client that uses WebLogic SSL classes to invoke an Enterprise JavaBean (EJB) must use the BEA license file. When you run your client application, set the following system properties on the command line: bea.home=license_file_directory java.protocol.handler.pkgs=com.certicom.net.ssl Where license_file_directory refers to the directory that contains the BEA license file (license.bea). Here is an example of a run command that uses the default location of the license file (c:\bea): java -Dbea.home=c:\bea \ -Djava.protocol.handler.pkgs=com.certicom.net.ssl my_app SSLClient Sample The SSLClient sample demonstrates how to use the WebLogic SSL library to make outgoing SSL connections using URL and URLConnection objects. It shows both how to do this from a standalone application as well as from a servlet in WebLogic Server. Note: When making an outgoing SSL connection, a WebLogic Server instance uses the server's certificate. When communicating to either the same or another WebLogic Server instance with twoway SSL, the originating server's certificate will be verified against the client root CA list in the receiving WebLogic Server instance. List-1 shows a sample SSLClient. This code is taken from the SSLClient.java file located at SAMPLES_HOME\server\examples\src\examples\security\sslclient. Listing 1 SSL Client Sample Code package examples.security.sslclient; import java.io.File; import java.net.URL; import java.io.IOException; import java.io.InputStream; import java.io.FileInputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.Hashtable; import java.security.Provider; import javax.naming.NamingException; import javax.naming.Context; import javax.naming.InitialContext; import javax.servlet.ServletOutputStream; import weblogic.net.http.*;

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

- 15 import weblogic.jndi.Environment; /** SSLClient is a short example of how to use the SSL library of * WebLogic to make outgoing SSL connections. It shows both how to * do this from a stand-alone application as well as from within * WebLogic (in a Servlet). * * Be careful to notice that the WebLogic Server, when making an * outgoing SSL connection, will use that instance of the server's * certificate. When communicating to either the same or another * WebLogic Server with two-way SSL, the originating server's * certificate will be verified against the client root CA list in * the receiving WebLogic Server. * * @author Copyright 1999-2002 by BEA Systems, Inc. All Rights Reserved. */ public class SSLClient { public void SSLClient() {} public static void main (String [] argv) throws IOException { if ((!((argv.length == 4) || (argv.length == 5))) || (!(argv[0].equals("wls"))) ){ System.out.println("example: java SSLClient wls server2.weblogic.com 80 443 /examplesWebApp/SnoopServlet.jsp"); System.exit(-1); } try { System.out.println("----"); if (argv.length == 5) { if (argv[0].equals("wls")) wlsURLConnect(argv[1], argv[2], argv[3], argv[4], System.out); } else { // for null query, default page returned... if (argv[0].equals("wls")) wlsURLConnect(argv[1], argv[2], argv[3], null, System.out); } System.out.println("----"); } catch (Exception e) { e.printStackTrace(); printSecurityProviders(System.out); System.out.println("----"); } } private static void printOut(String outstr, OutputStream stream) { if (stream instanceof PrintStream) {

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

- 16 ((PrintStream)stream).print(outstr); return; } else if (stream instanceof ServletOutputStream) { try { ((ServletOutputStream)stream).print(outstr); return; } catch (IOException ioe) { System.out.println(" IOException: "+ioe.getMessage()); } } System.out.print(outstr); } private static void printSecurityProviders(OutputStream stream) { StringBuffer outstr = new StringBuffer(); outstr.append(" JDK Protocol Handlers and Security Providers:\n"); outstr.append(" java.protocol.handler.pkgs - "); outstr.append(System.getProperties().getProperty( "java.protocol.handler.pkgs")); outstr.append("\n"); Provider[] provs = java.security.Security.getProviders(); for (int i=0; i<provs.length; i++) outstr.append(" provider[" + i + "] - " + provs[i].getName() + " - " + provs[i].getInfo() + "\n"); outstr.append("\n"); printOut(outstr.toString(), stream); } private static void tryConnection(java.net.HttpURLConnection connection, OutputStream stream) throws IOException { connection.connect(); String responseStr = "\t\t" + connection.getResponseCode() + " -- " + connection.getResponseMessage() + "\n\t\t" + connection.getContent().getClass().getName() + "\n"; connection.disconnect(); printOut(responseStr, stream); } /* * This method contains an example of how to use the URL and * URLConnection objects to create a new SSL connection, using * WebLogic SSL client classes. */ public static void wlsURLConnect(String host, String port, String sport, String query,

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

- 17 OutputStream out) { try { if (query == null) query = "/examplesWebApp/index.jsp"; // The following protocol registration is taken care of in the // normal startup sequence of WebLogic. It can be turned off // using the console SSL panel. // // We duplicate it here as a proof of concept in a stand alone // java application. Using the URL object for a new connection // inside of WebLogic would work as expected. java.util.Properties p = System.getProperties(); String s = p.getProperty("java.protocol.handler.pkgs"); if (s == null) { s = "weblogic.net"; } else if (s.indexOf("weblogic.net") == -1) { s += "|weblogic.net"; } p.put("java.protocol.handler.pkgs", s); System.setProperties(p); printSecurityProviders(out); // end of protocol registration printOut(" Trying a new HTTP connection using WLS client classes \n\thttp://" + host + ":" + port + query + "\n", out); URL wlsUrl = null; try { wlsUrl = new URL("http", host, Integer.valueOf(port).intValue(), query); weblogic.net.http.HttpURLConnection connection = new weblogic.net.http.HttpURLConnection(wlsUrl); tryConnection(connection, out); } catch (Exception e) { printOut(e.getMessage(), out); e.printStackTrace(); printSecurityProviders(System.out); System.out.println("----"); } printOut(" Trying a new HTTPS connection using WLS client classes \n\thttps://" + host + ":" + sport + query + "\n", out); wlsUrl = new URL("https", host, Integer.valueOf(sport).intValue(), query); weblogic.net.http.HttpsURLConnection sconnection = new weblogic.net.http.HttpsURLConnection(wlsUrl); // Only when you have configured a two-way SSL connection, i.e. // Client Certs Requested and Enforced is selected in Two Way Client Cert // Behavior field in the Server Attributes

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

- 18 // that are located on the Advanced Options pane under Keystore & SSL // tab on the server, the following private key and the client cert chain // is used. File ClientKeyFile = new File ("clientkey.pem"); File ClientCertsFile = new File ("client2certs.pem"); if (!ClientKeyFile.exists() || !ClientCertsFile.exists()) { System.out.println("Error : clientkey.pem/client2certs.pem is not present in this directory."); System.out.println("To create it run - ant createmycerts."); System.exit(0); } InputStream [] ins = new InputStream[2]; ins[0] = new FileInputStream("client2certs.pem"); ins[1] = new FileInputStream("clientkey.pem"); String pwd = "clientkey"; sconnection.loadLocalIdentity(ins[0], ins[1], pwd.toCharArray()); tryConnection(sconnection, out); } catch (Exception ioe) { printOut(ioe.getMessage(), out); ioe.printStackTrace(); } } }

Question 7(ii) Describe the components of a digital certificate. Ans: Digital Certificates are part of a technology called Public Key Infrastructure or PKI. Digital
certificates have been described as virtual ID cards. This is a useful analogy. There are many ways that digital certificates and ID cards really are the same. Both ID cards and client digital certificates contain information about you, such as your name, and information about the organization that issued the certificate or card to you. Universities generally issue institutional ID cards only after ensuring or validating that you are a bona fide student, faculty, or staff member. In PKI terms, this is called the registration process verifying that you are eligible to receive a certificate and verifying the information in it. Similar to an important ID card, once a digital certificate is issued, it should be managed with care. Just as you would not lend someone else your ID card allowing entry into a secure facility, you should never lend someone your digital certificate. If your certificate or ID card is lost or stolen, it should be reported to the issuing office so that it can be invalidated and a new one issued. How is a digital certificate created? In creating digital certificates a unique cryptographic key pair is generated. One of these keys is referred to as a public key and the other as a private key. Then the certification authoritygenerally on your campuscreates a digital certificate by combining information about you and the issuing organization with the public key and digitally signing the whole thing. This is very much like an organizations ID office filling out an ID card for you and then signing it to make it official.

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

- 19 In PKI terms, the public key for an individual is put into a digital document, along with information about that individual, and then the digital document is signed by the organizations certification authority. This signed document can be transmitted to anyone and used to identify the subject of the certificate. However, the private key of the original key pair must be securely managed and never given to anyone else. As the private key is a very large prime number, it is not something an individual memorizes; rather, the private key must be stored on some device, such as a laptop computer, PDA, or USB key ring. If you send a copy of your certificate to another computer to authenticate yourself, what keeps someone with access to that computer from reusing it later to pretend to be you? Unlike an ID card which is valuable by itself, the digital certificate is useless without the associated private key. That is why protecting the private key is so important. The private key must never be given to anyone else nor left somewhere outside of control by the owner. An added value of digital certificates is that they provide a higher level of security than what we currently have with PIN and password combinations. Users still use passwords, but only on their local computer to protect their digital certificates. If one loses the device on which a digital certificate is stored, a person holding the certificate would still need the password to unlock the certificate

Q 8:(i) Assume that there is a table named Fecully in Oracle with fields (f_id, f_name, f_room, f_department). Write a code using servlet which will display all the fields of a faculty table is tabular manner. Ans: import java.sql.*;
import org.apache.commons.dbcp.BasicDataSource; public class GetAllRowsDBCP { public static void main(String[] args) { System.out.println("Getting All Rows from a table!\n"); BasicDataSource bds = new BasicDataSource(); bds.setDriverClassName("com.mysql.jdbc.Driver"); bds.setUrl("jdbc:mysql://localhost:3306/mydb"); bds.setUsername("root"); bds.setPassword(""); try { Connection con = bds.getConnection(); try { Statement st = con.createStatement(); ResultSet res = st.executeQuery("SELECT * FROM faculty"); System.out.println("faculty id: " + "\t\t" + "faculty name: "+ "\t\t" +faculty room+ "\t\t" +faculty department); while (res.next()) { String fid = res.getInt("f_id"); String fname = res.getString("f_name"); String froom = res.getString("f_room") String fdept = res.getString("f_department"); System.out.println(fid + "\t\t" + fname+ "\t\t" +froom+ "\t\t" +fdept);

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

- 20 } con.close(); } catch (SQLException s) { System.out.println("SQL code does not execute."); } } catch (Exception e) { e.printStackTrace(); } } }

Question 8(ii) Describe 5 benefits of EJB architecture to an application developer. Ans:Benefits of EJB technology Some of the benefits of using enterprise beans are:
Component portability The EJB architecture provides a simple, elegant component container model. Java server components can be developed once and deployed in any EJB-compliant server. Architecture independence The EJB architecture is independent of any specific platform, proprietary protocol, or middleware infrastructure. Applications developed for one platform can be redeployed on other platforms. Developer productivity The EJB architecture improves the productivity of application developers by standardizing and automating the use of complex infrastructure services such as transaction management and security checking. Developers can create complex applications by focusing on business logic rather than environmental and transactional issues. Customization Enterprise bean applications can be customized without access to the source code. Application behaviour and runtime settings are defined through attributes that can be changed when the enterprise bean is deployed. Multitier technology The EJB architecture overlays existing infrastructure services. Versatility and scalability The EJB architecture can be used for small-scale or large-scale business transactions. As processing requirements grow, the enterprise beans can be migrated to more powerful operating environments. In addition to these general benefits of using EJB technology, there are specific benefits of using enterprise beans with CICS. For example: Superior workload management You can balance client connections across a set of cloned listener regions. You can use CICSPlex SM or the CICS distributed routing program to balance OTS transactions across a set of cloned AORs. Superior transaction management Enterprise beans in a CICS EJB server benefit from CICS transaction management servicesfor example:

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

- 21 Shunting System log management Performance optimizations Runaway detection Deadlock detection TCLASS management Monitoring and statistics

Q9: (i) List the features of Semantic database. Ans:


1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. Semantic Database Design Optimal Processing Algorithms Efficient Storage Techniques Application Schema Design Methodology ODBC/SQL Compliance Semantic SQL Internet/WEB Enabled Exceptional usability and flexibility Shorter application design and programming cycle Provides user control via an intuitive structure of information Empowers end-users to pose complex ad hoc decision support queries Superior efficiency-Highest level of optimization Massive reduction in storage size for large applications, such as Data Warehouses Directly supports conceptual data model of the enterprise Internet-integrated Semantic view mirrors real world Complex relations made simple Queries made simple, very short Shorter application programs No restrictions on data Very efficient full indexing Full indexing -- indexing on every attribute and relationship Flexible classification of objects Lazy queries Compaction of sparse data No keys are needed Automatic consistency of database Better concurrency control Multi-processor parallelism Interoperability (ODBC, SQL) No tuning required Benchmarks

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

- 22 -

Q9(ii) What are the challenges in designing multimedia database? Ans : Many inherent characteristics of multimedia data have direct and indirect impacts on the
design of MMDBs. These include : the huge size of MMDBs, temporal nature, richness of content, complexity of representation and subjective interpretation. The major challenges in designing multimedia databases arise from several requirements they need to satisfy such as the following: 1. Manage different types of input, output, and storage devices. Data input can be from a variety of devices such as scanners, digital camera for images, microphone, MIDI devices for audio, video cameras. Typical output devices are high-resolution monitors for images and video, and speakers for audio. 2. Handle a variety of data compression and storage formats. The data encoding has a variety of formats even within a single application. For instance, in medical applications, the MRI images of brain has lossless or very stringent quality of lossy coding technique, while the X-ray images of bones can be less stringent. Also, the radiological image data, the ECG data, other patient data, etc. have widely varying formats. 3. Support different computing platforms and operating systems. Different users operate computers and devices suited to their needs and tastes. But they need the same kind of userlevel view of the database. 4. Integrate different data models. Some data such as numeric and textual data are best handled using a relational database model, while some others such as video documents are better handled using an object-oriented database model. So these two models should coexist together in MMDBs. 5. Offer a variety of user-friendly query systems suited to different kinds of media. From a user point of view, easy-to-use queries and fast and accurate retrieval of information is highly desirable. The query for the same item can be in different forms. For example, a portion of interest in a video can be queried by using either 1) a few sample video frames as an example, 2) a clip of the corresponding audio track or 3) a textual description using keywords. 6. Handle different kinds of indices. The inexact and subjective nature of multimedia data has rendered keyword-based indices and exact and range searches used in traditional databases ineffective. For example, the retrieval of records of persons based on social security number is precisely defined, but the retrieval of records of persons having certain facial features from a database of facial images requires, content-based queries and similarity-based retrievals. This requires indices that are content dependent, in addition to key-word indices. 7. Develop measures of data similarity that correspond well with perceptual similarity. Measures of similarity for different media types need to be quantified to correspond well with the perceptual similarity of objects of those data types. These need to be incorporated into the search process 8. Provide transparent view of geographically distributed data. MMDBs are likely to be a distributed nature. The media data resides in many different storage units possibly spread out geographically. This is partly due to the changing nature of computation and computing resources from centralized to networked and distributed. 9. Adhere to real-time constraints for the transmission of media data. Video and audio are inherently temporal in nature. For example, the frames of a video need to be presented at the rate of at least 30 frames/sec. for the eye to perceive continuity in the video. 10. Synchronize different media types while presenting to user. It is likely that different media types corresponding to a single multimedia object are stored in different formats, on different devices, and have different rates of transfer. Thus they need to be periodically synchronized for presentation.

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

- 23 The recent growth in using multimedia data in applications has been phenomenal. Multimedia databases are essential for efficient management and effective use of huge amounts of data. The diversity of applications using multimedia data, the rapidly changing technology, and the inherent complexities in the semantic representation, interpretation and comparison for similarity pose many challenges. MMDBs are still in their infancy. Today's MMDBs are closely bound to narrow application areas. The experiences acquired from developing and using novel multimedia applications will help advance the multimedia database technology.

PEET KUMAR

ENROLLMENT NO. 084458114

MCA

You might also like