KickJava   Java API By Example, From Geeks To Geeks.

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


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 import javax.transaction.UserTransaction JavaDoc;
18 import java.net.URLEncoder JavaDoc;
19
20 /**
21  * This is a stateless session bean used to get the information about an item.
22  *
23  * @author <a HREF="mailto:cecchet@rice.edu">Emmanuel Cecchet</a> and <a HREF="mailto:julie.marguerite@inrialpes.fr">Julie Marguerite</a>
24  * @version 1.1
25  */

26
27 public class MDB_ViewItem implements MessageDrivenBean JavaDoc, MessageListener
28 {
29   private DataSource JavaDoc dataSource;
30   private MessageDrivenContext JavaDoc messageDrivenContext;
31   private TopicConnectionFactory connectionFactory;
32   private TopicConnection connection;
33   private Topic topic;
34   private TopicSession session;
35   private TopicPublisher replier;
36   private Context JavaDoc initialContext = null;
37
38
39   public MDB_ViewItem()
40   {
41
42   }
43
44   public void onMessage(Message message)
45   {
46     try
47     {
48       MapMessage request = (MapMessage)message;
49       String JavaDoc correlationID = request.getJMSCorrelationID();
50       int itemId = request.getInt("itemId");
51       int userId = request.getInt("userId");
52         // Retrieve the connection factory
53
connectionFactory = (TopicConnectionFactory) initialContext.lookup(BeanConfig.TopicConnectionFactoryName);
54
55       // get the item description
56
String JavaDoc html = getItemDescription(itemId, userId);
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_ViewItem: " +e);
81     }
82   }
83
84   /**
85    * Get the full description of an item and the bidding option if userId>0.
86    *
87    * @param item an <code>Item</code> value
88    * @param userId an authenticated user id
89    */

90   public String JavaDoc getItemDescription(int itemId, int userId) throws RemoteException JavaDoc
91   {
92     StringBuffer JavaDoc html = new StringBuffer JavaDoc();
93     Connection JavaDoc conn = null;
94     PreparedStatement JavaDoc stmt = null;
95     ResultSet JavaDoc rs = null;
96
97     String JavaDoc itemName=null, endDate=null, startDate=null, description=null, sellerName=null;
98     float maxBid=0, initialPrice=0, buyNow=0, reservePrice=0;
99     int qty=0, sellerId=-1, nbOfBids=0;
100     String JavaDoc firstBid=null;
101
102     try
103     {
104       conn = dataSource.getConnection();
105       conn.setAutoCommit(false);
106       stmt = conn.prepareStatement("SELECT * FROM items WHERE id=?");
107       stmt.setInt(1, itemId);
108       rs = stmt.executeQuery();
109     }
110     catch (SQLException JavaDoc e)
111     {
112       try
113       {
114         if (stmt != null) stmt.close();
115         if (conn != null) conn.close();
116       }
117       catch (Exception JavaDoc ignore)
118       {
119       }
120       throw new RemoteException JavaDoc("Failed to get the item: " +e);
121     }
122     try
123     {
124       if (!rs.first())
125       {
126         stmt = conn.prepareStatement("SELECT * FROM old_items WHERE id=?");
127         stmt.setInt(1, itemId);
128         rs = stmt.executeQuery();
129       }
130     }
131     catch (SQLException JavaDoc e)
132     {
133       try
134       {
135         if (stmt != null) stmt.close();
136         if (conn != null) conn.close();
137       }
138       catch (Exception JavaDoc ignore)
139       {
140       }
141       throw new RemoteException JavaDoc("Failed to get the item from old items: " +e);
142     }
143     try
144     {
145       if (rs.first())
146       {
147         itemName = rs.getString("name");
148         description = rs.getString("description");
149         endDate = rs.getString("end_date");
150         startDate = rs.getString("start_date");
151         initialPrice = rs.getFloat("initial_price");
152         reservePrice = rs.getFloat("reserve_price");
153         qty = rs.getInt("quantity");
154         sellerId = rs.getInt("seller");
155         
156         maxBid = rs.getFloat("max_bid");
157         nbOfBids = rs.getInt("nb_of_bids");
158         
159         PreparedStatement JavaDoc sellerStmt = null;
160         ResultSet JavaDoc sellerResult = null;
161         try
162         {
163           sellerStmt = conn.prepareStatement("SELECT nickname FROM users WHERE id=?");
164           sellerStmt.setInt(1, sellerId);
165           sellerResult = sellerStmt.executeQuery();
166           // Get the seller's name
167
if (sellerResult.first())
168             sellerName = sellerResult.getString("nickname");
169           sellerStmt.close(); // close statement
170
}
171         catch (SQLException JavaDoc e)
172         {
173           try
174           {
175             if (sellerStmt != null) sellerStmt.close(); // close statement
176
if (conn != null) conn.close();
177           }
178           catch (Exception JavaDoc ignore)
179           {
180           }
181           throw new RemoteException JavaDoc("Failed to execute Query for seller: " +e);
182         }
183       }
184
185       if (maxBid == 0)
186       {
187         firstBid = "none";
188         maxBid = initialPrice;
189         buyNow = rs.getFloat("buy_now");
190       }
191       else
192       {
193         if (qty > 1)
194         {
195           PreparedStatement JavaDoc bidStmt = null;
196           ResultSet JavaDoc bidResult = null;
197           try
198           {
199             /* Get the qty max first bids and parse bids in this order
200                until qty is reached. The bid that reaches qty is the
201                current minimum bid. */

202             bidStmt = conn.prepareStatement("SELECT bids.id, bids.qty, bids.bid FROM bids WHERE item_id=? ORDER BY bid DESC LIMIT ?");
203             bidStmt.setInt(1, itemId);
204             bidStmt.setInt(2, qty);
205             bidResult = bidStmt.executeQuery();
206           }
207           catch (SQLException JavaDoc e)
208           {
209             try
210             {
211               if (bidStmt != null) bidStmt.close(); // close statement
212
if (conn != null) conn.close();
213             }
214             catch (Exception JavaDoc ignore)
215             {
216             }
217           }
218
219           try
220           {
221             float bidValue;
222             int numberOfItems = 0;
223             while (bidResult.next())
224             {
225               bidValue = bidResult.getFloat("bid");
226               numberOfItems += bidResult.getInt("qty");
227               if (numberOfItems >= qty)
228               {
229                 maxBid = bidValue;
230                 break;
231               }
232             }
233             bidStmt.close(); // close statement
234
}
235           catch (Exception JavaDoc e)
236           {
237             try
238             {
239               if (stmt != null) stmt.close();
240               if (conn != null) conn.close();
241             }
242             catch (Exception JavaDoc ignore)
243             {
244             }
245             throw new RemoteException JavaDoc("Problem while computing current bid: "+e+"<br>");
246           }
247           Float JavaDoc foo = new Float JavaDoc(maxBid);
248           firstBid = foo.toString();
249         }
250       }
251       if (stmt != null) stmt.close();
252       if (conn != null) conn.close();
253      
254       if (userId>0)
255       {
256         html.append(printHTMLHighlighted("You are ready to bid on: "+itemName));
257       }
258       else
259       {
260         html.append(printHTMLHighlighted(itemName));
261       }
262       html.append("<TABLE>\n"+
263                   "<TR><TD>Currently<TD><b><BIG>"+maxBid+"</BIG></b>\n");
264       // Check if the reservePrice has been met (if any)
265
if (reservePrice > 0)
266       { // Has the reserve price been met ?
267
if (maxBid >= reservePrice)
268           html.append("(The reserve price has been met)\n");
269         else
270           html.append("(The reserve price has NOT been met)\n");
271       }
272       html.append("<TR><TD>Quantity<TD><b><BIG>"+qty+"</BIG></b>\n"+
273                   "<TR><TD>First bid<TD><b><BIG>"+firstBid+"</BIG></b>\n"+
274                   "<TR><TD># of bids<TD><b><BIG>"+nbOfBids+"</BIG></b> (<a HREF=\""+BeanConfig.context+"/servlet/edu.rice.rubis.beans.servlets.ViewBidHistory?itemId="+itemId+"\">bid history</a>)\n"+
275                   "<TR><TD>Seller<TD><a HREF=\""+BeanConfig.context+"/servlet/edu.rice.rubis.beans.servlets.ViewUserInfo?userId="+sellerId+"\">"+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"+
276                   "<TR><TD>Started<TD>"+startDate+"\n"+
277                   "<TR><TD>Ends<TD>"+endDate+"\n"+
278                   "</TABLE>");
279       // Can the user buy this item now ?
280
if (buyNow > 0)
281         html.append("<p><a HREF=\""+BeanConfig.context+"/servlet/edu.rice.rubis.beans.servlets.BuyNowAuth?itemId="+itemId+"\">"+
282                     "<IMG SRC=\""+BeanConfig.context+"/buy_it_now.jpg\" height=22 width=150></a>"+
283                     " <BIG><b>You can buy this item right now for only $"+buyNow+"</b></BIG><br><p>\n");
284
285       if (userId<=0)
286       {
287         html.append("<a HREF=\""+BeanConfig.context+"/servlet/edu.rice.rubis.beans.servlets.PutBidAuth?itemId="+itemId+"\"><IMG SRC=\""+BeanConfig.context+"/bid_now.jpg\" height=22 width=90> on this item</a>\n");
288       }
289
290       html.append(printHTMLHighlighted("Item description"));
291       html.append(description);
292       html.append("<br><p>\n");
293
294       if (userId>0)
295       {
296         html.append(printHTMLHighlighted("Bidding"));
297         float minBid = maxBid+1;
298         html.append("<form action=\""+BeanConfig.context+"/servlet/edu.rice.rubis.beans.servlets.StoreBid\" method=POST>\n"+
299                   "<input type=hidden name=minBid value="+minBid+">\n"+
300                   "<input type=hidden name=userId value="+userId+">\n"+
301                   "<input type=hidden name=itemId value="+itemId+">\n"+
302                   "<input type=hidden name=maxQty value="+qty+">\n"+
303                   "<center><table>\n"+
304                   "<tr><td>Your bid (minimum bid is "+minBid+"):</td>\n"+
305                   "<td><input type=text size=10 name=bid></td></tr>\n"+
306                   "<tr><td>Your maximum bid:</td>\n"+
307                   "<td><input type=text size=10 name=maxBid></td></tr>\n");
308         if (qty > 1)
309           html.append("<tr><td>Quantity:</td>\n"+
310                     "<td><input type=text size=5 name=qty></td></tr>\n");
311         else
312           html.append("<input type=hidden name=qty value=1>\n");
313         html.append("</table><p><input type=submit value=\"Bid now!\"></center><p>\n");
314       }
315     }
316     catch (Exception JavaDoc e)
317     {
318       throw new RemoteException JavaDoc("Unable to print Item description (exception: "+e+")<br>\n");
319     }
320     return html.toString();
321   }
322
323   /**
324    * Construct a html highlighted string.
325    * @param msg the message to display
326    * @return a string in html format
327    * @since 1.1
328    */

329   public String JavaDoc printHTMLHighlighted(String JavaDoc msg)
330   {
331     return "<TABLE width=\"100%\" bgcolor=\"#CCCCFF\">\n<TR><TD align=\"center\" width=\"100%\"><FONT size=\"4\" color=\"#000000\"><B>"+msg+"</B></FONT></TD></TR>\n</TABLE><p>\n";
332   }
333
334
335   // ======================== EJB related methods ============================
336

337   /**
338    * Set the associated context. The container call this method
339    * after the instance creation.
340    * The enterprise Bean instance should store the reference to the context
341    * object in an instance variable.
342    * This method is called with no transaction context.
343    *
344    * @param MessageDrivenContext A MessageDrivenContext interface for the instance.
345    * @throws EJBException Thrown by the method to indicate a failure caused by
346    * a system-level error.
347    */

348   public void setMessageDrivenContext(MessageDrivenContext JavaDoc ctx)
349   {
350     messageDrivenContext = ctx;
351     if (dataSource == null)
352     {
353       // Finds DataSource from JNDI
354
try
355       {
356         initialContext = new InitialContext JavaDoc();
357         dataSource = (DataSource JavaDoc)initialContext.lookup("java:comp/env/jdbc/rubis");
358       }
359       catch (Exception JavaDoc e)
360       {
361         throw new EJBException JavaDoc("Cannot get JNDI InitialContext");
362       }
363     }
364   }
365
366   /**
367    * The Message driven bean must define an ejbCreate methods with no args.
368    *
369    */

370   public void ejbCreate()
371   {
372
373   }
374  
375   /**
376    * A container invokes this method before it ends the life of the message-driven object.
377    * This happens when a container decides to terminate the message-driven object.
378    *
379    * This method is called with no transaction context.
380    *
381    * @throws EJBException Thrown by the method to indicate a failure caused by
382    * a system-level error.
383    */

384   public void ejbRemove() {}
385  
386
387
388 }
389
Popular Tags