KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > edu > rice > rubis > beans > MDB_BuyNow


1 package edu.rice.rubis.beans;
2
3 import java.rmi.RemoteException JavaDoc;
4 import javax.ejb.MessageDrivenBean JavaDoc;
5 import javax.ejb.MessageDrivenContext JavaDoc;
6 import javax.ejb.EJBException JavaDoc;
7 import javax.jms.*;
8 import javax.naming.Context JavaDoc;
9 import javax.naming.InitialContext JavaDoc;
10 import javax.rmi.PortableRemoteObject JavaDoc;
11 import javax.sql.DataSource JavaDoc;
12 import java.sql.Connection JavaDoc;
13 import java.sql.PreparedStatement JavaDoc;
14 import java.sql.ResultSet JavaDoc;
15 import java.sql.SQLException JavaDoc;
16 import java.io.Serializable JavaDoc;
17
18 /**
19  * This is a stateless session bean used to build the html form to buy an item.
20  *
21  * @author <a HREF="mailto:cecchet@rice.edu">Emmanuel Cecchet</a> and <a HREF="mailto:julie.marguerite@inrialpes.fr">Julie Marguerite</a>
22  * @version 1.1
23  */

24
25 public class MDB_BuyNow implements MessageDrivenBean JavaDoc, MessageListener
26 {
27   private DataSource JavaDoc dataSource;
28   private MessageDrivenContext JavaDoc messageDrivenContext;
29   private TopicConnectionFactory connectionFactory;
30   private TopicConnection connection;
31   private Topic topic;
32   private TopicSession session;
33   private TopicPublisher replier;
34   private Context JavaDoc initialContext = null;
35
36
37   public MDB_BuyNow()
38   {
39
40   }
41
42   public void onMessage(Message message)
43   {
44     try
45     {
46       MapMessage request = (MapMessage)message;
47       String JavaDoc correlationID = request.getJMSCorrelationID();
48       int itemId = request.getInt("itemId");
49       String JavaDoc username = request.getString("username");
50       String JavaDoc password = request.getString("password");
51
52         // Retrieve the connection factory
53
connectionFactory = (TopicConnectionFactory) initialContext.lookup(BeanConfig.TopicConnectionFactoryName);
54
55       // get the post comment form
56
String JavaDoc html = getBuyNowForm(itemId, username, password);
57
58       // send the reply
59
TemporaryTopic temporaryTopic = (TemporaryTopic) request.getJMSReplyTo();
60       if (temporaryTopic != null)
61       {
62         // create a connection
63
connection = connectionFactory.createTopicConnection();
64         // create a session: no transaction, auto ack
65
session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
66         TextMessage reply = session.createTextMessage();
67         reply.setJMSCorrelationID(correlationID);
68         reply.setText(html);
69         replier = session.createPublisher(null); // unidentified publisher
70
connection.start();
71         replier.publish(temporaryTopic, reply);
72         replier.close();
73         session.close();
74         connection.stop();
75         connection.close();
76       }
77     }
78     catch (Exception JavaDoc e)
79     {
80       throw new EJBException JavaDoc("Message traitment failed for MDB_BuyNow: " +e);
81     }
82   }
83
84   /**
85    * Authenticate the user and get the information to build the html form.
86    *
87    * @return a string in html format
88    * @since 1.1
89    */

90   public String JavaDoc getBuyNowForm(int itemId, String JavaDoc username, String JavaDoc password) throws RemoteException JavaDoc
91   {
92     int userId = -1;
93     StringBuffer JavaDoc html = new StringBuffer JavaDoc();
94     PreparedStatement JavaDoc stmt = null;
95     ResultSet JavaDoc rs = null;
96     Connection JavaDoc conn = null;
97
98     // Authenticate the user who want to buy
99
if ((username != null && !username.equals("")) || (password != null && !password.equals("")))
100       {
101         TopicConnection authConnection;
102         TopicSession authSession;
103         Topic authTopic;
104         try
105         {
106           // create a connection
107
authConnection = connectionFactory.createTopicConnection();
108           // lookup the destination
109
authTopic = (Topic) initialContext.lookup(BeanConfig.PrefixTopicName+"topicAuth");
110           // create a session
111
authSession = authConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); // no transaction and auto ack
112
}
113         catch (Exception JavaDoc e)
114         {
115           throw new EJBException JavaDoc("Cannot connect to message bean MDB_Auth : " +e+"<br>");
116         }
117         try
118         {
119           // create a requestor to receive the reply
120
TopicRequestor requestor = new TopicRequestor(authSession, authTopic);
121           // create a message
122
MapMessage m = authSession.createMapMessage();
123           // set parameters
124
m.setStringProperty("nickname", username);
125           m.setStringProperty("password", password);
126           m.setJMSCorrelationID("auth");
127           // send the message and receive the reply
128
authConnection.start(); // allows message to be delivered (default is connection stopped)
129
MapMessage authReply = (MapMessage)requestor.request(m);
130           authConnection.stop();
131           // read the reply
132
userId = authReply.getInt("userId");
133           // close connection and session
134
requestor.close(); // also close the session
135
authConnection.close();
136         }
137         catch (Exception JavaDoc e)
138         {
139           throw new EJBException JavaDoc("user authentication failed: " +e+"<br>");
140         }
141         if (userId == -1)
142         {
143            html.append("You don't have an account on RUBiS!<br>You have to register first.<br>");
144            return html.toString();
145         }
146       }
147     // Try to find the Item corresponding to the Item ID
148
String JavaDoc itemName = null, description = null;
149     String JavaDoc startDate = null, endDate = null, sellerName = null;
150     int quantity = 0, sellerId = -1;
151     float buyNow = 0;
152     try
153     {
154       conn = dataSource.getConnection();
155       stmt = conn.prepareStatement("SELECT * FROM items WHERE id=?");
156       stmt.setInt(1, itemId);
157       rs = stmt.executeQuery();
158       if (rs.first())
159       {
160         itemName = rs.getString("name");
161         description = rs.getString("description");
162         startDate = rs.getString("start_date");
163         endDate = rs.getString("end_date");
164         buyNow = rs.getFloat("buy_now");
165         quantity = rs.getInt("quantity");
166         sellerId = rs.getInt("seller");
167       }
168       stmt.close();
169     }
170     catch (Exception JavaDoc e)
171     {
172       try
173       {
174         if (stmt != null) stmt.close();
175         if (conn != null) conn.close();
176       }
177       catch (Exception JavaDoc ignore)
178       {
179       }
180       throw new RemoteException JavaDoc("Failed to execute Query for item: " +e);
181     }
182
183     try
184     {
185       stmt = conn.prepareStatement("SELECT nickname FROM users WHERE id=?");
186       stmt.setInt(1, sellerId);
187       ResultSet JavaDoc srs = stmt.executeQuery();
188       if (srs.first())
189       {
190         sellerName = srs.getString("nickname");
191       }
192       stmt.close();
193       conn.close();
194     }
195     catch (SQLException JavaDoc s)
196     {
197       try
198       {
199         if (stmt != null) stmt.close();
200         if (conn != null) conn.close();
201       }
202       catch (Exception JavaDoc ignore)
203       {
204       }
205       throw new RemoteException JavaDoc("Failed to execute Query for seller: " +s);
206     }
207
208     // Display the form for buying the item
209
html.append("<TABLE width=\"100%\" bgcolor=\"#CCCCFF\">\n<TR><TD align=\"center\" width=\"100%\"><FONT size=\"4\" color=\"#000000\"><B>You are ready to buy this item: "+itemName+"</B></FONT></TD></TR>\n</TABLE><p>\n");
210     try
211     {
212       html.append(printItemDescriptionToBuyNow(itemId, itemName, description, buyNow, quantity, sellerId, sellerName, startDate, endDate, userId));
213     }
214     catch (Exception JavaDoc e)
215     {
216       throw new RemoteException JavaDoc("Unable to print Item description: " +e);
217     }
218
219     return html.toString();
220   }
221  
222   /**
223    * Display item information for the Buy Now servlet
224    *
225    * @return a <code>String</code> containing HTML code
226    * @exception RemoteException if an error occurs
227    * @since 1.0
228    */

229   public String JavaDoc printItemDescriptionToBuyNow(int itemId, String JavaDoc itemName, String JavaDoc description, float buyNow, int quantity, int sellerId, String JavaDoc sellerName, String JavaDoc startDate, String JavaDoc endDate, int userId) throws RemoteException JavaDoc
230   {
231     StringBuffer JavaDoc result = new StringBuffer JavaDoc("<TABLE>\n"+"<TR><TD>Quantity<TD><b><BIG>"+quantity+"</BIG></b>\n");
232     result.append("<TR><TD>Seller<TD><a HREF=\""+BeanConfig.context+"/servlet/edu.rice.rubis.beans.servlets.ViewUserInfo?userId="+sellerId+"\">"+
233                   sellerName+"</a> (<a HREF=\""+BeanConfig.context+"/servlet/edu.rice.rubis.beans.servlets.PutCommentAuth?to="+sellerId+"&itemId="+itemId+"\">Leave a comment on this user</a>)\n"+
234                   "<TR><TD>Started<TD>"+startDate+"\n"+"<TR><TD>Ends<TD>"+endDate+"\n"+
235                   "</TABLE>"+
236                   "<TABLE width=\"100%\" bgcolor=\"#CCCCFF\">\n"+
237                   "<TR><TD align=\"center\" width=\"100%\"><FONT size=\"4\" color=\"#000000\"><B>Item description</B></FONT></TD></TR>\n"+
238                   "</TABLE><p>\n"+description+"<br><p>\n"+
239                   "<TABLE width=\"100%\" bgcolor=\"#CCCCFF\">\n"+
240                   "<TR><TD align=\"center\" width=\"100%\"><FONT size=\"4\" color=\"#000000\"><B>Buy Now</B></FONT></TD></TR>\n"+
241                   "</TABLE><p>\n"+
242                   "<form action=\""+BeanConfig.context+"/servlet/edu.rice.rubis.beans.servlets.StoreBuyNow\" method=POST>\n"+
243                   "<input type=hidden name=userId value="+userId+">\n"+
244                   "<input type=hidden name=itemId value="+itemId+">\n"+
245                   "<input type=hidden name=maxQty value="+quantity+">\n");
246     if (quantity > 1)
247       result.append("<center><table><tr><td>Quantity:</td>\n"+
248                     "<td><input type=text size=5 name=qty></td></tr></table></center>\n");
249     else
250       result.append("<input type=hidden name=qty value=1>\n");
251     result.append("<p><input type=submit value=\"Buy now!\"></center><p>\n");
252     return result.toString();
253   }
254                   
255   // ======================== EJB related methods ============================
256

257   /**
258    * Set the associated context. The container call this method
259    * after the instance creation.
260    * The enterprise Bean instance should store the reference to the context
261    * object in an instance variable.
262    * This method is called with no transaction context.
263    *
264    * @param MessageDrivenContext A MessageDrivenContext interface for the instance.
265    * @throws EJBException Thrown by the method to indicate a failure caused by
266    * a system-level error.
267    */

268   public void setMessageDrivenContext(MessageDrivenContext JavaDoc ctx)
269   {
270     messageDrivenContext = ctx;
271     if (dataSource == null)
272     {
273       // Finds DataSource from JNDI
274
try
275       {
276         initialContext = new InitialContext JavaDoc();
277         dataSource = (DataSource JavaDoc)initialContext.lookup("java:comp/env/jdbc/rubis");
278       }
279       catch (Exception JavaDoc e)
280       {
281         throw new EJBException JavaDoc("Cannot get JNDI InitialContext");
282       }
283     }
284   }
285
286   /**
287    * The Message driven bean must define an ejbCreate methods with no args.
288    *
289    */

290   public void ejbCreate()
291   {
292
293   }
294  
295   /**
296    * A container invokes this method before it ends the life of the message-driven object.
297    * This happens when a container decides to terminate the message-driven object.
298    *
299    * This method is called with no transaction context.
300    *
301    * @throws EJBException Thrown by the method to indicate a failure caused by
302    * a system-level error.
303    */

304   public void ejbRemove() {}
305
306
307
308 }
309
Popular Tags