start of new file
[IRC.git] / Robust / src / Benchmarks / WebServerJ / WebServerThread.java
1 import java.io.*;
2 import java.net.*;
3
4 public class WebServerThread extends Thread {
5     //Filename requested by the client 
6     String filename;
7     String[] parsed; 
8     String prefix;
9     Logger log;
10     Inventory inventorylist;
11     Socket sock;
12     InputStream sockin;
13     OutputStream sockout;
14
15     //Constructor
16     public WebServerThread(Socket s, Logger log, Inventory inventory){
17         parsed = new String[4];
18         this.log=log;
19         this.sock=s;
20         try {
21             sockin=s.getInputStream();
22             sockout=s.getOutputStream();
23         } catch (Exception e) {
24             e.printStackTrace();
25         }
26         this.inventorylist=inventory;
27     }
28     
29     public void run() {
30         // Process the incoming http request 
31         while (!clientrequest()) {
32         }
33         if(checktrans()==false) {
34             // Not special transaction , do normal filesending  
35             SendFile();
36             LogRequest();
37         } else {
38             // Invoke special inventory transaction
39             Transaction();
40             LogRequest();
41         }
42     }
43     
44     //Do the WriteIO on server socket and send the requested file to Client
45     public void SendFile() {
46         sendfile();
47         try {
48             sock.close();
49         } catch (Exception e) {
50             e.printStackTrace();
51         }
52     }
53
54     // Log the Client request
55     public void LogRequest() {
56         log.logrequest(filename);
57     }
58     
59     //Transaction on Inventory
60     public void Transaction() {
61         // Parse
62         int op = parseTransaction();
63         // Check for the kind of operation
64         if (op == 0 ) { /* Add */
65             //          System.printString("DEBUG > Calling add transaction\n");
66             Integer qty = new Integer(parsed[2]);
67             Integer price = new Integer(parsed[3]);
68             inventorylist.additem(parsed[1], qty.intValue(), price.intValue());
69             httpresponse();
70             StringBuffer s = new StringBuffer("Added Item ");
71             s.append(parsed[1]);
72             s.append(" Quantity ");
73             s.append(parsed[2]);
74             s.append(" Price ");
75             s.append(parsed[3]);
76             s.append("\n");
77             String towrite = new String(s);
78             try {
79                 sockout.write(towrite.getBytes());
80             } catch (Exception e) {
81                 e.printStackTrace();
82             }
83         } else if (op == 1) { /* Buy */
84             //          System.printString("DEBUG > Calling buy transaction\n");
85             Integer qty = new Integer(parsed[2]);
86             int ret = inventorylist.buyitem(parsed[1], qty.intValue());
87             if (ret >= 0) {
88                 httpresponse();
89                 StringBuffer s = new StringBuffer("Bought item ");
90                 s.append(parsed[1]);
91                 s.append(" Quantity ");
92                 s.append(parsed[2]);
93                 s.append(" Cost ");
94                 Integer cost = new Integer(ret*qty.intValue());
95                 String c = cost.toString();
96                 s.append(c);
97                 String towrite = new String(s);
98                 try {
99                     sockout.write(towrite.getBytes());
100                 } catch (Exception e) {
101                     e.printStackTrace();
102                 }
103             } else {
104                 httpresponse();
105                 String s = new String("Error encountered");
106                 try {
107                     sockout.write(s.getBytes());
108                 } catch (Exception e) {
109                     e.printStackTrace();
110                 }
111             }
112         } else if (op == 2) { /* Inventory */
113             //          System.printString("DEBUG > Calling inventory transaction\n");
114             httpresponse();
115             inventorylist.inventory(sock);      
116         } else { /* Error */ 
117             //          System.printString("T > Error - Unknown transaction\n");
118         }
119         //Invoke close operations
120         try {
121             sock.close();
122         } catch (Exception e) {e.printStackTrace();}
123     }
124
125     
126     //Send the http header for web browser display      
127     public void httpresponse(){
128         StringBuffer header = new StringBuffer("HTTP/1.0 200 OK\n");
129         header.append("Content-type: text/html\n");
130         header.append("\n\n");
131         String temp_str = new String(header);
132         try {
133             sockout.write(temp_str.getBytes());
134         } catch (Exception e) {
135             e.printStackTrace();
136         }
137         return;
138         
139     }
140     
141     // Send the html file , read from file one byte at a time   
142     public void sendfile() {
143         StringBuffer req_file = new StringBuffer("./htmlfiles/");
144         req_file.append(filename);
145         String filepath = new String(req_file);
146         FileInputStream def_file = null;
147         try {
148             def_file=new FileInputStream(filepath);
149         } catch (FileNotFoundException e) {
150         } 
151         //      int status = def_file.getfd();//Checks if the file is present in 
152         //current directory     
153         httpresponse();
154         if (def_file == null){
155             StringBuffer response = new StringBuffer("404: not found: ");//Send 404 error if
156             // file not found
157             response.append(filename);
158             String buffer = new String(response);
159             try {
160                 sockout.write(buffer.getBytes());
161             } catch (Exception e) {
162                 e.printStackTrace();
163             }
164             try {
165                 def_file.close();
166             } catch (Exception e) {
167                 e.printStackTrace();
168             }
169             return;
170             }
171         byte buf[] = new byte[16];
172         int ret;
173         
174         try {
175         while ((ret = def_file.read(buf)) > 0) {// Read from file and write 
176             // one byte at a time into the socket 
177             byte tosend[] = new byte[ret];
178             for (int i = 0; i < ret; i++) {
179                 tosend[i] = buf[i];
180             }
181             sockout.write(tosend);
182             //String str = new String(tosend);
183         }
184         def_file.close();
185         } catch (Exception e) {
186             e.printStackTrace();
187         }
188     }
189     
190     //Read the client request and extract the filename from it  
191     public boolean clientrequest(){
192         byte b1[] = new byte[1024];
193         int numbytes=0;
194         try {
195             numbytes=sockin.read(b1);//Read client request from web server socket
196         } catch (Exception e) {
197             e.printStackTrace();
198         }
199         String curr=(new String(b1)).substring(0, numbytes);
200         if (prefix!=null) {
201             StringBuffer sb=new StringBuffer(prefix);
202             sb.append(curr);
203             curr=sb.toString();
204         }
205         prefix=curr;
206         if(prefix.indexOf("\r\n\r\n")>=0) {
207             
208             int index = prefix.indexOf('/');//Parse the GET client request to find filename
209             int end = prefix.indexOf('H');
210             filename = prefix.substring((index+1), (end-1));
211             //      System.printString("\n");
212             return true;
213         }
214         return false;
215     }
216     
217     // Parse  for the prefix in the client request
218     // This is helpful to find if the prefix is a special transaction
219     public boolean checktrans(){
220         if (filename.startsWith("trans") == true) {
221             return true;
222         } else {
223             return false;
224         }
225     }
226     
227     //Parse for the substrings in the filename and use it to obtain the
228     //kind of operation, name of item, quantity of item, price of item
229     //e.g. trans_add_car_2_10000 is the filename
230     //store in the parsed[] string , add,car,2,1000
231     public int parseTransaction(){
232         int start = filename.indexOf('_');
233         String s = filename.substring(start+1);
234         
235         if (s.startsWith("add")==true){
236             //          System.printString("DEBUG > ADD\n");
237             int i1 = s.indexOf('_');
238             parsed[0] = new String(s.substring(0,i1));
239             
240             int i2 = s.indexOf('_',i1+1);
241             parsed[1] = new String(s.substring(i1+1,i2));
242             
243             int i3 = s.indexOf('_',i2+1);
244             parsed[2] = new String(s.substring(i2+1,i3));
245             
246             String s3 = s.substring(i3+1);
247             parsed[3] = s3;
248             
249             return 0;
250             
251         }
252         if (s.startsWith("buy")==true){
253             //          System.printString("DEBUG > BUY\n");
254             int i1 = s.indexOf('_');
255             parsed[0] = s.substring(0,i1);
256             
257             int i2 = s.indexOf('_', i1+1);
258             parsed[1] = s.substring(i1+1,i2);
259             
260             String s2 = s.substring(i2+1);
261             parsed[2] = s2;
262             
263             parsed[3] = "";
264             
265             return 1;
266         }
267         if (s.startsWith("inventory")==true){
268             //          System.printString("DEBUG > INVENTORY\n");
269             return 2;
270             
271         }
272         // Error transaction
273         return -1;
274     }
275 }