programming XML by Example phần 9 ppt

53 234 0
programming XML by Example phần 9 ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

{ “name”, “street”, “postal-code”, “locality”, “country”, “email” }; int found = 0; for(int i = 0;i < fields.length;i++) { String value = request.getParameter(fields[i]); if(!XMLUtil.isEmpty(value)) found++; } return found == fields.length; } /** * save the order * @param request the request received from the client * @param response interface to the client * @exception IOException error writing the reply * @exception ServletException error in processing the request */ public void doSaveOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String productid = request.getParameter(“product”), merchantid = request.getParameter(“merchant”); Product product = getProduct(merchantid,productid); if(null == product) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } Merchant merchant = product.getMerchant(); String postURL = merchant.getPostURL(); Writer writer = null; if(null != postURL) 409 The Middle Tier continues 14 2429 CH12 2.29.2000 2:25 PM Page 409 writer = new StringWriter(); else { String directory = getInitParameter(merchant.getID() + “.orders”), // should be enough to avoid duplicates fname = String.valueOf(System.currentTimeMillis()) + “.xml”; File file = new File(directory,fname); writer = new FileWriter(file); } writer.write(“<?xml version=\”1.0\”?>”); writer.write(“<order>”); writer.write(“<buyer”); writeAttribute(“name”,request,writer); writeAttribute(“street”,request,writer); writeAttribute(“region”,request,writer); writeAttribute(“postal-code”,request,writer); writeAttribute(“locality”,request,writer); writeAttribute(“country”,request,writer); writeAttribute(“email”,request,writer); writer.write(“/>”); writer.write(“<product”); writeAttribute(“quantity”,request,writer); writer.write(“ id=\””); writer.write(product.getID()); writer.write(“\” name=\””); writer.write(product.getName()); writer.write(“\” price=\””); writer.write(product.getPrice()); writer.write(“\”/></order>”); writer.close(); if(null != postURL) { Dictionary parameters = new Hashtable(); String user = merchant.getPostUser(), password = merchant.getPostPassword(), 410 Chapter 12: Putting It All Together: An e-Commerce Example Listing 12.12: continued 14 2429 CH12 2.29.2000 2:25 PM Page 410 xmlData = writer.toString(); parameters.put(“user”,user); parameters.put(“password”,password); parameters.put(“xmldata”,xmlData); HTTPPost post = new HTTPPost(postURL,parameters); post.doRequest(); } writer = response.getWriter(); writer.write(“<HTML><HEAD><TITLE>Checkout</TITLE></HEAD>”); writer.write(“<BODY><P>Thank you for shopping with us!”); writer.write(“<BR><A HREF=\””); writer.write(request.getServletPath()); writer.write(“\”>Return to the shop</A>”); writer.write(“</BODY></HTML>”); writer.flush(); } /** * helper method: return the product */ protected Product getProduct(String merchantid, String productid) throws ServletException { MerchantCollection merchants = shop.getMerchants(); Merchant merchant = merchants.getMerchant(merchantid); if(null != merchant) return merchant.getProduct(productid); else return null; } /** * helper method: write one attribute */ protected void writeAttribute(String id, HttpServletRequest request, 411 The Middle Tier continues 14 2429 CH12 2.29.2000 2:25 PM Page 411 Writer writer) throws IOException { String value = request.getParameter(id); if(!XMLUtil.isEmpty(value)) { writer.write(“ “); writer.write(id); writer.write(“=\””); writer.write(value); writer.write(“\””); } } /** * collect buyer data * @param request the request received from the client * @param response interface to the client * @exception IOException error writing the reply * @exception ServletException error in processing the request */ public void doCollectData(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String productid = request.getParameter(“product”), merchantid = request.getParameter(“merchant”), quantity = request.getParameter(“quantity”); Product product = getProduct(merchantid,productid); if(null == product) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } Writer writer = response.getWriter(); writer.write(“<HTML><HEAD><TITLE>Checkout</TITLE></HEAD>”); writer.write(“<BODY><P>Enter your name and address:”); 412 Chapter 12: Putting It All Together: An e-Commerce Example Listing 12.12: continued 14 2429 CH12 2.29.2000 2:25 PM Page 412 writer.write(“<FORM METHOD=\”POST\” ACTION=\””); writer.write(request.getServletPath() + “/checkout”); writer.write(“\”><TABLE BORDER=\”0\”>”); writeRow(“Name *:”,”name”,request,writer); writeRow(“Street *:”,”street”,request,writer); writeRow(“Region:”,”region”,request,writer); writeRow(“ZIP or postal-code *:”,”postal-code”,request,writer); writeRow(“Locality *:”,”locality”,request,writer); writeRow(“Country *:”,”country”,request,writer); writeRow(“Email *:”,”email”,request,writer); writer.write(“</TABLE>”); writer.write(“Your order: “); writer.write(quantity); writer.write(“ * “); writer.write(product.getName()); writer.write(“ at “); writer.write(product.getPrice()); writer.write(“ each<BR>”); writer.write(“<INPUT TYPE=\”HIDDEN\” NAME=\”product\””); writer.write(“ VALUE=\””); writer.write(productid); writer.write(“\”>”); writer.write(“<INPUT TYPE=\”HIDDEN\” NAME=\”merchant\””); writer.write(“ VALUE=\””); writer.write(merchantid); writer.write(“\”>”); writer.write(“<INPUT TYPE=\”HIDDEN\” NAME=\”quantity\””); writer.write(“ VALUE=\””); writer.write(quantity); writer.write(“\”>”); writer.write(“<INPUT TYPE=\”SUBMIT\” VALUE=\”Order\”>”); writer.write(“</FORM></HTML>”); writer.flush(); } /** * helper method: write one row 413 The Middle Tier continues 14 2429 CH12 2.29.2000 2:25 PM Page 413 */ protected void writeRow(String label, String id, HttpServletRequest request, Writer writer) throws IOException { writer.write(“<TR><TD>”); writer.write(label); writer.write(“</TD><TD>”); writer.write(“<INPUT TYPE=\”TEXT\” NAME=\””); writer.write(id); writer.write(“\””); String value = request.getParameter(id); if(!XMLUtil.isEmpty(value)) { writer.write(“ VALUE=\””); writer.write(value); writer.write(“\””); } writer.write(“></TD></TR>”); } } Listing 12.13: HTTPPost.java package com.psol.xcommerce; import java.io.*; import java.net.*; import java.util.*; /** * Does an HTTP POST. * * @version Sep 10, 1999 * @author Benoît Marchal <bmarchal@pineapplesoft.com> */ 414 Chapter 12: Putting It All Together: An e-Commerce Example Listing 12.12: continued 14 2429 CH12 2.29.2000 2:25 PM Page 414 public class HTTPPost { /** * properties */ protected URL url; protected String query; /** * Creates a new HTTPPost. * @param url URL to connect to * @parameters POST request parameter */ public HTTPPost(URL url,Dictionary parameters) { this.url = url; query = buildQuery(parameters); } /** * Creates a new HTTPPost. * @param url URL to connect to * @parameters POST request parameter * @exception MalformedURLException if the URL is invalid */ public HTTPPost(String url,Dictionary parameters) throws MalformedURLException { this(new URL(url),parameters); } /** * executes the post request * @exception IOException error posting the data */ public void doRequest() throws IOException 415 The Middle Tier continues 14 2429 CH12 2.29.2000 2:25 PM Page 415 { // this stupid thing does not default to 80 int port = url.getPort(); if(port == -1) port = 80; Socket s = new Socket(url.getHost(),port); PrintStream o = new PrintStream(s.getOutputStream()); o.print(“POST “); o.print(url.getFile()); o.print(“ HTTP/1.0\r\n”); o.print(“Accept: text/html text/xml\r\n”); o.print(“Host: “); o.print(url.getHost()); o.print(“\r\n”); o.print(“Content-type: “); o.print(“application/x-www-form-urlencoded\r\n”); o.print(“Content-length: “); o.print(query.length()); o.print(“\r\n\r\n”); o.print(query); o.print(“\r\n”); InputStream i = s.getInputStream(); StringBuffer reply = new StringBuffer(); int c = i.read(); boolean firstLine = true; while(c != -1) { if(firstLine) if(c == ‘\r’ || c == ‘\n’) firstLine = false; else reply.append((char)c); c = i.read(); } String stReply = reply.toString(); int returnCode = Integer.parseInt(stReply.substring(9,12)); if(!(returnCode >= 200 && returnCode < 300)) throw new ProtocolException(stReply.substring(13)); } /** 416 Chapter 12: Putting It All Together: An e-Commerce Example Listing 12.13: continued 14 2429 CH12 2.29.2000 2:25 PM Page 416 * format the request according to the proper encoding * @param parameters query parameters * @return string with the query properly formatted */ protected String buildQuery(Dictionary parameters) { StringBuffer request = new StringBuffer(); Enumeration keys = parameters.keys(); String key = null; boolean first = true; while(keys.hasMoreElements()) { if(!first) request.append(‘&’); else first = false; key = (String)keys.nextElement(); request.append(key); request.append(‘=’); request.append( URLEncoder.encode((String)parameters.get(key))); // request.append(“\r\n”); } return request.toString(); } } Encapsulating XML Tools You use the DOM interface to encapsulate tools in XCommerce; however, there are holes in DOM. In particular, there is no standard way to create or parse XML documents. The XSL processor is even worse because it has no API at all. The class XMLUtil encapsulates the vendor-specific part in the XML parser and XSL processor. If you later decide to use another XML parser, XMLUtil is the only class that needs updating. XMLUtil is defined in Listing 12.14. 417 Encapsulating XML Tools EXAMPLE 14 2429 CH12 2.29.2000 2:25 PM Page 417 Listing 12.14: XMLUtil.java package com.psol.xcommerce; import java.io.*; import java.util.*; import org.xml.sax.*; import org.w3c.dom.*; import com.lotus.xsl.*; import javax.servlet.*; import com.ibm.xml.dom.*; import com.ibm.xml.parsers.*; import com.lotus.xml.*; import com.lotus.xml.xml4j2dom.*; /** * XMLUtil isolates non-portable aspects of DOM, calling * XSL processor and some utility functions.<BR> * This version is for IBM’s XML for Java, to use another * processor this is the only class to change. * * @version Sep 10, 1999 * @author Benoît Marchal <bmarchal@pineapplesoft.com> */ class XMLUtil { /** * the HTML doctype */ protected static final String DOCTYPE = “<!DOCTYPE HTML PUBLIC \”-//W3C//DTD HTML 4.0 “ + “Transitional//EN\”>”; /** * parses a document with DOM * @param systemID system id (URL) for the document * @return DOM Document * @exception ServletException error parsing the document 418 Chapter 12: Putting It All Together: An e-Commerce Example 14 2429 CH12 2.29.2000 2:25 PM Page 418 [...]... continues 14 24 29 CH12 444 2. 29. 2000 2:25 PM Page 444 Chapter 12: Putting It All Together: An e-Commerce Example Listing 12.17: continued { stmt.close(); } writer.write(“”); writer.flush(); } } Viewer and Editor EXAMPLE XMLi is a smaller merchant It doesn’t have a Web site or a database XMLi creates its list of products manually with the editor shown in Listings 12.18, 12. 19, and 12.20 Listing... request.getParameter(“user”), sqlPassword = request.getParameter(“password”), xmlData = request.getParameter(“xmldata”); Reader reader = new StringReader(xmlData); Document orderDocument = XMLUtil.parse(reader); Element orderElement = orderDocument.getDocumentElement(), buyerElement = XMLUtil.extractFirst(orderElement,”buyer”), productElement = XMLUtil.extractFirst(orderElement,”product”); String name = buyerElement.getAttribute(“name”),... response.setStatus(HttpServletResponse.SC_OK); response.setContentType(“text /xml ); Writer writer = response.getWriter(); writer.write(“< ?xml version=\”1.0\”?>”); writer.write(“200”); writer.flush(); } } Listing 12.17 is XMLServerConsole, a simple management interface for the database 14 24 29 CH12 2. 29. 2000 2:25 PM Page 435 The Data Tier 435 Listing 12.17: XMLServerConsole.java package com.psol.xcommerce; import... java.io.*; import java.sql.*; import java.text.*; import org.w3c.dom.*; import javax.servlet.*; import javax.servlet.http.*; /** * XMLServer returns database records in XML * * @version Dec 23, 199 9 * @author Benoît Marchal */ public class XMLServer extends HttpServlet { /** * currency formater for numbers */ protected NumberFormat formatter = NumberFormat.getCurrencyInstance();...14 24 29 CH12 2. 29. 2000 2:25 PM Page 4 19 Encapsulating XML Tools 4 19 */ public static Document parse(String systemID) throws ServletException { try { DOMParser parser = new DOMParser(); parser.parse(systemID); return parser.getDocument();... text.append(t.getData()); } } } 14 24 29 CH12 2. 29. 2000 2:25 PM Page 427 Encapsulating XML Tools return text.toString(); } /** * check if a string is empty * @param string string to test * @return true if empty, false otherwise */ public static boolean isEmpty(String string) { if(null != string) return string.trim().length() == 0; else return true; } /** * Write the input in XML (or HTML) by escaping what * must... writing */ public static void writeInXML(Writer writer,String string) throws IOException { for(int i = 0;i < string.length();i++) { char c = string.charAt(i); if(c == ‘ . @version Sep 10, 199 9 * @author Benoît Marchal <bmarchal@pineapplesoft.com> */ 414 Chapter 12: Putting It All Together: An e-Commerce Example Listing 12.12: continued 14 24 29 CH12 2. 29. 2000 2:25. 12.14. 417 Encapsulating XML Tools EXAMPLE 14 24 29 CH12 2. 29. 2000 2:25 PM Page 417 Listing 12.14: XMLUtil.java package com.psol.xcommerce; import java.io.*; import java.util.*; import org .xml. sax.*; import. com.lotus.xsl.*; import javax.servlet.*; import com.ibm .xml. dom.*; import com.ibm .xml. parsers.*; import com.lotus .xml. *; import com.lotus .xml. xml4j2dom.*; /** * XMLUtil isolates non-portable aspects of DOM,

Ngày đăng: 13/08/2014, 21:21

Tài liệu cùng người dùng

Tài liệu liên quan