******************* HelloWorld.java Basic Hello World application. ******************* */ public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, world."); } } /*
Aug 29
Basic Hello World application
Aug 29
StringTest.java Demonstrates various methods of the String class.
/** Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class StringTest { public static void main (String[] args) { String str = ""; if (args.length > 0) { str = args[0]; } if (str.length()>8) { System.out.println("String is \"" + str + "\"\n"); System.out.println(" charAt(3) ------------------ " + str.charAt(3)); System.out.println(" compareTo(Moscow) ---------- " + str.compareTo("Moscow")); System.out.println(" concat(SuFFiX) ------------- " + str.concat("SuFFiX")); System.out.println(" endsWith(hic) -------------- " + str.endsWith("hic")); System.out.println(" == Geographic -------------- " + (str == "Geographic")); System.out.println(" equals(geographic) --------- " + str.equals("geographic")); System.out.println(" equalsIgnoreCase(geographic) " + str.equalsIgnoreCase("geographic")); System.out.println(" indexOf('o') --------------- " + str.indexOf('o')); System.out.println(" indexOf('i',5) ------------- " + str.indexOf('i',5)); System.out.println(" indexOf('o',5) ------------- " + str.indexOf('o',5)); System.out.println(" indexOf(rap) --------------- " + str.indexOf("rap")); System.out.println(" indexOf(rap, 5) ------------ " + str.indexOf("rap", 5)); System.out.println(" lastIndexOf('o') ----------- " + str.lastIndexOf('o')); System.out.println(" lastIndexOf('i',5) --------- " + str.lastIndexOf('i',5)); System.out.println(" lastIndexOf('o',5) --------- " + str.lastIndexOf('o',5)); System.out.println(" lastIndexOf(rap) ----------- " + str.lastIndexOf("rap")); System.out.println(" lastIndexOf(rap, 5) -------- " + str.lastIndexOf("rap", 5)); System.out.println(" length() ------------------- " + str.length()); System.out.println(" replace('c','k') ----------- " + str.replace('c','k')); System.out.println(" startsWith(eog,1) ---------- " + str.startsWith("eog",1)); System.out.println(" startsWith(eog) ------------ " + str.startsWith("eog")); System.out.println(" substring(3) --------------- " + str.substring(3)); System.out.println(" substring(3,8) ------------- " + str.substring(3,8)); System.out.println(" toLowerCase() -------------- " + str.toLowerCase()); System.out.println(" toUpperCase() -------------- " + str.toUpperCase()); System.out.println(" trim() --------------------- " + str.trim()); System.out.println("\nString is still \"" + str + "\"\n"); } } }
Aug 29
NegativeLengthException.java Illustrates defining and throwing your own exceptions.
import java.io.*; /** Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class NegativeLengthException extends Exception { /** Test NegativeLengthException */ public static void main(String[] args) { try { int lineLength = readLength(); for(int i=0; i
Aug 29
TreeTest.java Builds a binary tree and prints the contents of the nodes. Uses the following classes:
Treetest.java /** A NodeOperator that prints each node. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ class PrintOperator implements NodeOperator { public void operateOn(Node node) { System.out.println(node.getNodeValue()); } } /** A sample tree representing a parse tree of * the sentence "Java hackers hack Java", using * some simple context-free grammar. */ public class TreeTest { public static void main(String[] args) { Node adjective = new Node(" Adjective", new Leaf(" Java")); Node noun1 = new Node(" Noun", new Leaf(" hackers")); Node verb = new Node(" TransitiveVerb", new Leaf(" hack")); Node noun2 = new Node(" Noun", new Leaf(" Java")); Node np = new Node(" NounPhrase", adjective, noun1); Node vp = new Node(" VerbPhrase", verb, noun2); Node sentence = new Node("Sentence", np, vp); PrintOperator printOp = new PrintOperator(); System.out.println("Depth first traversal:"); sentence.depthFirstSearch(printOp); System.out.println("\nBreadth first traversal:"); sentence.breadthFirstSearch(printOp); } } Leaf.java A leaf node with no children. /** Leaf node: a node with no subtrees. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class Leaf extends Node { public Leaf(Object value) { super(value, null, null); } } Node.java A data structure representing a node in a binary tree. import java.util.Vector; /** A data structure representing a node in a binary tree. * It contains a node value and a reference (pointer) to * the left and right subtrees. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class Node { private Object nodeValue; private Node leftChild, rightChild; /** Build Node with specified value and subtrees. */ public Node(Object nodeValue, Node leftChild, Node rightChild) { this.nodeValue = nodeValue; this.leftChild = leftChild; this.rightChild = rightChild; } /** Build Node with specified value and L subtree. R child * will be null. If you want both children to be null, use * the Leaf constructor. */ public Node(Object nodeValue, Node leftChild) { this(nodeValue, leftChild, null); } /** Return the value of this node. */ public Object getNodeValue() { return(nodeValue); } /** Specify the value of this node. */ public void setNodeValue(Object nodeValue) { this.nodeValue = nodeValue; } /** Return the L subtree. */ public Node getLeftChild() { return(leftChild); } /** Specify the L subtree. */ public void setLeftChild(Node leftChild) { this.leftChild = leftChild; } /** Return the R subtree. */ public Node getRightChild() { return(rightChild); } /** Specify the R subtree. */ public void setRightChild(Node rightChild) { this.rightChild = rightChild; } /** Traverse the tree in depth-first order, applying * the specified operation to each node along the way. */ public void depthFirstSearch(NodeOperator op) { op.operateOn(this); if (leftChild != null) { leftChild.depthFirstSearch(op); } if (rightChild != null) { rightChild.depthFirstSearch(op); } } /** Traverse the tree in breadth-first order, applying the * specified operation to each node along the way. */ public void breadthFirstSearch(NodeOperator op) { Vector nodeQueue = new Vector(); nodeQueue.addElement(this); Node node; while(!nodeQueue.isEmpty()) { node = (Node)nodeQueue.elementAt(0); nodeQueue.removeElementAt(0); op.operateOn(node); if (node.getLeftChild() != null) { nodeQueue.addElement(node.getLeftChild()); } if (node.getRightChild() != null) { nodeQueue.addElement(node.getRightChild()); } } } } NodeOperator.java An interface used in the Node class to ensure that an object has an operateOn method. /** An interface used in the Node class to ensure that * an object has an operateOn method. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public interface NodeOperator { void operateOn(Node node); }
Aug 29
Illustrates the use of arrays
/** Report on a round of golf at St. Andy?s. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class Golf { public static void main(String[] args) { int[] pars = { 4,5,3,4,5,4,4,3,4 }; int[] scores = { 5,6,3,4,5,3,2,4,3 }; report(pars, scores); } /** Reports on a short round of golf. */ public static void report(int[] pars, int[] scores) { for(int i=0; i
Aug 29
Factorial.java Computes an exact factorial, n!, using a BigInteger
import java.math.BigInteger; /** Computes an exact factorial, using a BigInteger. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class Factorial { public static void main(String[] args) { for(int i=1; i<=256; i*=2) { System.out.println(i + "!=" + factorial(i)); } } public static BigInteger factorial(int n) { if (n <= 1) { return(new BigInteger("1")); } else { BigInteger bigN = new BigInteger(String.valueOf(n)); return(bigN.multiply(factorial(n - 1))); } } }
Aug 29
Exec.java Provides static methods for running external processes from applications.
import java.io.*; /** A class that eases the pain of running external processes * from applications. Lets you run a program three ways: * * exec: Execute the command, returning * immediately even if the command is still running. * This would be appropriate for printing a file. * execWait: Execute the command, but don?t * return until the command finishes. This would be * appropriate for sequential commands where the first * depends on the second having finished (e.g., * javac followed by java). * execPrint: Execute the command and print the * output. This would be appropriate for the Unix * command ls. * * Note that the PATH is not taken into account, so you must * specify the full pathname to the command, and shell * built-in commands will not work. For instance, on Unix the * above three examples might look like: * * Exec.exec("/usr/ucb/lpr Some-File"); * Exec.execWait("/usr/local/bin/javac Foo.java"); * Exec.execWait("/usr/local/bin/java Foo"); * Exec.execPrint("/usr/bin/ls -al"); * * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class Exec { private static boolean verbose = true; /** Determines if the Exec class should print which commands * are being executed, and prints error messages if a problem * is found. Default is true. * * @param verboseFlag true: print messages, false: don?t. */ public static void setVerbose(boolean verboseFlag) { verbose = verboseFlag; } /** Will Exec print status messages? */ public static boolean getVerbose() { return(verbose); } /** Starts a process to execute the command. Returns * immediately, even if the new process is still running. * * @param command The full pathname of the command to * be executed. No shell built-ins (e.g., "cd") or shell * meta-chars (e.g. ">") are allowed. * @return false if a problem is known to occur, but since * this returns immediately, problems aren?t usually found * in time. Returns true otherwise. */ public static boolean exec(String command) { return(exec(command, false, false)); } /** Starts a process to execute the command. Waits for the * process to finish before returning. * * @param command The full pathname of the command to * be executed. No shell built-ins or shell metachars are * allowed. * @return false if a problem is known to occur, either due * to an exception or from the subprocess returning a * nonzero value. Returns true otherwise. */ public static boolean execWait(String command) { return(exec(command, false, true)); } /** Starts a process to execute the command. Prints any output * the command produces. * * @param command The full pathname of the command to * be executed. No shell built-ins or shell meta-chars are * allowed. * @return false if a problem is known to occur, either due * to an exception or from the subprocess returning a * nonzero value. Returns true otherwise. */ public static boolean execPrint(String command) { return(exec(command, true, false)); } /** This creates a Process object via Runtime.getRuntime.exec() * Depending on the flags, it may call waitFor on the process * to avoid continuing until the process terminates, and open * an input stream from the process to read the results. */ private static boolean exec(String command, boolean printResults, boolean wait) { if (verbose) { printSeparator(); System.out.println("Executing '" + command + "'."); } try { // Start running command, returning immediately. Process p = Runtime.getRuntime().exec(command); // Print the output. Since we read until there is no more // input, this causes us to wait until the process is // completed. if(printResults) { BufferedReader buffer = new BufferedReader( new InputStreamReader(p.getInputStream())); String s = null; try { while ((s = buffer.readLine()) != null) { System.out.println("Output: " + s); } buffer.close(); if (p.exitValue() != 0) { if (verbose) { printError(command + " -- p.exitValue() != 0"); } return(false); } } catch (Exception e) { // Ignore read errors; they mean the process is done. } // If not printing the results, then we should call waitFor // to stop until the process is completed. } else if (wait) { try { System.out.println(" "); int returnVal = p.waitFor(); if (returnVal != 0) { if (verbose) { printError(command); } return(false); } } catch (Exception e) { if (verbose) { printError(command, e); } return(false); } } } catch (Exception e) { if (verbose) { printError(command, e); } return(false); } return(true); } private static void printError(String command, Exception e) { System.out.println("Error doing exec(" + command + "): " + e.getMessage()); System.out.println("Did you specify the full " + "pathname?"); } private static void printError(String command) { System.out.println("Error executing ?" + command + "?."); } private static void printSeparator() { System.out.println ("=============================================="); } }
Aug 29
Controlling Image Loading
~~~~~~~~~~~~~~~~~~~ ImageBox.java A class that incorrectly tries to load an image and draw an outline around it. The problem is that the size of the image is requested before the image is completely loaded, thus, returning a width and height of -1. ~~~~~~~~~~~~~~~~~~~ import java.applet.Applet; import java.awt.*; /** A class that incorrectly tries to load an image and draw an * outline around it. Don't try this at home. * ******************** public class ImageBox extends Applet { private int imageWidth, imageHeight; private Image image; public void init() { String imageName = getParameter("IMAGE"); if (imageName != null) { image = getImage(getDocumentBase(), imageName); } else { image = getImage(getDocumentBase(), "error.gif"); } setBackground(Color.white); // The following is wrong, since the image won't be done // loading, and -1 will be returned. imageWidth = image.getWidth(this); imageHeight = image.getHeight(this); } public void paint(Graphics g) { g.drawImage(image, 0, 0, this); g.drawRect(0, 0, imageWidth, imageHeight); } } >>>>>>>>>>>>>>>>>> BetterImageBox.java An improved version of ImageBox.java. Here a MediaTracker is used to block (wait till the image is completely loaded) before preceding to determine the image size. >>>>>>>>>>>>>>>>>> import java.applet.Applet; import java.awt.*; /** This version fixes the problems associated with ImageBox by * using a MediaTracker to be sure the image is loaded before * you try to get its dimensions. * ********************************* public class BetterImageBox extends Applet { private int imageWidth, imageHeight; private Image image; public void init() { String imageName = getParameter("IMAGE"); if (imageName != null) { image = getImage(getDocumentBase(), imageName); } else { image = getImage(getDocumentBase(), "error.gif"); } setBackground(Color.white); MediaTracker tracker = new MediaTracker(this); tracker.addImage(image, 0); try { tracker.waitForAll(); } catch(InterruptedException ie) {} if (tracker.isErrorAny()) { System.out.println("Error while loading image"); } // This is safe: image is fully loaded imageWidth = image.getWidth(this); imageHeight = image.getHeight(this); } public void paint(Graphics g) { g.drawImage(image, 0, 0, this); g.drawRect(0, 0, imageWidth, imageHeight); } } >>>>>>>>>>>>>>>>> TrackerUtil.java A utility class that lets you load and wait for an image in a single swoop. >>>>>>>>>>>>>>>>> import java.awt.*; /** A utility class that lets you load and wait for an image or * images in one fell swoop. If you are loading multiple * images, only use multiple calls to waitForImage if you * need loading to be done serially. Otherwise, use * waitForImages, which loads concurrently, which can be * much faster. * ******************* public class TrackerUtil { public static boolean waitForImage(Image image, Component c) { MediaTracker tracker = new MediaTracker(c); tracker.addImage(image, 0); try { tracker.waitForAll(); } catch(InterruptedException ie) {} if (tracker.isErrorAny()) { return(false); } else { return(true); } } public static boolean waitForImages(Image[] images, Component c) { MediaTracker tracker = new MediaTracker(c); for(int i=0; i>>>>>>>>>>>>>>>>>>>>>
Aug 29
HelloWWW2.java Illustrates the ability of an applet to read parameters contained in the HTML document
HelloWWW2.java Illustrates the ability of an applet to read parameters contained in the HTML document (PARAM element containing a NAME-VALUE pair).
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& import java.applet.Applet; import java.awt.*; ************************* public class HelloWWW2 extends Applet { public void init() { setFont(new Font("SansSerif", Font.BOLD, 30)); Color background = Color.gray; Color foreground = Color.darkGray; String backgroundType = getParameter("BACKGROUND"); if (backgroundType != null) { if (backgroundType.equalsIgnoreCase("LIGHT")) { background = Color.white; foreground = Color.black; } else if (backgroundType.equalsIgnoreCase("DARK")) { background = Color.black; foreground = Color.white; } } setBackground(background); setForeground(foreground); } public void paint(Graphics g) { g.drawString("Hello, World Wide Web.", 5, 35); } } >>>>>>>>>>>>>>>>>>>>>>>
Aug 29
An example Travel Site
quick-search.html Front end to travel site <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!-- Front end to travel servlet. Taken from Core Web Programming Java 2 Edition from Prentice Hall and Sun Microsystems Press, . May be freely used or adapted. --> <HTML> <HEAD> <TITLE>Online Travel Quick Search</TITLE> <LINK REL=STYLESHEET HREF="travel-styles.css" TYPE="text/css"> </HEAD> <BODY> <BR> <H1>Online Travel Quick Search</H1> <FORM ACTION="/servlet/cwp.Travel" METHOD="POST"> <CENTER> Email address: <INPUT TYPE="TEXT" NAME="emailAddress"><BR> Password: <INPUT TYPE="PASSWORD" NAME="password" SIZE=10><BR> Origin: <INPUT TYPE="TEXT" NAME="origin"><BR> Destination: <INPUT TYPE="TEXT" NAME="destination"><BR> Start date (MM/DD/YY): <INPUT TYPE="TEXT" NAME="startDate" SIZE=8><BR> End date (MM/DD/YY): <INPUT TYPE="TEXT" NAME="endDate" SIZE=8><BR> <P> <TABLE CELLSPACING=1> <TR> <TH> <IMG SRC="airplane.gif" WIDTH=100 HEIGHT=29 ALIGN="TOP" ALT="Book Flight"> <TH> <IMG SRC="car.gif" WIDTH=100 HEIGHT=31 ALIGN="MIDDLE" ALT="Rent Car"> <TH> <IMG SRC="bed.gif" WIDTH=100 HEIGHT=85 ALIGN="MIDDLE" ALT="Find Hotel"> <TH> <IMG SRC="passport.gif" WIDTH=71 HEIGHT=100 ALIGN="MIDDLE" ALT="Edit Account"> <TR> <TH><SMALL> <INPUT TYPE="SUBMIT" NAME="flights" VALUE="Book Flight"> </SMALL> <TH><SMALL> <INPUT TYPE="SUBMIT" NAME="cars" VALUE="Rent Car"> </SMALL> <TH><SMALL> <INPUT TYPE="SUBMIT" NAME="hotels" VALUE="Find Hotel"> </SMALL> <TH><SMALL> <INPUT TYPE="SUBMIT" NAME="account" VALUE="Edit Account"> </SMALL> </TABLE> </CENTER> </FORM> <BR> <P ALIGN="CENTER"> <B>Not yet a member? Get a free account <A HREF="accounts.jsp">here</A>.</B></P> </BODY> </HTML> Travel.java Servlet used by travel site. Uses the MVC architecture in that servlet just does computation; all presentation done by JSP. Uses the TravelCustomer bean. package cwp; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** Top-level travel-processing servlet. This servlet sets up * the customer data as a bean, then forwards the request * to the airline booking page, the rental car reservation * page, the hotel page, the existing account modification * page, or the new account page. * <P> * Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class Travel extends HttpServlet { private TravelCustomer[] travelData; public void init() { travelData = TravelData.getTravelData(); } /** Since password is being sent, use POST only. However, * the use of POST means that you cannot forward * the request to a static HTML page, since the forwarded * request uses the same request method as the original * one, and static pages cannot handle POST. Solution: * have the "static" page be a JSP file that contains * HTML only. That's what accounts.jsp is. The other * JSP files really need to be dynamically generated, * since they make use of the customer data. */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String emailAddress = request.getParameter("emailAddress"); String password = request.getParameter("password"); TravelCustomer customer = TravelCustomer.findCustomer(emailAddress, travelData); if ((customer == null) || (password == null) || (!password.equals(customer.getPassword()))) { gotoPage("/travel/accounts.jsp", request, response); } // The methods that use the following parameters will // check for missing or malformed values. customer.setStartDate(request.getParameter("startDate")); customer.setEndDate(request.getParameter("endDate")); customer.setOrigin(request.getParameter("origin")); customer.setDestination(request.getParameter ("destination")); HttpSession session = request.getSession(true); session.setAttribute("customer", customer); if (request.getParameter("flights") != null) { gotoPage("/travel/BookFlights.jsp", request, response); } else if (request.getParameter("cars") != null) { gotoPage("/travel/RentCars.jsp", request, response); } else if (request.getParameter("hotels") != null) { gotoPage("/travel/FindHotels.jsp", request, response); } else if (request.getParameter("cars") != null) { gotoPage("/travel/EditAccounts.jsp", request, response); } else { gotoPage("/travel/IllegalRequest.jsp", request, response); } } private void gotoPage(String address, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(address); dispatcher.forward(request, response); } } TravelCustomer Bean package cwp; import java.util.*; import java.text.*; /** Describes a travel services customer. Implemented * as a bean with some methods that return data in HTML * format, suitable for access from JSP. * <P> * Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class TravelCustomer { private String emailAddress, password, firstName, lastName; private String creditCardName, creditCardNumber; private String phoneNumber, homeAddress; private String startDate, endDate; private String origin, destination; private FrequentFlyerInfo[] frequentFlyerData; private RentalCarInfo[] rentalCarData; private HotelInfo[] hotelData; public TravelCustomer(String emailAddress, String password, String firstName, String lastName, String creditCardName, String creditCardNumber, String phoneNumber, String homeAddress, FrequentFlyerInfo[] frequentFlyerData, RentalCarInfo[] rentalCarData, HotelInfo[] hotelData) { setEmailAddress(emailAddress); setPassword(password); setFirstName(firstName); setLastName(lastName); setCreditCardName(creditCardName); setCreditCardNumber(creditCardNumber); setPhoneNumber(phoneNumber); setHomeAddress(homeAddress); setStartDate(startDate); setEndDate(endDate); setFrequentFlyerData(frequentFlyerData); setRentalCarData(rentalCarData); setHotelData(hotelData); } public String getEmailAddress() { return(emailAddress); } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } public String getPassword() { return(password); } public void setPassword(String password) { this.password = password; } public String getFirstName() { return(firstName); } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return(lastName); } public void setLastName(String lastName) { this.lastName = lastName; } public String getFullName() { return(getFirstName() + " " + getLastName()); } public String getCreditCardName() { return(creditCardName); } public void setCreditCardName(String creditCardName) { this.creditCardName = creditCardName; } public String getCreditCardNumber() { return(creditCardNumber); } public void setCreditCardNumber(String creditCardNumber) { this.creditCardNumber = creditCardNumber; } public String getCreditCard() { String cardName = getCreditCardName(); String cardNum = getCreditCardNumber(); cardNum = cardNum.substring(cardNum.length() - 4); return(cardName + " (XXXX-XXXX-XXXX-" + cardNum + ")"); } public String getPhoneNumber() { return(phoneNumber); } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getHomeAddress() { return(homeAddress); } public void setHomeAddress(String homeAddress) { this.homeAddress = homeAddress; } public String getStartDate() { return(startDate); } public void setStartDate(String startDate) { this.startDate = startDate; } public String getEndDate() { return(endDate); } public void setEndDate(String endDate) { this.endDate = endDate; } public String getOrigin() { return(origin); } public void setOrigin(String origin) { this.origin = origin; } public String getDestination() { return(destination); } public void setDestination(String destination) { this.destination = destination; } public FrequentFlyerInfo[] getFrequentFlyerData() { return(frequentFlyerData); } public void setFrequentFlyerData(FrequentFlyerInfo[] frequentFlyerData) { this.frequentFlyerData = frequentFlyerData; } public String getFrequentFlyerTable() { FrequentFlyerInfo[] frequentFlyerData = getFrequentFlyerData(); if (frequentFlyerData.length == 0) { return("<I>No frequent flyer data recorded.</I>"); } else { String table = "<TABLE>\n" + " <TR><TH>Airline<TH>Frequent Flyer Number\n"; for(int i=0; i<frequentFlyerData.length; i++) { FrequentFlyerInfo info = frequentFlyerData[i]; table = table + "<TR ALIGN=\"CENTER\">" + "<TD>" + info.getAirlineName() + "<TD>" + info.getFrequentFlyerNumber() + "\n"; } table = table + "</TABLE>\n"; return(table); } } public RentalCarInfo[] getRentalCarData() { return(rentalCarData); } public void setRentalCarData(RentalCarInfo[] rentalCarData) { this.rentalCarData = rentalCarData; } public HotelInfo[] getHotelData() { return(hotelData); } public void setHotelData(HotelInfo[] hotelData) { this.hotelData = hotelData; } // This would be replaced by a database lookup // in a real application. public String getFlights() { String flightOrigin = replaceIfMissing(getOrigin(), "Nowhere"); String flightDestination = replaceIfMissing(getDestination(), "Nowhere"); Date today = new Date(); DateFormat formatter = DateFormat.getDateInstance(DateFormat.MEDIUM); String dateString = formatter.format(today); String flightStartDate = replaceIfMissing(getStartDate(), dateString); String flightEndDate = replaceIfMissing(getEndDate(), dateString); String [][] flights = { { "Java Airways", "1522", "455.95", "Java, Indonesia", "Sun Microsystems", "9:00", "3:15" }, { "Servlet Express", "2622", "505.95", "New Atlanta", "New Atlanta", "9:30", "4:15" }, { "Geek Airlines", "3.14159", "675.00", "JHU", "MIT", "10:02:37", "2:22:19" } }; String flightString = ""; for(int i=0; i<flights.length; i++) { String[] flightInfo = flights[i]; flightString = flightString + getFlightDescription(flightInfo[0], flightInfo[1], flightInfo[2], flightInfo[3], flightInfo[4], flightInfo[5], flightInfo[6], flightOrigin, flightDestination, flightStartDate, flightEndDate); } return(flightString); } private String getFlightDescription(String airline, String flightNum, String price, String stop1, String stop2, String time1, String time2, String flightOrigin, String flightDestination, String flightStartDate, String flightEndDate) { String flight = "<P><BR>\n" + "<TABLE WIDTH=\"100%\"><TR><TH CLASS=\"COLORED\">\n" + "<B>" + airline + " Flight " + flightNum + " ($" + price + ")</B></TABLE><BR>\n" + "<B>Outgoing:</B> Leaves " + flightOrigin + " at " + time1 + " AM on " + flightStartDate + ", arriving in " + flightDestination + " at " + time2 + " PM (1 stop -- " + stop1 + ").\n" + "<BR>\n" + "<B>Return:</B> Leaves " + flightDestination + " at " + time1 + " AM on " + flightEndDate + ", arriving in " + flightOrigin + " at " + time2 + " PM (1 stop -- " + stop2 + ").\n"; return(flight); } private String replaceIfMissing(String value, String defaultValue) { if ((value != null) && (value.length() > 0)) { return(value); } else { return(defaultValue); } } public static TravelCustomer findCustomer (String emailAddress, TravelCustomer[] customers) { if (emailAddress == null) { return(null); } for(int i=0; i<customers.length; i++) { String custEmail = customers[i].getEmailAddress(); if (emailAddress.equalsIgnoreCase(custEmail)) { return(customers[i]); } } return(null); } } BookFlights.jsp, RentCars.jsp, FindHotels.jsp, EditAccounts.jsp, and IllegalRequest.jsp Pages used by the Travel servlet to do its presentation. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!-- Flight-finding page for travel example. Taken from Core Web Programming Java 2 Edition from Prentice Hall and Sun Microsystems Press, . May be freely used or adapted. --> <HTML> <HEAD> <TITLE>Best Available Flights</TITLE> <LINK REL=STYLESHEET HREF="/travel/travel-styles.css" TYPE="text/css"> </HEAD> <BODY> <H1>Best Available Flights</H1> <CENTER> <jsp:useBean id="customer" class="cwp.TravelCustomer" scope="session" /> Finding flights for <jsp:getProperty name="customer" property="fullName" /> <P> <jsp:getProperty name="customer" property="flights" /> <P><BR><HR><BR> <FORM ACTION="/servlet/BookFlight"> <jsp:getProperty name="customer" property="frequentFlyerTable" /> <P> <B>Credit Card:</B> <jsp:getProperty name="customer" property="creditCard" /> <P> <INPUT TYPE="SUBMIT" NAME="holdButton" VALUE="Hold for 24 Hrs"> <P> <INPUT TYPE="SUBMIT" NAME="bookItButton" VALUE="Book It!"> </FORM> </CENTER> </BODY> </HTML> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!-- Car rental page not implemented -- see airline booking page. Taken from Core Web Programming Java 2 Edition from Prentice Hall and Sun Microsystems Press, . May be freely used or adapted. --> <HTML> <HEAD> <TITLE>Not Implemented</TITLE> <LINK REL=STYLESHEET HREF="/travel/travel-styles.css" TYPE="text/css"> </HEAD> <BODY> <H1>Car Rental Page Not Implemented</H1> <CENTER> Hey, this is only an example. See the airline booking page. </CENTER> </BODY> </HTML> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!-- Hotel page not implemented -- see airline booking page. Taken from Core Web Programming Java 2 Edition from Prentice Hall and Sun Microsystems Press, . May be freely used or adapted. --> <HTML> <HEAD> <TITLE>Not Implemented</TITLE> <LINK REL=STYLESHEET HREF="/travel/travel-styles.css" TYPE="text/css"> </HEAD> <BODY> <H1>Hotel Page Not Implemented</H1> <CENTER> Hey, this is only an example. See the airline booking page. </CENTER> </BODY> </HTML> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!-- Account page not implemented -- see airline booking page. Taken from Core Web Programming Java 2 Edition from Prentice Hall and Sun Microsystems Press, . May be freely used or adapted. --> <HTML> <HEAD> <TITLE>Not Implemented</TITLE> <LINK REL=STYLESHEET HREF="/travel/travel-styles.css" TYPE="text/css"> </HEAD> <BODY> <H1>Accounts Page Not Implemented</H1> <CENTER> Hey, this is only an example. See the airline booking page. </CENTER> </BODY> </HTML> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!-- Illegal request at Travel Quick Search page. Taken from Core Web Programming Java 2 Edition from Prentice Hall and Sun Microsystems Press, . May be freely used or adapted. --> <HTML> <HEAD> <TITLE>Illegal Request</TITLE> <LINK REL=STYLESHEET HREF="/travel/travel-styles.css" TYPE="text/css"> </HEAD> <BODY> <H1>Illegal Request</H1> <CENTER>Please try again.</CENTER> </BODY> </HTML>