Y:/Code Backup/UDPserv/RFIDudpServer1Thread.java

Go to the documentation of this file.
00001 /******************************************************************************                      
00002  *
00003  *       Copyright (C) 2006 J Team, Inc.
00004  *       All Rights Reserved
00005  *
00006  * File Name      : RFIDudpServer1Thread.java
00007  * Project Name   : UDPserv
00008  * Description    : This code was adapted from SunMicrosystem's example code.  
00009  *                  Datagram packets recceived by this code are in the following
00010  *                  format: 
00011  * 
00012  *                  CMD:SERIALNUMBER
00013  *                  where CMD is:
00014  *                  U => Get User Data
00015  *                  I => Get Item Data, Add to Shopping Cart
00016  *                  R => Remove Item from Shopping Cart
00017  *                  M => End + E-Mail
00018  *                  
00019  * Authors: Jared Suttles
00020  *          Jennifer Tietz
00021  *          Jonathan Chen
00022  *          Joshua Chapman
00023  *
00024  * Version : 1.2
00025  * Date    : 05/01/06
00026  *
00027  *****************************************************************************/
00028 
00029 import java.io.*;
00030 import java.net.*;
00031 import java.text.DateFormat;
00032 import java.text.NumberFormat;
00033 import java.util.Date;
00034 import java.util.GregorianCalendar;
00035 import java.util.HashMap;
00036 import java.util.Locale;
00037 
00038 public class RFIDudpServer1Thread extends Thread {
00039 
00040     public boolean mailedFlag = true;
00041     protected DatagramSocket socket = null;
00042     protected BufferedReader in = null;
00043     protected HashMap ShoppingCart = null;
00044 
00045     public RFIDudpServer1Thread() throws IOException {
00046         this("RFIDudpServer1Thread");
00047     }
00048 
00049     public RFIDudpServer1Thread(String name) throws IOException {
00050         super(name);
00051         int i = 0;
00052         i = 2000;
00053         boolean flag = true;
00054         while (flag) {
00055           try
00056           {
00057             socket = new DatagramSocket(i);
00058             flag = false;
00059           } catch (SocketException e) {
00060                   System.out.println("Got an error on " + i);
00061           }
00062         }
00063         System.out.println("Got Socket " + i);
00064         ShoppingCart = new HashMap();
00065     
00066     }
00067 
00068     public void run() {
00069                 while (true) {
00070             try {
00071                 byte[] buf = new byte[14];
00072 
00073                 // receive request
00074                 DatagramPacket packet = new DatagramPacket(buf, buf.length);
00075                 socket.receive(packet);
00076               
00077                 // figure out response
00078                 String FileLine = null;
00079                 String GotString = new String(packet.getData());
00080                 System.out.println("GOT PACKET WITH: " + GotString + " As its data");
00081                 FileLine = getData(GotString);
00082                 buf = FileLine.getBytes();
00083 
00084                     // send the response to the client at "address" and "port"
00085                 InetAddress address = packet.getAddress();
00086                 int port = packet.getPort();
00087                 System.out.println("To port " + port);
00088                 packet = new DatagramPacket(buf, buf.length, address, port);
00089                 socket.send(packet);
00090             } catch (IOException e) {
00091                 e.printStackTrace();
00092             }
00093         }
00094     }
00095     // Right now it will just get the next line of the file and return it.. later,
00096     // it should find the corresponding Serial number.
00097     protected String getData(String FromPacket) {
00098         String[] CmdSerial = null;
00099         String[] LineArray = null;
00100           String returnValue = null;
00101         String checkSerial = null;
00102         String SerialCMP = null;
00103         char CMD = 'V';
00104         boolean found = false;
00105         
00106                 System.out.println("\nReceived Packet: "+FromPacket);
00107 
00108                 try {
00109                 
00110                 // This should open the file and then read a line from it.
00111                 in = new BufferedReader(new FileReader("RFIDXpr3ss.txt"));
00112         } catch (Exception e) {
00113             System.err.println("Could not open RFID Xpr3ss DB");
00114             System.exit(0);
00115         }
00116                 //Split the packet input string to CMD and Serial#
00117                 CmdSerial = FromPacket.split(":");
00118                 System.out.println("After Split: " + CmdSerial[0]+ " - " + CmdSerial[1]);
00119                 //Get the Serial number from the packet
00120                 SerialCMP = CmdSerial[1];
00121                 //Get the Command from the packet
00122                 CMD = CmdSerial[0].charAt(0);
00123                 
00124         
00125         
00126         try {
00127                 // Set the file pointer
00128                 if ((CMD == 'U') || (CMD == 'M')) {
00129                         while ((checkSerial = in.readLine()).compareTo("//USERS") != 0);
00130                 } else if ((CMD == 'I') || (CMD == 'R')) {
00131                         while ((checkSerial = in.readLine()).compareTo("//ITEMS") != 0);
00132                 } else if (CMD == 'T'){
00133                                 System.out.println("Received Time Synch Request");
00134                                 GregorianCalendar myDate = new GregorianCalendar();
00135                                 Date d = myDate.getTime();
00136                                 DateFormat df1 = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM);
00137                                 returnValue = df1.format(d);
00138                                 System.out.println("Returning: " + returnValue);
00139                         found = true;
00140                         }
00141 
00142                 while(found == false)
00143                 {
00144                         if ((checkSerial = in.readLine()) == null)
00145                         {
00146                                 returnValue = "~ERROR";
00147                             System.out.println("Invalid Serial Number");
00148                                 break;
00149                         } else if ((checkSerial.charAt(0) == '/') && (checkSerial.charAt(1) == '/')) {
00150                                 returnValue = "~ERROR";
00151                             System.out.println("Invalid Serial Number");
00152                                 break;                          
00153                         }
00154                         //System.out.println("FROM File GOT:" + checkSerial);
00155                         LineArray = checkSerial.split(",");
00156 
00157                         if (SerialCMP.compareTo(LineArray[0]) == 0)
00158                         {
00159                                 if (CMD == 'I'){
00160                                     returnValue = LineArray[1]+LineArray[2];
00161                                     System.out.println("Returning: " + returnValue);
00162                                 AddToCart(LineArray);
00163                                     found = true;
00164                                 }
00165                                 else if (CMD == 'R'){
00166                                     returnValue = "ACK";
00167                                     System.out.println("Returning: " + returnValue);
00168                                 RmFromCart(LineArray);
00169                                     found = true;
00170                                 }
00171                                 else if(CMD == 'U') {
00172                                         returnValue = LineArray[3]+LineArray[2]+LineArray[1];
00173                                         System.out.println("Returning User Info:" + returnValue);
00174                                         mailedFlag = false;
00175                                         found = true;
00176                                 }
00177                                 else if(CMD == 'M'){
00178                                         returnValue = "SENT";
00179                                         sendMail("smtp.purdue.edu", LineArray[2], LineArray[3]);
00180                                         System.out.println("Returning ACK:" + returnValue);
00181                                         found = true;
00182                                 }
00183                                 else {
00184                                     returnValue = "~ERROR";
00185                                     System.out.println("Returning ERR no packet");
00186                                     break;
00187                                 }
00188                         }
00189                 }
00190         } catch (IOException e) {
00191             returnValue = "IOException occurred in server.";
00192         }
00193         return returnValue;
00194     }
00195     
00196     public void Test() {
00197         String Items[] = {
00198                         "0413AADF243A,Toilet Paper 6pk         , 1630",
00199                         "0413AAC71B37,Hamburger                ,  129",
00200                         "0413AACDC145,Captain Crunch           ,  634",
00201                         "0413AAD7422B,Ritz Crackers            ,  315",
00202                         "0413AAC34F3A,The Fast and Furious DVD , 1570",
00203                         "0413AADB1132,Intro to Digital Systems ,34999"};
00204         String User = "041112BE8D2C,1464,jjchen@purdue.edu,Jonathan Chen";
00205         String temp = null;
00206         String LineArray[] = null;
00207         
00208         for (int Index = 0; Index < Items.length; Index++) {
00209                 temp = Items[Index];
00210                 LineArray = temp.split(",");
00211                 AddToCart(LineArray);
00212                 if (Index == 3) RmFromCart(LineArray);
00213         }
00214 
00215         LineArray = User.split(",");
00216         sendMail("smtp.purdue.edu", LineArray[2], LineArray[3]);
00217         
00218         return;
00219     }
00220     
00221     public void sendMail(String mailServer, String recipient, String username) {
00222         if (!mailedFlag) {
00223                 mailedFlag = true;
00224         try {
00225               Socket s = new Socket(mailServer, 587);
00226               BufferedReader in = new BufferedReader
00227                   (new InputStreamReader(s.getInputStream(), "8859_1"));
00228               BufferedWriter out = new BufferedWriter
00229                   (new OutputStreamWriter(s.getOutputStream(), "8859_1"));
00230 
00231               String messageBody = MakeReceiptBody(username);
00232               send(in, out, "EHLO rfidXpr3ss");
00233               // warning : some mail server validate the sender address
00234               //           in the MAIL FROm command, put your real address here
00235               send(in, out, "AUTH LOGIN");
00236               send(in, out, "anN1dHRsZXM=");
00237               send(in, out, "amp0dXR0bGVzMTIxNw==");
00238               send(in, out, "MAIL FROM: <rfid_Xpr3ss@purdue.edu>");
00239               send(in, out, "RCPT TO: " + recipient);
00240               send(in, out, "DATA");
00241               send(out, "Subject: Receipt of Purchase");
00242               send(out, "From: rfid Xpr3ss <rfid_Xpr3ss@purdue.edu>");
00243               send(out, "\n");
00244               // message body
00245               send(out, messageBody);
00246               //send(out, "Thanks for your purchase\n");
00247               //send(out, "Hey, look it works!");
00248               send(out, "\n.\n");
00249               send(in, out, "QUIT");
00250               s.close();
00251               ShoppingCart = new HashMap();
00252 
00253               }
00254            catch (Exception e) {
00255               e.printStackTrace();
00256               }
00257         }
00258      }
00259 
00260          private String MakeReceiptBody(String username) {
00261                  String messageBody = "";
00262                  String myuser;
00263                  float Total = 0;
00264                  ItemStruct temp;
00265                  int i = 19;
00266                  
00267                  // Get time and date for email
00268                  GregorianCalendar myDate = new GregorianCalendar();
00269                  Date d = myDate.getTime();
00270                  DateFormat df1 = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
00271                  String s1 = df1.format(d);
00272                  messageBody += s1 + "\n\n";
00273                  
00274                  while (username.charAt(i) == ' ') i--;
00275                  myuser = username.substring(0,i+1);
00276                  // Get user name
00277                  messageBody += myuser + ",\n\nPlease find your receipt below, courtesy of RFID Xpr3ss.\n\n\n";
00278                  
00279                  // Initialize message body
00280                  messageBody += "ITEM                           PRICE\n------                       -------\n";
00281                  
00282                  // Get array of keys from hash map
00283                  Object keys[] = ShoppingCart.keySet().toArray();
00284                  
00285                  for (int Index = 0; Index < keys.length; Index++) {
00286                          // Get current item from hash map
00287                          temp = (ItemStruct) ShoppingCart.get((String)keys[Index]);
00288                          
00289                          // Add item and price to message body
00290                          messageBody += temp.Name + "    " + GetCurrencyString(temp.Price,7) + "\n";
00291                          
00292                          // Add item price to total
00293                          Total += temp.Price;
00294                  }
00295                  // Append Total
00296                  messageBody += "                             -------\n" +
00297                                         "                    TOTAL:  " + GetCurrencyString(Total,8) + "\n";
00298                  
00299                  // Conclude message body
00300                  messageBody += "\nThank you for using RFID Xpr3ss!\n";
00301                  
00302                  return messageBody;
00303          }
00304 
00305 
00306                 private String GetCurrencyString(float total, int fieldwidth) {
00307                         Locale locale = Locale.US;
00308                         String currency = NumberFormat.getCurrencyInstance(locale).format(total);
00309                         while(currency.length() < fieldwidth){
00310                                 currency = currency.substring(0,1)+" "+currency.substring(1);
00311                         }
00312                         return currency;
00313         }
00314 
00315                 public void send(BufferedReader in, BufferedWriter out, String s) {
00316            try {
00317               out.write(s + "\n");
00318               out.flush();
00319               System.out.println(s);
00320               s = in.readLine();
00321               //System.out.println(s);
00322               }
00323            catch (Exception e) {
00324               e.printStackTrace();
00325               }
00326            }
00327 
00328          public void send(BufferedWriter out, String s) {
00329            try {
00330               out.write(s + "\n");
00331               out.flush();
00332               System.out.println(s);
00333               }
00334            catch (Exception e) {
00335               e.printStackTrace();
00336               }
00337            }
00338          
00339          private void AddToCart(String LineArray[]) {
00340              ItemStruct temp = new ItemStruct(LineArray[1],getFloatVal(LineArray[2]));
00341              ShoppingCart.put(LineArray[0],temp);             
00342          }
00343 
00344          private void RmFromCart(String LineArray[]) {
00345              ShoppingCart.remove(LineArray[0]);
00346          }
00347 
00348          private float getFloatVal(String str) {
00349              float val = 0;
00350              for (int strIndex = str.length()-1; strIndex >= 0; strIndex--) {
00351                  if (str.charAt(strIndex) <= '9' && str.charAt(strIndex) >= '0') {
00352                      val += (str.charAt(strIndex) - '0') * Math.pow(10,(str.length()-strIndex-3));
00353                  }
00354              }
00355              return val;
00356          } 
00357 }

Generated on Sun Apr 30 18:42:49 2006 for UDPserver by  doxygen 1.4.6-NO