Chris Pollett >
Old Classes
> |
HW2 Solutions Page//EmailServlet.java -- a servlet to store student e-mails in grades file import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; /** EmailServlet is a simple servlet that allows students to store their emails in the tabbed Excel file a professor might use for a class (right now hard-coded as CS100). The format of this file is spelled-out in the HW description. @author Chris Pollett */ public class EmailServlet extends HttpServlet { /** This method is called when the servlet is initially loaded into the server. Since we retain our Servlet fields until the server releases us, we only need to read in the data file and set up our look up table here. */ public void init(ServletConfig conf) throws ServletException { super.init(conf); dataFile = conf.getServletContext().getRealPath(""); dataFile += "/WEB-INF/classes/CS100.txt"; courseData = new Vector(); lookupRow = new Hashtable(); readDataFile(); } /** This method is called whenever a request of our servlet is made. It spits out the header and footer HTML and calls the appropriate subfunction to handle the request. @param request - data on this request @param response - data on where to reply to @throws IOException, ServletException */ public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); out = response.getWriter(); out.println("<html>"); out.println("<head><title>CS100 Email Collector</title></head>"); out.println("<body bgcolor=\"#EEEEEE\">"); out.println("<center><h3>CS100 Email Collector</h3>"); String studentID = request.getParameter("studentID"); String email = request.getParameter("email"); if(studentID == null || email == null) contactPage(); else if(validID(studentID)) submitPage(studentID, email); else invalidIDPage(); out.println("<center></body></html>"); } /** This method is called when the servlet is relased by the Server. Just to be on the safe side we rewrite out all the data to the data file again. */ public void destroy() { writeDataFile(); super.destroy(); } /* If no data was sent to the servlet then we output the HTML below. */ private void contactPage() { out.print("<p>Please enter your student ID "); out.println("with dashes (i.e., XXX-XX-XXXX):</p>"); out.println("<form method=\"GET\" action=\"EmailServlet\">"); out.print("<p><input type=\"text\" name=\"studentID\""); out.println(" size=\"11\" maxlength=\"11\" ></p>"); out.println("<p>Then enter your e-mail address:</p>"); out.print("<p><input type=\"text\" name=\"email\""); out.println(" size=\"11\" maxlength=\"40\" ></p>"); out.println("<p><input type=\"submit\" ></p>"); out.println("</form>"); } /* Updates the given students e-mail address, writes out the updated data file to disk (so that it is immediately available to the professor), spits out acknowledgement of update HTML. @param studentID - a student ID in the data file @param email - the email address for this student. */ private void submitPage(String studentID, String email) { int rowNum = ((Integer) lookupRow.get("\""+studentID+"\"") ).intValue(); String line = (String)courseData.get(rowNum); StringTokenizer fields = new StringTokenizer(line,"\t"); int cnt=0; String outLine=""; while(fields.hasMoreTokens()) { String field = fields.nextToken(); if(cnt == emailColumn) outLine += "\""+email+"\"\t"; else outLine += field+"\t"; cnt++; } courseData.set(rowNum, outLine); writeDataFile(); out.println("<p>Your e-mail has been updated. Have a nice day!</p>"); } /* Checks if the given studentID is in our data file. @return true - if studentID was in data file */ private boolean validID(String studentID) { return (lookupRow.get("\""+studentID+"\"") == null) ? false : true; } /* HTML that is output if the studentID sent was not in the data file */ private void invalidIDPage() { out.println("<p>Invalid ID. Please contact the professor.</p>"); } /* Reads the data file into a Vector. Also puts into a HashTable pairs of the form (studentID, rowNumber) where rowNumber is the row in the Vector that one can find the given studentID. */ private void readDataFile() { try { String line; BufferedReader buf = new BufferedReader( new FileReader(dataFile)); //Get file meta data studentIDColumn = -1; emailColumn = -1; line= buf.readLine(); courseData.add(line); setStudentIDEmailColumns(line); //Now read in rest of file while((line=buf.readLine())!=null) { courseData.add(line); StringTokenizer lineFields = new StringTokenizer(line,"\t"); String field=""; for(int i=0; i <= studentIDColumn; i++) field = lineFields.nextToken(); lookupRow.put(field, new Integer(courseData.size()-1)); } buf.close(); } catch(IOException e) { System.err.println(e.toString()); } catch(Exception e) { System.err.println("ID or Email column missing"); } } /* Given the meta line for the data file this computes which column has the the studentID data. and which column has the email data. These two items are stored in the global variables emailColumn and studentIDColumn @param metaLine - meta data line for file */ private void setStudentIDEmailColumns(String metaLine) throws Exception { StringTokenizer meta = new StringTokenizer(metaLine,"\t"); int cnt = 0; while(meta.hasMoreTokens()) { String field = meta.nextToken(); if(field.equals("\"EMAIL\"")) emailColumn = cnt; if(field.equals("\"StudentID\"")) studentIDColumn = cnt; cnt++; } if( studentIDColumn < 0 || emailColumn <0) throw new Exception(); } /* Used to write out the file back to disk after an e-mail has been updated */ private void writeDataFile() { try { PrintWriter outFile = new PrintWriter( new BufferedWriter( new FileWriter(dataFile))); Iterator data = courseData.iterator(); while(data.hasNext()) { outFile.println((String)data.next()); } outFile.close(); } catch(IOException e) { System.err.println(e.toString()); } } private String dataFile; //String path to file CS100.txt private Vector courseData; // stores all the rows of data file Hashtable lookupRow; // used to look up a row by its studentID private int studentIDColumn; //column of row which has studentID private int emailColumn; //column of row which has email private PrintWriter out; //writes to browser } |