ࡱ > [@ 5S bjbj44 : Vi Vi mJ .O .O .O 8 fO l O " P ( P " P P P R R R ; / ? O $ R B s R R R R R s P P ; k k k R P P k R k k xl @ V P ~P N!, .O ba h f ~ 0 r i V V j t R 'R k 5R AR R R R s s > G D k ( G Lab 2 Due: Wednesday, February 22, 2006
Lab Topics: Servlets, XML DOM, JDBC, RDBMS
In lab 1 you worked with the Simple API for XML (SAX) to read RSS news feeds. In this lab you will work with XMLs Document Object Model to read and process XML documents.
The language that you will process will be made up of documents describing individual schedules. Schedule documents are not as prevalent on the web as are RSS documents. It is anticipated that the web of the future will contain a wide variety of data sources in XML.
The schedule documents that you will process will be both static and dynamic. The static documents will be found locally and on the internet. The dynamic documents will be generated from a relational database system. Directions for accessing Microsofts Access database from a servlet will be provided. Feel free to use any relational database management system.
Part I Web/Database Integration Exercise Two Questions at 10 Points Each
Build a simple database and use Microsofts administrative tool to give it a system wide name.
===================================================================
Create a simple database with a single table called student. Store the student table in an Access database called studentDB.mdb. Each row of the table will be a triple holding a primary key, student name and student qpa.
Choose Start/Settings/Control Panel/Administrative Tools/Data Sources ODBC/System DSN.
Choose Add and select Access. Enter the name MyStudentTable and then browse the file system and associate the name with the studentDB.mdb file created above. You will access this database from within a servlet by referring to the name MyStudentTable.
Write a servlet that reads the database and writes HTML to a browser
=================================================
Build the appropriate directory structure for Tomcat.
Within your build.properties file include the line:
app.path=/MyStudentReader
Within the web directory include the following index.html file:
Read MS Access
The web.xml file will contain the following:
TestServlet
ReadStudentDB
TestServlet
/getByName/*
Use ant to compile the servlet called ReadStudentDB.java found here and placed under the src directory.
// ReadStudentDB.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
import java.util.*;
public class ReadStudentDB extends HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse response)
throws ServletException,
IOException {
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:MyStudentTable");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String resultString = "";
String selectStatement = "select * " + "from student";
PreparedStatement prepStmt =
con.prepareStatement(selectStatement);
ResultSet rs = prepStmt.executeQuery();
resultString += "";
while (rs.next()) {
resultString += rs.getString(1)+"";
resultString += rs.getString(2)+"
";
}
resultString += "";
prepStmt.close();
out.println(resultString);
}
catch (SQLException ex) {
System.out.println("SQL EX " + ex.getMessage());
}
catch(Exception ex) {
System.out.println(" A Wierd Exception " + ex);
}
finally {
try {
if(con != null) con.close();
}
catch(SQLException e){
System.out.println("Problem closing");
}
}
}
}
Testing and submission
Make sure Tomcat is running.
Use a browser to visit http://localhost:8080/MyStudentReader/index.html.
Paste a screen shot here showing your browser displaying the contents of the student database.
Modify the servlet so that it only displays the student whose name is entered in the HTML form. Paste a copy of this new servlet here. Include some screen shots demonstrating that it works. Single quotes are needed in the SQL. See any SQL book for examples.
Part II Reading Schedule.xml using XML DOM
5 Questions (3-7)
In part I you used a browser as the client. In this part you will write your own client. A DOS client will be fine. If you would prefer to add GUI features to your client that would be fine as well. Browser clients are great at reading and interpreting XHTML documents. Your client will be written to read and interpret schedule.xml documents.
Assume that following schedule (schedule.xml) and the following Document Type Definition are available on the internet. In order to simplify the project we will assume that the letters A,B,C, D and E represent well known time slots.
File: schedule.xml located at http://localhost:8080/MccarthysSchedule/schedule.xml
A
B
E
B
C
E
B
C
A
A
C
A
C
A
Figure 2.1
File: Schedule.dtd located at http://localhost:8080/MccarthysSchedule/Schedule.dtd
Figure 2.2
Lets also assume that the following schedule and DTD are available locally:
File: schedule.xml located in the clients directory
C
D
E
A
D
E
B
C
B
B
D
B
D
A
Figure 2.3
File: Schedule.dtd holds the grammar for schedules and is located in the clients directory as well
Figure 2.4
In addition, the client will need to make use of an XML document containing URLs of schedules. This document and its DTD appear next:
File: urlList.xml located in the clients directory
schedule.xml
http://localhost:8080/MccarthysSchedule/schedule.xml
Figure 2.5
File: urlList.dtd located in the clients directory
Figure 2.6
Consider a Java client that reads the list of URLs contained in the urlList.xml file. The program then fetches the schedule documents at those URLs and displays a list of meeting times.
The output of my solution looks like the following:
D:\McCarthy\www\95-702\examples\scheduleOnTheWeb\clientcode>java Scheduler
Processing 2 schedules
Attempting to access schedule.xml
Attempting to access http://localhost:8080/MccarthysSchedule/schedule.xml
Got 2 schedules
Available meeting times
Schedule meeting for Monday at E
Schedule meeting for Tuesday at E
Schedule meeting for Wednesday at B
Schedule meeting for Wednesday at C
Schedule meeting for Sunday at A
Figure 2.7
There are two document types that we are working with. The first is the document type that contains schedule data. The second is the document type that contains a list of URLs.
Below is a wrapper class that reads the URLs into a DOM tree and provides user classes with a simple interface to the URLs.
It will be your responsibility to write the code that handles the schedule document type. This wrapper class should know nothing about the scheduling process. In other words, your wrapper class should only provide simple access to the XML documents fields. In this way, there is a natural separation of concerns and other applications might make use of these classes.
/** URLListDoc.java Wraps urlList.xml documents
Provide an InputSource object to initialize the objects of this class.
An InputSource object may be created with a StringReader containing an XML
document, a String containing a file path or a URL.
This class passes the InputSource object to the parser and the document
is parsed. The documents fields are then available to a client program.
The individual URL strings are returned by calling
public String getURL(int i). The integer i must be in the range 1 <= i <= getNumURLs().
public int getNumURLs() returns an int representing the number of URLs in InputSource.
*/
import java.io.File;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class URLListDoc
{
public final static String ROOT = "URLList";
public final static String URL = "URL";
private Document dom;
/** The constructor takes an InputSource object as input. It passes the InputSource object
* to the parser and builds a DOM tree.
*/
public URLListDoc(InputSource is)
{
try {
DocumentBuilderFactory docBuilderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder =
docBuilderFactory.newDocumentBuilder();
dom = docBuilder.parse(is);
}
catch(SAXParseException err) {
System.out.println("Parsing error" +
", line " + err.getLineNumber() +
", URI " + err.getSystemId());
System.out.println(" " + err.getMessage());
}
catch(SAXException e) {
Exception x = e.getException();
((x == null) ? e : x).printStackTrace();
}
catch (Throwable t) {
t.printStackTrace();
}
}
/** getNumURLs takes no arguments. It simply returns the number of URLs
* read from the InputSource.
* @return int >= 0 representing the number of URL's available.
*/
public int getNumURLs() throws Exception
{
try
{
NodeList nl = dom.getElementsByTagName(URL);
return nl.getLength();
}
catch(Exception ex)
{
ex.printStackTrace(System.err);
throw new Exception("Problems with reading URL data");
}
}
public String getURL(int i) throws Exception
{
try
{
NodeList nl = dom.getElementsByTagName(URL);
Node urlNode = (Node)nl.item(i-1);
Text text = (Text)urlNode.getFirstChild();
return (String)text.getNodeValue();
}
catch(Exception ex)
{
ex.printStackTrace(System.err);
throw new Exception("Problems with getURL");
}
}
/** main is for testing.
*/
public static void main(String args[]) throws Exception {
InputSource is = new InputSource("urlList.xml");
URLListDoc urlDoc = new URLListDoc(is);
for(int k = 1; k <= urlDoc.getNumURLs(); k++){
System.out.println("URL " + k + " = " + urlDoc.getURL(k));
}
}
} Figure 2.8
Please use the same names as mentioned below for your files and classes.
Write a Java application client called Scheduler.java that reads a list of n local URLs and visits the n sites associated with those URLs to retrieve schedules. Scheduler.java then computes and displays all available meeting times (where all n schedules show the same available meeting time slot) on the DOS screen.
Sketch of Scheduler.java:
Reads a URL list by creating an InputSource object pointing to urlList.xml file and passing the InputSource object to the URLList constructor
For each URL listed (there may be many)
Create an InputSource object with that URL and pass it to the ScheduleDoc.java constructor
Work from the n schedules to display every possible meeting time when all participants can
be present. Assume that the meeting times are represented by the letters A,B,C, D and E.
Sketch of URLListDoc.java and ScheduleDoc.java:
Scheduler.java: will make use of two types of documents and so you will provide two Java classes that wrap document instances. One of those classes, URLListDoc.java, is provided in Figure 2.8.
URLListDoc.java
public Constructor : public URLListDoc(InputSource is)
public Methods: public int getNumURLs() throws Exception
public String getURL(int i) throws Exception
ScheduleDoc.java
public constructor : public ScheduleDoc(InputSource is)
public method: public boolean getAvailable(String day, String slot) throws Exception
Demonstrate that your program works
(3) (10 Points) Paste a DOS screen shot showing your program running using the schedules in Figures 2.1 and 2.3. Figure 2.1 must be available on the internet and must be stored as a Tomcat web application. Figure 2.3 should be a local file stored in the same directory as the client. This all happens on your machine.
(4) (10 Points) Paste a DOS screen shot showing your program running using the schedules in Figures 2.1 and 2.3 as well as a schedule available on my server. You will find a schedule at the URL
http://www.andrew.cmu.edu/~mm6/95-702/HempelsSchedule/schedule.xml
Paste a copy here of your updated urlList.xml file. It will now contain a reference to HempelsSchedule.
Paste a copy of the DOS screen shot showing your client running with these three schedules.
(5) (10 Points) This is the same problem as 4 but with one less schedule. Paste a screen shot showing your program running using the schedules in Figures 2.1 and the schedule available from my server. You will find a schedule at http://www.andrew.cmu.edu/~mm6/95-702/HempelsSchedule/schedule.xml
Paste a copy here of your updated urlList.xml file.
Paste a copy here of the DOS screen showing your client run with these two schedules.
(6) (25 Points) Paste a copy of URLListDoc.java , ScheduleDoc.java, and Scheduler.java here. For full credit these programs must have names as specified above and be clean and well documented.
(7) (25 Points) Write a servlet that uses JDBC to access the schedule data from a relational database. Use the JDBC servlet, ReadStudentDB.java, as a guide. Note that ReadStudentDB.java generates XHTML. Rather than generating XHTML, your servlet will generate XML (in particular, schedule.xml.) You need not return a DTD. You may build a DOM tree if you like (see slides on how to create a DOM tree from scratch) or you may decide to simply write schedule.xml tags directly from the servlet. Modify your URL list document so that it holds a pointer to this servlet.
Paste a copy here of your updated urlList.xml file. It will now contain a reference to this new servlet.
Paste a screen shot here of your database table holding a schedule.
Paste a copy of your servlet here. The code should be clean and well-documented.
Paste a copy here of a DOS screen shot demonstrating that your client is able to read from the servlet.
You are not required to turn in a disk with this lab. But please keep your files in case we need to review them. Simply submit a copy of this document to the digital drop box on Blackboard with each question answered.
95-702 Organizational Communication & Distributed Object Technologies Carnegie Mellon University
PAGE
PAGE 1
! # ' ( ) * 2 B K M Y Z [ i
I
~pf\R\H\R\R h^" CJ OJ QJ h3V CJ OJ QJ hyEz CJ OJ QJ hgU CJ OJ QJ hpO h<&