KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > example > Magic8BallRequest


1 package example;
2
3 import com.caucho.util.L10N;
4 import java.util.logging.Logger JavaDoc;
5 import java.util.logging.Level JavaDoc;
6
7 import com.caucho.vfs.*;
8 import com.caucho.server.port.ServerRequest;
9 import com.caucho.server.connection.Connection;
10 import java.io.IOException JavaDoc;
11
12 /**
13  * Protocol specific information for each request. An instance of this
14  * object may be reused to reduce memory allocations.
15  */

16 public class Magic8BallRequest implements ServerRequest {
17   static protected final Logger JavaDoc log =
18     Logger.getLogger(Magic8BallRequest.class.getName());
19   static final L10N L = new L10N(Magic8BallRequest.class);
20
21   Connection _conn;
22   Magic8BallProtocol _protocol;
23
24
25   // the parser is reset for each request
26
Parser _parser = new Parser();
27
28   Magic8Ball _magic8ball = new Magic8Ball();
29
30   /**
31    *
32    */

33   public Magic8BallRequest(Magic8BallProtocol protocol, Connection conn)
34   {
35     _protocol = protocol;
36     _conn = conn;
37   }
38
39   /**
40    * Initialize the connection. At this point, the current thread is the
41    * connection thread.
42    */

43   public void init()
44   {
45   }
46
47   /**
48    * Handle a new connection. The controlling Server may call
49    * handleRequest again after the connection completes, so the
50    * implementation must initialize any variables for each connection.
51    */

52   public boolean handleRequest() throws IOException JavaDoc
53   {
54     ReadStream readStream = _conn.getReadStream();
55     WriteStream writeStream = _conn.getWriteStream();
56
57     try {
58       _parser.init(readStream);
59
60
61       AbstractCommand cmd = null;
62       do {
63         String JavaDoc result = null;
64         String JavaDoc error = null;
65
66         cmd = _parser.nextCommand();
67         if (_parser.isError()) {
68           error = _parser.getError();
69         }
70         else if (cmd != null) {
71           result = cmd.act(_magic8ball);
72           if (cmd.isError())
73             error = cmd.getError();
74         }
75
76         if (error != null) {
77           writeStream.print("ERROR: ");
78           writeStream.println(_parser.getError());
79           break;
80         }
81         else if (result != null) {
82           writeStream.print("RESULT: ");
83           writeStream.println(result);
84         }
85       } while (cmd != null);
86     } catch (Throwable JavaDoc e) {
87       log.log(Level.WARNING, e.toString(), e);
88     }
89
90     return false;
91   }
92 }
93
94
Popular Tags