import javax.servlet.*; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.net.*; import java.sql.*; import java.util.*; import java.sql.*; import java.util.Properties; import java.util.*; import WebFlow.*; import WebFlow.submitJob.*; import org.w3c.dom.*; import com.ibm.xml.parser.Parser; import com.ibm.xml.parser.TXDocument; /** * ImageDBServlet.java * * This servlet demonstrates how to use JDBC driver to access the * image database from the servlet, thus shows a 3-tier JDBC example. * * @author xjqiu@npac.syr.edu */ public class ImageDBServlet extends HttpServlet { String imgname; String color; String type; String url; String noneLabel=" "; String prefix ="http://class-server.npac.syr.edu:3768/cps616spring99-docs/cy99xfq/accessaries/"; StringBuffer outputStr; DataOutput outputStream; String Filename = "tempxml"; Document doc; Element root; /** * * doGet() method * At Server side, collection query information from client side interface, * access Image Database, send back HTML file containing query results * */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { Connection con; PrintWriter out; res.setContentType("text/html"); out = new PrintWriter(res.getOutputStream()); /** * Connection between client and server side by Servlet. * There are two key functionality: * produceXML --- server gets query table from client, perform Database access and produce XML file. * renderXML --- server gets signal from client, parser XML file and send back display to client. */ if (req.getParameter("imgname") != null) imgname=req.getParameter("imgname"); else imgname=noneLabel; if (req.getParameter("color") != null) color=req.getParameter("color"); else color=noneLabel; if (req.getParameter("type") != null) type=req.getParameter("type"); else type=noneLabel; if (req.getParameter("url") != null) url=req.getParameter("url"); else url=noneLabel; String cntrl = req.getParameter("control"); if(cntrl != null) { if (cntrl.equals("Produce XML")) {//Produce button pressed produceXML(req, out); }else if (cntrl.equals("Render XML")) {//Render button pressed renderXML(out); } } } /** * * There are two key functionalities: * produceXML --- server gets query table from client, perform Database access and produce XML file. * renderXML --- server gets signal from client, parser XML file and send back display to client. */ private void produceXML(HttpServletRequest req, PrintWriter out) { String sql; sql = getSQLstring(req); open(); Vector vec = getRecords(sql); Hashtable ht ; printXMLHeader(); for(Enumeration e = vec.elements(); e.hasMoreElements(); ){ ht = (Hashtable) e.nextElement(); printXMLbody(ht); } printXMLFooter(); close(); informClient(out); } private void renderXML(PrintWriter out) { //Insert new record to database file Vector vec = getXMLvalues(Filename); Hashtable ht ; printPageHeader(out); if(vec.size() <= 0) { out.println("
No Records Matched the Query !
"); }else { for(Enumeration e = vec.elements(); e.hasMoreElements(); ){ ht = (Hashtable) e.nextElement(); printPagebody(ht,out); } } printPageFooter(out); } /** * Return successful producing XML file message to client. */ private void informClient(PrintWriter out) { out.println(""); out.println(" ImageDB Servlet Page "); out.println(""); out.println("
XML file has been produced.
"); out.println("
Press \"Render\" for display.
"); out.println("
"); out.println("
"); out.println("
"); out.println(""); out.println("
Image   Database"); out.println("
Image Name : "); out.println("
Color : "); out.println("
Type : "); out.println("
URL : "); out.println("

"); out.println(""); out.println(""); out.println(""); out.println("

"); out.println("
"); out.println("Back"); out.println(""); out.println(""); out.flush(); } /** * * There are three methods to produce XML file at server side: * printXMLHeader --- * printXMLbody --- * printXMLFooter --- * */ private boolean printXMLHeader( ) { try { //creates a Document object; doc = (Document)Class.forName("com.ibm.xml.parser.TXDocument").newInstance(); //makes the "Images" element as the root, and adds it. root = doc.createElement("Images"); return true; } catch(Exception ex) { System.err.println("printPageFooter->error happened in printXMLHeader..." ); ex.printStackTrace(); return false; } } private boolean printXMLbody(Hashtable ht) { try { //Makes the "Image" element, and adds it Element item= doc.createElement("Image"); item.setAttribute("imgname", ht.get("imgname").toString()); item.setAttribute("color", ht.get("color").toString()); item.setAttribute("type", ht.get("type").toString()); item.setAttribute("url", ht.get("url").toString()); item.appendChild(doc.createTextNode(ht.get("imgname").toString()+" Node")); root.appendChild(item); return true; } catch (Exception ex) { System.err.println("printXML->error happened in printXMLbody..." ); ex.printStackTrace(); return false; } } private boolean printXMLFooter( ) { try { //create the command //doc.appendChild(doc.createComment("DOCTYPE application SYSTEM")); //add the root doc.appendChild(root); // Shows the XML document ((TXDocument)doc).setVersion("1.0"); //((TXDocument)doc).printWithFormat(new PrintWriter(System.out)); ((TXDocument)doc).print(new FileWriter(Filename)); return true; } catch(Exception ex) { System.err.println("printPageFooter->error happened in pringXMLFooter..." ); ex.printStackTrace(); return false; } } /** * * There are three methods to parse XML file, interprate them into HTML and send back to client for display. * printPageHeader --- * printPagebody --- * printPageFooter --- * */ private boolean printPageHeader(PrintWriter out) { try { out.println(""); out.println(""); out.println("3-Tier Model - Java Servlet, XML and JDBC"); out.println(""); out.println(""); out.println("

Images

"); out.println("
"); out.println("
"); out.println(""); out.println(""); return true; } catch(Exception ex) { System.err.println("printPageFooter->error display..." ); ex.printStackTrace(); return false; } } private boolean printPagebody(Hashtable ht, PrintWriter out) { try { out.println(""); out.println(""); out.println(""); out.println(""); return true; } catch (Exception ex) { System.err.println("printPageBody->error display..." ); ex.printStackTrace(); return false; } } private boolean printPageFooter(PrintWriter out) { try { out.println("
 
Name :"+ ht.get("imgname").toString()+""); out.println("
Color :"+ht.get("color").toString()+"
Type :"+ht.get("type").toString()+"
 "); out.println("
"); out.println("
"); out.println("
"); out.println("
"); out.println(""); out.println(""); out.println(""); out.flush(); return true; } catch (Exception ex) { System.err.println("printPageFooter->error display..." ); ex.printStackTrace(); return false; } } /** * * This is an important method which uses * IBM Parser to parse the XML file * store data values into a vector of hashtables. * */ private Vector getXMLvalues(String fname) { Vector vec = new Vector(); Hashtable ht = new Hashtable(); try { FileInputStream is = new FileInputStream(fname); Parser parser = new Parser(fname); Document doc = parser.readStream(is); if(parser.getNumberOfErrors()>0) { System.exit(1); } Node root = doc.getDocumentElement(); String attribute; for(Node child= root.getFirstChild(); child!=null; child= child.getNextSibling()) { ht.put("imgname", ((Element)child).getAttribute("imgname")); ht.put("color", ((Element)child).getAttribute("color")); ht.put("type", ((Element)child).getAttribute("type")); ht.put("url", ((Element)child).getAttribute("url")); vec.addElement(ht.clone()); ht.clear(); } }catch(Exception e) { System.out.println(e.getMessage()); System.out.println("Exception inside getXMLvalues..."); } return vec; } /** * * Access Database. * */ private String getSQLstring(HttpServletRequest req) { String tmpstr = "select * from images_table where "; StringBuffer strbuf = new StringBuffer(); if(!(imgname.trim().equals(""))) { strbuf.append("upper(imgname)=upper('"+(req.getParameter("imgname")).trim()+"') and "); }else { strbuf.append("imgname like '%' and "); } if(!(color.trim().equals(""))) { strbuf.append("upper(color)=upper('"+(req.getParameter("color")).trim()+"') and "); }else { strbuf.append("color like '%' and "); } if(!(type.trim().equals(""))) { strbuf.append("upper(type)=upper('"+(req.getParameter("type")).trim()+"') and "); }else { strbuf.append("type like '%' and "); } if(!(url.trim().equals(""))) { strbuf.append("upper(url)=upper('"+(req.getParameter("url")).trim()+"');"); }else { strbuf.append("url like '%'"); } tmpstr = tmpstr + strbuf.toString(); if(tmpstr == null || tmpstr.equals("") ) return noneLabel; else return tmpstr; } private String get(String key, Hashtable ht){ //Check keyword field, subsitute null field with " " if(ht.get(key) != null) return ht.get(key).toString(); else return " "; } public Connection conn; private void open() { //Open the connection to DB try { Class.forName("oracle.jdbc.driver.OracleDriver"); conn = DriverManager.getConnection ("jdbc:oracle:thin:@carver.npac.syr.edu:1521:europe", "xjqiu", "judy"); System.out.println("Connection Open"); } catch (Exception e) { System.err.println("Error connection: " + e);} } private int getMaxId(String sql) { //Get the Maxium id from records returned int i = 0; try { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); if(rs == null) return -1; rs.next(); i = rs.getInt("max(id)"); rs.close(); stmt.close(); }catch(Exception e) { e.printStackTrace(System.out); return -1; } return i; } private int executeSQL(String sql) { // Execute Query operation by input sql string int i = -1; try { Statement stmt = conn.createStatement(); stmt.execute(sql); i = 1; stmt.close(); }catch(Exception e) { System.out.println("Exception in updating record"); e.printStackTrace(System.out); } return i; } private Vector getRecords(String sql) {//Return all records that matches the given name/phone field Vector vec = new Vector(); Hashtable ht = new Hashtable(); try { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); while(rs.next()) { ht.put("id",new Integer(rs.getInt("id"))); ht.put("imgname",rs.getString("imgname")); ht.put("color",rs.getString("color")); ht.put("type",rs.getString("type")); ht.put("url",rs.getString("url")); vec.addElement(ht.clone()); System.out.println("Hashtable inside getRec = "+ht); ht.clear(); } rs.close(); stmt.close(); }catch(Exception e) { System.out.println(e.getMessage()); System.out.println("Exception inside getRecords..."); } return vec; } private void close() { //Close connection to DB try { conn.close(); System.out.println("Connection Closed"); } catch (Exception e) {System.err.println("Error in closing dbase");} } }//end of class